<commit_before>$(function () {
    $(".config-editor .message").slideDown().delay(5000).slideUp();

    $("button.base64").click(function () {
        var self = $(this);
        var url = cryptoRandomUrl;
        var target = self.data("base64target");
        $.ajax({
            url: url, cache: false
            success: function (result) {
                $("#" + target).val(result);
            }
        });
    });
});
<commit_msg>IE cached ajax response as noted in Issue 422 Update<commit_after>$(function () {
    $(".config-editor .message").slideDown().delay(5000).slideUp();

    $("button.base64").click(function () {
        var self = $(this);
        var url = cryptoRandomUrl;
        var target = self.data("base64target");
        $.ajax({
            url: url, cache: false,
            success: function (result) {
                $("#" + target).val(result);
            }
        });
    });
});
<|endoftext|>


<commit_before>// obj_diff API tests
//
// Copyright 2011 Iris Couch
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

var test = require('tap').test
  , obj_diff = require('../api')
  ;

test('Diff objects', function(t) {
  go({}, {}, {})
  go({a:1}, {a:1}, {})
  go({}, {foo:'bar'}, {foo: {from:undefined, to:'bar'}})
  go({foo:'bar'}, {}, {foo: {from:'bar', to:undefined}})
  go({a:1}, {a:"1"}, {a: {from:1, to:"1"}})
  go({a:1}, {b:1}, {a: {from:1, to:undefined}, b: {from:undefined, to:1}})
  go({}, {obj:{hi:true}}, {obj: {from:undefined, to:{hi:true}}})
  go({first:{second:{value:false}}}, {first:{second:{value:true}}}, {first:{second:{value:{from:false, to:true}}}})

  t.end();

  function go(a, b, expected) {
    var diff = obj_diff(a, b);

    var message = [ "from="   + JSON.stringify(a)
                  , "to="     + JSON.stringify(b)
                  , "expect=" + JSON.stringify(expected)
                  ].join(' ');

    t.same(diff, expected, message);
  }
})
<commit_msg>Refactor the tester function to a metafunction<commit_after>// obj_diff API tests
//
// Copyright 2011 Iris Couch
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

var test = require('tap').test
  , obj_diff = require('../api')
  ;

function make_tester(t) {
  return go;
  function go(a, b, expected) {
    var diff = obj_diff(a, b);

    var message = [ "from="   + JSON.stringify(a)
                  , "to="     + JSON.stringify(b)
                  , "expect=" + JSON.stringify(expected)
                  ].join(' ');

    t.same(diff, expected, message);
  }
}

test('Diff objects', function(t) {
  var go = make_tester(t);

  go({}, {}, {})
  go({a:1}, {a:1}, {})
  go({}, {foo:'bar'}, {foo: {from:undefined, to:'bar'}})
  go({foo:'bar'}, {}, {foo: {from:'bar', to:undefined}})
  go({a:1}, {a:"1"}, {a: {from:1, to:"1"}})
  go({a:1}, {b:1}, {a: {from:1, to:undefined}, b: {from:undefined, to:1}})
  go({}, {obj:{hi:true}}, {obj: {from:undefined, to:{hi:true}}})
  go({first:{second:{value:false}}}, {first:{second:{value:true}}}, {first:{second:{value:{from:false, to:true}}}})

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


<commit_before>var net = require('net');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');
var ltx = require('ltx');
var StreamParser = require('./stream_parser');
var starttls = require('../starttls');

var NS_XMPP_TLS = exports.NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls';
var NS_STREAM = exports.NS_STREAM = 'http://etherx.jabber.org/streams';
var NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams';

/**
 Base class for connection-based streams.

 The socket parameter is optional for incoming connections.

 A note on events: this base class will emit 'rawStanza' and leaves
 'stanza' to Client & Component. Therefore we won't confuse the
 user with stanzas before authentication has finished.
*/

function Connection(socket) {
    var self = this;
    EventEmitter.call(this);

    this.charset = 'UTF-8';
    this.xmlns = { stream: NS_STREAM };

    this.socket = socket || new net.Stream();
    this.socket.addListener('data', function(data) {
        self.onData(data);
    });
    this.socket.addListener('end', function() {
        self.onEnd();
    });
    var proxyEvent = function(event) {
        self.socket.addListener(event, function() {
	    var args = Array.prototype.slice.call(arguments);
	    args.unshift(event);
	    self.emit.apply(self, args);
        });
    };
    proxyEvent('data');  // let them sniff
    proxyEvent('drain');
    proxyEvent('close');

    this.mixins = [];
}

sys.inherits(Connection, EventEmitter);
exports.Connection = Connection;

// Defaults
Connection.prototype.charset = 'UTF-8';
Connection.prototype.allowTLS = true;

/** Climbs the stanza up if a child was passed,
    but you can send strings and buffers too.
*/
Connection.prototype.send = function(stanza) {
    if (!this.socket.writable) {
        this.socket.end();
        return;
    }

    if (stanza.root) {
        var el = this.rmStreamNs(stanza.root());
        var socket = this.socket;
        el.write(function(s) { socket.write(s); });
        return el;
    } else {
        this.socket.write(stanza);
        return stanza;
    }
};

Connection.prototype.startParser = function() {
    var self = this;
    this.parser = new StreamParser.StreamParser(this.charset, this.maxStanzaSize);

    this.parser.addListener('start', function(attrs) {
        self.streamAttrs = attrs;
        /* We need those xmlns often, store them extra */
        self.streamNsAttrs = {};
        for(var k in attrs) {
        if (k == 'xmlns' ||
            k.substr(0, 6) == 'xmlns:')
                self.streamNsAttrs[k] = attrs[k];
        }

        /* Notify in case we don't wait for <stream:features/>
           (Component or non-1.0 streams)
         */
        self.emit('streamStart', attrs);
    });
    this.parser.addListener('stanza', function(stanza) {
        self.onStanza(self.addStreamNs(stanza));
    });
    this.parser.addListener('error', function(e) {
        self.error(e.condition || 'internal-server-error', e.message);
    });
    this.parser.addListener('end', function() {
        self.stopParser();
        self.end();
    });
};

Connection.prototype.stopParser = function() {
    delete this.parser;
};

Connection.prototype.startStream = function() {
    var attrs = {};
    for(var k in this.xmlns) {
        if (this.xmlns.hasOwnProperty(k)) {
            if (!k)
                attrs.xmlns = this.xmlns[k];
            else
                attrs['xmlns:' + k] = this.xmlns[k];
        }
    }
    if (this.xmppVersion)
        attrs.version = this.xmppVersion;
    if (this.streamTo)
        attrs.to = this.streamTo;
    if (this.streamId)
        attrs.id = this.streamId;

    var el = new ltx.Element('stream:stream', attrs);
    // make it non-empty to cut the closing tag
    el.t(' ');
    var s = el.toString();
    this.send(s.substr(0, s.indexOf(' </stream:stream>')));

    this.streamOpened = true;
};

Connection.prototype.onData = function(data) {
    if (this.parser)
        this.parser.write(data);
};

Connection.prototype.setSecure = function(credentials) {
    var self = this;
    this.stopParser();

    // Remove old event listeners
    this.socket.removeAllListeners('data');
    this.socket.removeAllListeners('end');
    this.socket.removeAllListeners('drain');
    this.socket.removeAllListeners('close');

    var ct = starttls(this.socket, credentials || this.credentials, function() {
        self.startParser();
        self.startStream();
    });

    // The socket is now the cleartext stream
    this.socket = ct;

    // Attach new listeners on the cleartext stream
    this.socket.addListener('data', function(data) {
        self.onData(data);
    });
    this.socket.addListener('end', function() {
        self.onEnd();
    });

    var proxyEvent = function(event) {
        self.socket.addListener(event, function() {
            self.emit.apply(self, Array.prototype.splice.call(arguments, 0, 0, event));
        });
    };
    proxyEvent('data');  // let them sniff
    proxyEvent('drain');
    proxyEvent('close');
};

/**
 * This is not an event listener, but takes care of the TLS handshake
 * before 'rawStanza' events are emitted to the derived classes.
 */
Connection.prototype.onStanza = function(stanza) {
    if (stanza.is('error', NS_STREAM)) {
        /* TODO: extract error text */
        this.emit('error', stanza);
    } else if (stanza.is('features', NS_STREAM) &&
               this.allowTLS &&
               stanza.getChild('starttls', NS_XMPP_TLS)) {
        /* Signal willingness to perform TLS handshake */
        this.send(new ltx.Element('starttls', { xmlns: NS_XMPP_TLS }));
    } else if (this.allowTLS &&
               stanza.is('proceed', NS_XMPP_TLS)) {
        /* Server is waiting for TLS handshake */
        this.setSecure();
    } else {
        this.emit('rawStanza', stanza);
    }
};

/**
 *  Add stream xmlns to a stanza, so the user can check for
 * 'jabber:client' etc.
 */
Connection.prototype.addStreamNs = function(stanza) {
    for(var k in this.streamNsAttrs) {
        if (!stanza.attrs[k])
            stanza.attrs[k] = this.streamNsAttrs[k];
    }
    return stanza;
};

/**
 * Remove superfluous xmlns that were aleady declared in
 * our <stream:stream>
 */
Connection.prototype.rmStreamNs = function(stanza) {
    for(var k in this.xmlns) {
        var attr = k ? 'xmlns:' + k : 'xmlns';
        if (stanza.attrs[attr] == this.xmlns[k])
            delete stanza.attrs[attr];
    }
    return stanza;
};

/**
 * Connection has been ended by remote, we will not get any incoming
 * 'data' events. Alternatively, used for 'error' event.
 */
Connection.prototype.onEnd = function() {
    this.stopParser();
    this.socket.end();
};

/**
 * XMPP-style end connection for user
 */
Connection.prototype.end = function() {
    if (this.socket.writable) {
        if (this.streamOpened) {
            this.socket.write('</stream:stream>');
            delete this.streamOpened;
        } else {
            this.socket.end();
        }
    }
};

/**
 * End connection with stream error.
 * Emits 'error' event too.
 *
 * @param {String} condition XMPP error condition, see RFC3920 4.7.3. Defined Conditions
 * @param {String} text Optional error message
 */
Connection.prototype.error = function(condition, message) {
    this.emit('error', new Error(message));

    if (!this.socket.writable)
        return;

    var e = new ltx.Element('stream:error');
    e.c(condition, { xmlns: NS_XMPP_STREAMS });
    if (message)
        e.c('text', { xmlns: NS_XMPP_STREAMS,
                      'xml:lang': 'en' }).
        t(message);

    this.send(e);
    this.end();
};

/**
 * Adds a mixin to this Connection for implementing higher-level functionality.
 *
 * A mixin is a module that exports a single function, taking the
 * Connection as its value. The module can perform its own stanza-handling,
 * event emission and other functionality. Note that mixins can only be
 * added once.
*/
Connection.prototype.addMixin = function(mixin, mixinArgs) {
    if(this.mixins.indexOf(mixin) == -1) {
        mixin(this, mixinArgs);
        this.mixins = this.mixins.concat(mixin);
    }
};
<commit_msg>connection: deduplicate code into setupStream()<commit_after>var net = require('net');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');
var ltx = require('ltx');
var StreamParser = require('./stream_parser');
var starttls = require('../starttls');

var NS_XMPP_TLS = exports.NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls';
var NS_STREAM = exports.NS_STREAM = 'http://etherx.jabber.org/streams';
var NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams';

/**
 Base class for connection-based streams.

 The socket parameter is optional for incoming connections.

 A note on events: this base class will emit 'rawStanza' and leaves
 'stanza' to Client & Component. Therefore we won't confuse the
 user with stanzas before authentication has finished.
*/

function Connection(socket) {
    EventEmitter.call(this);

    this.charset = 'UTF-8';
    this.xmlns = { stream: NS_STREAM };

    this.socket = socket || new net.Stream();
    this.setupStream();

    this.mixins = [];
}

sys.inherits(Connection, EventEmitter);
exports.Connection = Connection;

// Defaults
Connection.prototype.charset = 'UTF-8';
Connection.prototype.allowTLS = true;

/**
 Used by both the constructor and by reinitialization in setSecure().
*/
Connection.prototype.setupStream = function() {
    var self = this;
    this.socket.addListener('data', function(data) {
        self.onData(data);
    });
    this.socket.addListener('end', function() {
        self.onEnd();
    });
    var proxyEvent = function(event) {
        self.socket.addListener(event, function() {
	    var args = Array.prototype.slice.call(arguments);
	    args.unshift(event);
	    self.emit.apply(self, args);
        });
    };
    proxyEvent('data');  // let them sniff unparsed XML
    proxyEvent('drain');
    proxyEvent('close');
};

/** Climbs the stanza up if a child was passed,
    but you can send strings and buffers too.
*/
Connection.prototype.send = function(stanza) {
    if (!this.socket.writable) {
        this.socket.end();
        return;
    }

    if (stanza.root) {
        var el = this.rmStreamNs(stanza.root());
        var socket = this.socket;
        el.write(function(s) { socket.write(s); });
        return el;
    } else {
        this.socket.write(stanza);
        return stanza;
    }
};

Connection.prototype.startParser = function() {
    var self = this;
    this.parser = new StreamParser.StreamParser(this.charset, this.maxStanzaSize);

    this.parser.addListener('start', function(attrs) {
        self.streamAttrs = attrs;
        /* We need those xmlns often, store them extra */
        self.streamNsAttrs = {};
        for(var k in attrs) {
        if (k == 'xmlns' ||
            k.substr(0, 6) == 'xmlns:')
                self.streamNsAttrs[k] = attrs[k];
        }

        /* Notify in case we don't wait for <stream:features/>
           (Component or non-1.0 streams)
         */
        self.emit('streamStart', attrs);
    });
    this.parser.addListener('stanza', function(stanza) {
        self.onStanza(self.addStreamNs(stanza));
    });
    this.parser.addListener('error', function(e) {
        self.error(e.condition || 'internal-server-error', e.message);
    });
    this.parser.addListener('end', function() {
        self.stopParser();
        self.end();
    });
};

Connection.prototype.stopParser = function() {
    delete this.parser;
};

Connection.prototype.startStream = function() {
    var attrs = {};
    for(var k in this.xmlns) {
        if (this.xmlns.hasOwnProperty(k)) {
            if (!k)
                attrs.xmlns = this.xmlns[k];
            else
                attrs['xmlns:' + k] = this.xmlns[k];
        }
    }
    if (this.xmppVersion)
        attrs.version = this.xmppVersion;
    if (this.streamTo)
        attrs.to = this.streamTo;
    if (this.streamId)
        attrs.id = this.streamId;

    var el = new ltx.Element('stream:stream', attrs);
    // make it non-empty to cut the closing tag
    el.t(' ');
    var s = el.toString();
    this.send(s.substr(0, s.indexOf(' </stream:stream>')));

    this.streamOpened = true;
};

Connection.prototype.onData = function(data) {
    if (this.parser)
        this.parser.write(data);
};

Connection.prototype.setSecure = function(credentials) {
    var self = this;
    this.stopParser();

    // Remove old event listeners
    this.socket.removeAllListeners('data');
    this.socket.removeAllListeners('end');
    this.socket.removeAllListeners('drain');
    this.socket.removeAllListeners('close');

    var ct = starttls(this.socket, credentials || this.credentials, function() {
        self.startParser();
        self.startStream();
    });

    // The socket is now the cleartext stream
    this.socket = ct;

    // Attach new listeners on the cleartext stream
    this.setupStream();
};

/**
 * This is not an event listener, but takes care of the TLS handshake
 * before 'rawStanza' events are emitted to the derived classes.
 */
Connection.prototype.onStanza = function(stanza) {
    if (stanza.is('error', NS_STREAM)) {
        /* TODO: extract error text */
        this.emit('error', stanza);
    } else if (stanza.is('features', NS_STREAM) &&
               this.allowTLS &&
               stanza.getChild('starttls', NS_XMPP_TLS)) {
        /* Signal willingness to perform TLS handshake */
        this.send(new ltx.Element('starttls', { xmlns: NS_XMPP_TLS }));
    } else if (this.allowTLS &&
               stanza.is('proceed', NS_XMPP_TLS)) {
        /* Server is waiting for TLS handshake */
        this.setSecure();
    } else {
        this.emit('rawStanza', stanza);
    }
};

/**
 *  Add stream xmlns to a stanza, so the user can check for
 * 'jabber:client' etc.
 */
Connection.prototype.addStreamNs = function(stanza) {
    for(var k in this.streamNsAttrs) {
        if (!stanza.attrs[k])
            stanza.attrs[k] = this.streamNsAttrs[k];
    }
    return stanza;
};

/**
 * Remove superfluous xmlns that were aleady declared in
 * our <stream:stream>
 */
Connection.prototype.rmStreamNs = function(stanza) {
    for(var k in this.xmlns) {
        var attr = k ? 'xmlns:' + k : 'xmlns';
        if (stanza.attrs[attr] == this.xmlns[k])
            delete stanza.attrs[attr];
    }
    return stanza;
};

/**
 * Connection has been ended by remote, we will not get any incoming
 * 'data' events. Alternatively, used for 'error' event.
 */
Connection.prototype.onEnd = function() {
    this.stopParser();
    this.socket.end();
};

/**
 * XMPP-style end connection for user
 */
Connection.prototype.end = function() {
    if (this.socket.writable) {
        if (this.streamOpened) {
            this.socket.write('</stream:stream>');
            delete this.streamOpened;
        } else {
            this.socket.end();
        }
    }
};

/**
 * End connection with stream error.
 * Emits 'error' event too.
 *
 * @param {String} condition XMPP error condition, see RFC3920 4.7.3. Defined Conditions
 * @param {String} text Optional error message
 */
Connection.prototype.error = function(condition, message) {
    this.emit('error', new Error(message));

    if (!this.socket.writable)
        return;

    var e = new ltx.Element('stream:error');
    e.c(condition, { xmlns: NS_XMPP_STREAMS });
    if (message)
        e.c('text', { xmlns: NS_XMPP_STREAMS,
                      'xml:lang': 'en' }).
        t(message);

    this.send(e);
    this.end();
};

/**
 * Adds a mixin to this Connection for implementing higher-level functionality.
 *
 * A mixin is a module that exports a single function, taking the
 * Connection as its value. The module can perform its own stanza-handling,
 * event emission and other functionality. Note that mixins can only be
 * added once.
*/
Connection.prototype.addMixin = function(mixin, mixinArgs) {
    if(this.mixins.indexOf(mixin) == -1) {
        mixin(this, mixinArgs);
        this.mixins = this.mixins.concat(mixin);
    }
};
<|endoftext|>


<commit_before>// Copyright 2016 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE
'use strict';

module.exports = {
  prepareData
};

function prepareData(res) {
  const audits = res.audits;

  const resSW = audits['service-worker'];

  const resFMP = audits['first-meaningful-paint'];
  const resFMPext = resFMP.extendedInfo;

  const resTTI = audits['time-to-interactive'];
  const resTTIext = resTTI && resTTI.extendedInfo;

  const preparedResults = [
    {
      title: 'Service Worker',
      name: 'sw',
      value: resSW && resSW.rawValue
    },
    {
      title: 'First Contentful Paint',
      name: 'ttfcp',
      value: resFMPext && resFMPext.value.timings.fCP
    },
    {
      title: 'First Meaningful Paint',
      name: 'ttfmp',
      value: resFMP && resFMP.rawValue
    },
    {
      title: 'Time to Interactive',
      name: 'tti',
      value: resTTI && resTTI.rawValue
    },
    {
      title: 'Visually Complete 85%',
      name: 'vc85',
      value: resTTIext && parseFloat(resTTIext.value.timings.visuallyReady)
    }
  ];

  return {
    preparedResults,
    generatedTime: res.generatedTime,
    lighthouseVersion: res.lighthouseVersion,
    initialUrl: res.initialUrl,
    url: res.url
  };
}<commit_msg>Removes the metrics.js file which is not used anymore (though we might use it in the future if necessary)<commit_after><|endoftext|>


<commit_before>import React from 'react';

let SearchBox = React.createClass({

    getInitialState() {
        return {
            value: ''
        }
    },

    componentDidMount() {
        this.refs.searchBox.getDOMNode().focus();
    },

    keyDown(event) {
        console.info('SearchBox.keyDown');
        let keys = [13,27,38,39,40];
        if (keys.indexOf(event.keyCode) !== -1) {
            this.props.handleSpecial(event.keyCode);
        }
    },

    handleChange(event) {
        console.info('SearchBox.handleChange', event.target.value);
        this.setState({
            value: event.target.value
        });
        let keys = [13,27,38,39,40];
        if (keys.indexOf(event.keyCode) === -1) {
            let inputtedTerm = this.refs.searchBox.getDOMNode().value;
            this.props.handleTerm(inputtedTerm);
        }
    },

    render() {
        console.info('SearchBox.render');
        return <input ref="searchBox"
            className="SearchBox"
            onKeyDown={this.keyDown}
            onChange={this.handleChange}
            value={this.props.displayTerm} />
    }
});

module.exports = SearchBox;<commit_msg>remove state<commit_after>import React from 'react';

let SearchBox = React.createClass({

    componentDidMount() {
        this.refs.searchBox.getDOMNode().focus();
    },

    keyDown(event) {
        console.info('SearchBox.keyDown');
        let keys = [13,27,38,39,40];
        if (keys.indexOf(event.keyCode) !== -1) {
            this.props.handleSpecial(event.keyCode);
        }
    },

    handleChange(event) {
        console.info('SearchBox.handleChange', event.target.value);
        let keys = [13,27,38,39,40];
        if (keys.indexOf(event.keyCode) === -1) {
            let inputtedTerm = this.refs.searchBox.getDOMNode().value;
            this.props.handleTerm(inputtedTerm);
        }
    },

    render() {
        console.info('SearchBox.render');
        return <input ref="searchBox"
            className="SearchBox"
            onKeyDown={this.keyDown}
            onChange={this.handleChange}
            value={this.props.displayTerm} />
    }
});

module.exports = SearchBox;<|endoftext|>


<commit_before>
var DOMAIN = 'https://heka.house';
var ACCOUNT_ENDPOINT = ',system/newAccount';
var CERT_ENDPOINT = ',system/newCert';

var accURL = {};

function init() {
	var parser = document.createElement('a');
	parser.href = DOMAIN;
	accURL.host = parser.host + '/'; // => "example.com"
	accURL.path = parser.pathname; // => "/pathname/"
	accURL.schema = parser.protocol + '//';
}

init();

var makeURI = function(username) {
  if (username.length > 0) {
    return accURL.schema + username + '.' + accURL.host;
  }
  return null;
}

var makeHost = function(username) {
  if (username.length > 0) {
    return username + '.' + accURL.host;
  }
  return null;
}

var requestPersona = function(persona,cb) {

	if (persona.indexOf('-') === 0) {
		persona = persona.slice(1);
	}
	if (persona.lastIndexOf('-') === persona.length - 1) {
		persona = persona.slice(0, -1)
	}

	if (persona.length > 0) {
		// var mrp = require('minimal-request-promise');
		// options = {
		//     method: 'HEAD',
		//     hostname: makeURI(persona),
		//     path: '/',
		//     port: 443,
		//     headers: {},
		//     body: ''
		// };
		// return mrp(options).then(
		//   function (response) {
		//     return response.statusCode;
		//   },
		//   function (response) {
		//   	if (response.statusCode === undefined) {
		//   		return '999';
		//   	}
		//     return response.statusCode;
		//   }
		// );
		var url = makeURI(persona,function(status){
			console.log('status',status);
		});
		var http = new XMLHttpRequest();
		http.open('HEAD', makeURI(persona));
		http.onreadystatechange = function() {
		  console.log(this.status)
		    if (this.readyState == this.DONE) {
		      if (this.status === 0) {
		      	console.log('not connected');
		        cb('999');
		      } else if (this.status === 404) {
		        cb('404');
		      } else {
		        cb(this.status);
		      }
		    }
		};
		http.send();
	}

};

var createAccount = function(account,email,cb) {
	if (account.length > 0) {
		generateRSAKeyPair()
		.then(function(keyPair){
			storeKeys(keyPair);
			return generateCSR(keyPair,db,definePersonaCSR(account));
		})
		.then(function(csr){
			storeKeyValue(db,'csr',csr);
			certified.verifyCSR(csr)
			.then(function(verified){
				console.log(verified);
				if (verified) {
					certified.parseCSR(csr)
					.then(function(csrStruct){
						return JSON.stringify(csrStruct);
					})
					.then(function(csrStr){
						var url = makeURI(account) + ACCOUNT_ENDPOINT;
						var data = {"username":account,"email":email,"csr":csr};
						var http = new XMLHttpRequest();
						http.open('POST', url);
						http.withCredentials = true;
						http.setRequestHeader("Content-Type", "application/json");
						http.onreadystatechange = function() {
						    if (this.readyState == this.DONE) {
						      if (this.status === 200) {
						      	var account = JSON.parse(newAccount);
								console.log(account.created);
								console.log(account.secure.cert);
								certified.verifyCSR(csr)
								.then(function(verified){
									console.log("verified",verified);
									cb(this.responseText);
								});

						      } else {
						        console.log('Error creating account at '+url);
						      }
						    }
						};
						http.send(JSON.stringify(data));
						//document.querySelector("#spkacWebID").value = csrStr;
					});
				}
			});
		});

	}
};

window.requestPersona = requestPersona;

window.createAccount = createAccount;<commit_msg>completing registration<commit_after>
var DOMAIN = 'https://heka.house';
var ACCOUNT_ENDPOINT = ',system/newAccount';
var CERT_ENDPOINT = ',system/newCert';

var accURL = {};

function init() {
	var parser = document.createElement('a');
	parser.href = DOMAIN;
	accURL.host = parser.host + '/'; // => "example.com"
	accURL.path = parser.pathname; // => "/pathname/"
	accURL.schema = parser.protocol + '//';
}

init();

var makeURI = function(username) {
  if (username.length > 0) {
    return accURL.schema + username + '.' + accURL.host;
  }
  return null;
}

var makeHost = function(username) {
  if (username.length > 0) {
    return username + '.' + accURL.host;
  }
  return null;
}

var requestPersona = function(persona,cb) {

	if (persona.indexOf('-') === 0) {
		persona = persona.slice(1);
	}
	if (persona.lastIndexOf('-') === persona.length - 1) {
		persona = persona.slice(0, -1)
	}

	if (persona.length > 0) {
		// var mrp = require('minimal-request-promise');
		// options = {
		//     method: 'HEAD',
		//     hostname: makeURI(persona),
		//     path: '/',
		//     port: 443,
		//     headers: {},
		//     body: ''
		// };
		// return mrp(options).then(
		//   function (response) {
		//     return response.statusCode;
		//   },
		//   function (response) {
		//   	if (response.statusCode === undefined) {
		//   		return '999';
		//   	}
		//     return response.statusCode;
		//   }
		// );
		var url = makeURI(persona,function(status){
			console.log('status',status);
		});
		var http = new XMLHttpRequest();
		http.open('HEAD', makeURI(persona));
		http.onreadystatechange = function() {
		  console.log(this.status)
		    if (this.readyState == this.DONE) {
		      if (this.status === 0) {
		      	console.log('not connected');
		        cb('999');
		      } else if (this.status === 404) {
		        cb('404');
		      } else {
		        cb(this.status);
		      }
		    }
		};
		http.send();
	}

};

var createAccount = function(account,email,cb) {
	if (account.length > 0) {
		generateRSAKeyPair()
		.then(function(keyPair){
			storeKeys(keyPair);
			return generateCSR(keyPair,db,definePersonaCSR(account));
		})
		.then(function(csr){
			storeKeyValue(db,'csr',csr);
			certified.verifyCSR(csr)
			.then(function(verified){
				console.log(verified);
				if (verified) {
					certified.parseCSR(csr)
					.then(function(csrStruct){
						return JSON.stringify(csrStruct);
					})
					.then(function(csrStr){
						var url = makeURI(account) + ACCOUNT_ENDPOINT;
						var data = {"username":account,"email":email,"csr":csr};
						var http = new XMLHttpRequest();
						http.open('POST', url);
						http.withCredentials = true;
						http.setRequestHeader("Content-Type", "application/json");
						http.onreadystatechange = function() {
						    if (this.readyState == this.DONE) {
						      if (this.status === 200) {
						      	var account = JSON.parse(this.responseText);
								console.log(account.created);
								console.log(account.secure.cert);
								certified.verifyCSR(csr)
								.then(function(verified){
									console.log("verified",verified);
									cb(account);
								});

						      } else {
						        console.log('Error creating account at '+url);
						      }
						    }
						};
						http.send(JSON.stringify(data));
						//document.querySelector("#spkacWebID").value = csrStr;
					});
				}
			});
		});

	}
};

window.requestPersona = requestPersona;

window.createAccount = createAccount;<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
var path = require('path')
var child_process = require('child_process')
var stdin = require('stdin')
var pkg = require('../package.json')
var stylefmt = require('../')

var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
  boolean: [
    'help',
    'version'
  ],
  alias: {
    h: 'help',
    v: 'version',
    d: 'diff',
    l: 'list',
    R: 'recursive',
    b: 'config-basedir',
    c: 'config'
  }
})

var tmp = require('tmp')
var postcss = require('postcss')
var scss = require('postcss-scss')

if (argv.v) {
  console.log(pkg.version)
  process.exit()
}

if (argv.h) {
  console.log('Usage: stylefmt [options] input-name [output-name]')
  console.log('')
  console.log('Options:')
  console.log('')
  console.log('  -d, --diff             output diff against original file')
  console.log('  -l, --list             format list of space seperated files in place')
  console.log('  -R, --recursive        format files recursively')
  console.log('  -c, --config           path to a specific configuration file (JSON, YAML, or CommonJS)')
  console.log('  -b, --config-basedir   path to the directory that relative paths defining "extends"')
  console.log('  -v, --version          output the version number')
  console.log('  -h, --help             output usage information')
  process.exit()
}

var options ={}
if (argv.c) {
  options.configFile = argv.c
}

if (argv.b) {
  options.configBasedir = (path.isAbsolute(argv.b))
    ? argv.b
    : path.resolve(process.cwd(), argv.b)
}

if (argv.l) {
  var files = [argv.l].concat(argv._)
  processMultipleFiles(files)
} else if (argv._[0]) {
  var input = argv._[0]
  var output = argv._[1] || argv._[0]

  var css = fs.readFileSync(input, 'utf-8')

  postcss([stylefmt(options)])
    .process(css, { syntax: scss })
    .then(function (result) {
      var formatted = result.css
      if (argv.d) {
        var fullPath = path.resolve(process.cwd(), input)
        handleDiff(fullPath, input, formatted)
      } else {
        if (css !== formatted) {
          fs.writeFile(output, formatted, function (err) {
            if (err) {
              throw err
            }
          })
        }
      }
    })
} else if (argv.R) {
  var recursive = require('recursive-readdir')

  recursive(argv.R, function (err, files) {
    processMultipleFiles(files)
  })
} else {
  stdin(function (css) {
    postcss([stylefmt(options)])
      .process(css, { syntax: scss })
      .then(function (result) {
        process.stdout.write(result.css)
      })
  })
}

function processMultipleFiles (files) {
  files.forEach(function (file) {
    var fullPath = path.resolve(process.cwd(), file)
    if (!isCss(fullPath)) {
      return
    }

    var css = fs.readFileSync(fullPath, 'utf-8')

    postcss([stylefmt(options)])
      .process(css, { syntax: scss })
      .then(function (result) {
        var formatted = result.css
        if (css !== formatted) {
          fs.writeFile(fullPath, formatted, function (err) {
            if (err) {
              throw err
            }
          })
        }
      })
  })
}

function isCss (filePath) {
  return /^\.css|\.scss$/i.test(path.extname(filePath))
}

function diff (pathA, pathB, callback) {
  child_process.exec([
    'git', 'diff', '--ignore-space-at-eol', '--no-index', '--', pathA, pathB
  ].join(' '), callback)
}

function handleDiff (fullPath, original, formatted) {
  tmp.file(function (err, tmpPath, fd) {
    if (err) {
      console.error(err)
      return
    }

    fs.writeSync(fd, formatted, function (err) {
      if (err) {
        throw err;
      }

      diff(fullPath, tmpPath, function (err, stdout, stderr) {
        if (stdout) {
          console.log(stdout);
        }
        if (stderr) {
          console.error(stderr);
        }
      })
    })
  })
}
<commit_msg>Fixed: `config` option to CLI<commit_after>#!/usr/bin/env node

var fs = require('fs')
var path = require('path')
var child_process = require('child_process')
var stdin = require('stdin')
var resolveFrom = require('resolve-from')
var pkg = require('../package.json')
var stylefmt = require('../')

var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
  boolean: [
    'help',
    'version'
  ],
  alias: {
    h: 'help',
    v: 'version',
    d: 'diff',
    l: 'list',
    R: 'recursive',
    b: 'config-basedir',
    c: 'config'
  }
})

var tmp = require('tmp')
var postcss = require('postcss')
var scss = require('postcss-scss')

if (argv.v) {
  console.log(pkg.version)
  process.exit()
}

if (argv.h) {
  console.log('Usage: stylefmt [options] input-name [output-name]')
  console.log('')
  console.log('Options:')
  console.log('')
  console.log('  -d, --diff             output diff against original file')
  console.log('  -l, --list             format list of space seperated files in place')
  console.log('  -R, --recursive        format files recursively')
  console.log('  -c, --config           path to a specific configuration file (JSON, YAML, or CommonJS)')
  console.log('  -b, --config-basedir   path to the directory that relative paths defining "extends"')
  console.log('  -v, --version          output the version number')
  console.log('  -h, --help             output usage information')
  process.exit()
}

var options ={}
if (argv.c) {
  // Should check these possibilities:
  //   a. name of a node_module
  //   b. absolute path
  //   c. relative path relative to `process.cwd()`.
  // If none of the above work, we'll try a relative path starting
  // in `process.cwd()`.
  options.configFile = resolveFrom(process.cwd(), argv.c)
    || path.join(process.cwd(), argv.c)
}

if (argv.b) {
  options.configBasedir = (path.isAbsolute(argv.b))
    ? argv.b
    : path.resolve(process.cwd(), argv.b)
}

if (argv.l) {
  var files = [argv.l].concat(argv._)
  processMultipleFiles(files)
} else if (argv._[0]) {
  var input = argv._[0]
  var output = argv._[1] || argv._[0]

  var css = fs.readFileSync(input, 'utf-8')

  postcss([stylefmt(options)])
    .process(css, { syntax: scss })
    .then(function (result) {
      var formatted = result.css
      if (argv.d) {
        var fullPath = path.resolve(process.cwd(), input)
        handleDiff(fullPath, input, formatted)
      } else {
        if (css !== formatted) {
          fs.writeFile(output, formatted, function (err) {
            if (err) {
              throw err
            }
          })
        }
      }
    })
} else if (argv.R) {
  var recursive = require('recursive-readdir')

  recursive(argv.R, function (err, files) {
    processMultipleFiles(files)
  })
} else {
  stdin(function (css) {
    postcss([stylefmt(options)])
      .process(css, { syntax: scss })
      .then(function (result) {
        process.stdout.write(result.css)
      })
  })
}

function processMultipleFiles (files) {
  files.forEach(function (file) {
    var fullPath = path.resolve(process.cwd(), file)
    if (!isCss(fullPath)) {
      return
    }

    var css = fs.readFileSync(fullPath, 'utf-8')

    postcss([stylefmt(options)])
      .process(css, { syntax: scss })
      .then(function (result) {
        var formatted = result.css
        if (css !== formatted) {
          fs.writeFile(fullPath, formatted, function (err) {
            if (err) {
              throw err
            }
          })
        }
      })
  })
}

function isCss (filePath) {
  return /^\.css|\.scss$/i.test(path.extname(filePath))
}

function diff (pathA, pathB, callback) {
  child_process.exec([
    'git', 'diff', '--ignore-space-at-eol', '--no-index', '--', pathA, pathB
  ].join(' '), callback)
}

function handleDiff (fullPath, original, formatted) {
  tmp.file(function (err, tmpPath, fd) {
    if (err) {
      console.error(err)
      return
    }

    fs.writeSync(fd, formatted, function (err) {
      if (err) {
        throw err;
      }

      diff(fullPath, tmpPath, function (err, stdout, stderr) {
        if (stdout) {
          console.log(stdout);
        }
        if (stderr) {
          console.error(stderr);
        }
      })
    })
  })
}
<|endoftext|>


<commit_before>var config    = require("./config/config")
  , Sequelize = require("../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, { logging: false })
  , Helpers   = new (require("./config/helpers"))(sequelize)
  , Migrator  = require("../lib/migrator")
  , _         = Sequelize.Utils._

describe('Migrator', function() {
  describe('getUndoneMigrations', function() {
    var migrator      = null
      , SequelizeMeta = null

    var setup = function(_options) {
      Helpers.async(function(done) {
        var options = Sequelize.Utils._.extend({
          path: __dirname + '/assets/migrations'
        }, _options || {})

        migrator = new Migrator(sequelize, options)
        migrator.findOrCreateSequelizeMetaModel({ force: true }).success(function(_SequelizeMeta) {
          SequelizeMeta = _SequelizeMeta
          done()
        })
      })
    }

    beforeEach(function() { migrator = null })

    // specs

    it("returns no files if timestamps are after the files timestamp", function() {
      setup({ from: 20120101010101 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(0)
          done()
        })
      })
    })

    it("returns only files between from and to", function() {
      setup({ from: 19700101000000, to: 20111117063700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(1)
          expect(_.last(migrations).filename).toEqual('20111117063700-createPerson.js')
          done()
        })
      })
    })

    it("returns also the file which is exactly options.from or options.to", function() {
      setup({ from: 20111117063700, to: 20111123060700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(2)
          expect(migrations[0].filename).toEqual('20111117063700-createPerson.js')
          expect(migrations[1].filename).toEqual('20111123060700-addBirthdateToPerson.js')
          done()
        })
      })
    })

    it("returns all files to options.to if no options.from is defined", function() {
      setup({ to: 20111123060700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(2)
          done()
        })
      })
    })

    it("returns all files from last migration id stored in database", function() {
      setup()

      Helpers.async(function(done) {
        SequelizeMeta.create({ lastMigrationId: '20111117063700' }).success(function() {
          migrator.getUndoneMigrations(function(migrations) {
            expect(migrations.length).toEqual(1)
            expect(migrations[0].filename).toEqual('20111123060700-addBirthdateToPerson.js')
            done()
          })
        })
      })
    })
  })

  describe('migrate', function() {
    afterEach(function() {
      Helpers.async(function(done) {
        sequelize.getQueryInterface()
          .dropAllTables()
          .success(done)
          .error(function(err) { console.log(err) })
      })
    })

    xit("should execute the specified migration (and e.g. create a file)", function() {
      var migrator = new Migrator(sequelize, {
        path: __dirname + '/assets/migrations',
        from: 20111117063700,
        to: 20111117063700
      })

      Helpers.async(function(done) {
        migrator.migrate().success(done).error(function(err) { console.log(err) })
      })

      Helpers.async(function(done) {
        sequelize.getQueryInterface().showAllTables(function(tableName) {
          expect(tableNames.length).toEqual(1)
          done()
        })
      })
    })
  })
})
<commit_msg>correct spec for migration execution<commit_after>var config    = require("./config/config")
  , Sequelize = require("../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, { logging: false })
  , Helpers   = new (require("./config/helpers"))(sequelize)
  , Migrator  = require("../lib/migrator")
  , _         = Sequelize.Utils._

describe('Migrator', function() {
  describe('getUndoneMigrations', function() {
    var migrator      = null
      , SequelizeMeta = null

    var setup = function(_options) {
      Helpers.async(function(done) {
        var options = Sequelize.Utils._.extend({
          path: __dirname + '/assets/migrations'
        }, _options || {})

        migrator = new Migrator(sequelize, options)
        migrator.findOrCreateSequelizeMetaModel({ force: true }).success(function(_SequelizeMeta) {
          SequelizeMeta = _SequelizeMeta
          done()
        })
      })
    }

    beforeEach(function() { migrator = null })

    // specs

    it("returns no files if timestamps are after the files timestamp", function() {
      setup({ from: 20120101010101 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(0)
          done()
        })
      })
    })

    it("returns only files between from and to", function() {
      setup({ from: 19700101000000, to: 20111117063700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(1)
          expect(_.last(migrations).filename).toEqual('20111117063700-createPerson.js')
          done()
        })
      })
    })

    it("returns also the file which is exactly options.from or options.to", function() {
      setup({ from: 20111117063700, to: 20111123060700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(2)
          expect(migrations[0].filename).toEqual('20111117063700-createPerson.js')
          expect(migrations[1].filename).toEqual('20111123060700-addBirthdateToPerson.js')
          done()
        })
      })
    })

    it("returns all files to options.to if no options.from is defined", function() {
      setup({ to: 20111123060700 })

      Helpers.async(function(done) {
        migrator.getUndoneMigrations(function(migrations) {
          expect(migrations.length).toEqual(2)
          done()
        })
      })
    })

    it("returns all files from last migration id stored in database", function() {
      setup()

      Helpers.async(function(done) {
        SequelizeMeta.create({ lastMigrationId: '20111117063700' }).success(function() {
          migrator.getUndoneMigrations(function(migrations) {
            expect(migrations.length).toEqual(1)
            expect(migrations[0].filename).toEqual('20111123060700-addBirthdateToPerson.js')
            done()
          })
        })
      })
    })
  })

  describe('migrate', function() {
    afterEach(function() {
      Helpers.async(function(done) {
        sequelize.getQueryInterface()
          .dropAllTables()
          .success(done)
          .error(function(err) { console.log(err) })
      })
    })

    it("should execute the specified migration (and e.g. create a file)", function() {
      var migrator = new Migrator(sequelize, {
        path: __dirname + '/assets/migrations',
        from: 20111117063700,
        to: 20111117063700
      })

      Helpers.async(function(done) {
        migrator.migrate().success(done).error(function(err) { console.log(err) })
      })

      Helpers.async(function(done) {
        sequelize.getQueryInterface().showAllTables().success(function(tableNames) {
          tableNames = tableNames.slice('SequelizeMeta', 1)
          expect(tableNames.length).toEqual(1)
          expect(tableNames[0]).toEqual('Person')
          done()
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>$(document).ready(
  function () {
    var inputs = $('input');
    var c0 = inputs['0'];
    $('#reset-puzzle').click(
      function () {
        var c, k;
        for (k = 0; k < 81; k++) {
          c = $(inputs[String(k)]);
          c.val("");
          if (c.css("background-color")) {
            c.css("background-color", "");
          }
        }
        c0.focus();
        if ($('#solve-puzzle').attr('disabled')) {
          $('#solve-puzzle').removeAttr('disabled');
          // $('#solve-puzzle').removeClass('toggle-color');
        }
      });

    /* $("#reset-puzzle").hover(
        function () {
            $(this).addClass('toggle-color');
        },
        function () {
            $(this).removeClass('toggle-color');
        }
    );

    $("#solve-puzzle").hover(
        function () {
            if ($(this).attr('disabled')) {
            } else {
                $(this).addClass('toggle-color');
            }
        },
        function () {
            $(this).removeClass('toggle-color');
        }
    ); */

    $('#solve-puzzle').click(
      function () {
        var pz = [];
        var userin = [];
        var c, k, v, vv;
        var sbtn = $(this);
        for (k = 0; k < 81; k++) {
          c = $(inputs[String(k)]);
          vv = c.val();
          if (vv === '' || vv === '0') {
            v = 0;
          } else {
            v = Number(vv);
            if (isNaN(v)) {
                c.css("background-color", "#bf4040");
                sbtn.attr('disabled', 'disabled');
                $(window).alert('You have input non-digit character!');
                return;
            }
            userin.push(k);
          }
          pz.push(v);
        }
        $.ajax({
          url: 'api/solve',
          type: 'POST',
          data: {
            puzzle: JSON.stringify(pz)
          },
          dataType: 'json',
          success: function (data, status, xhr) {
            var idx;
            if (data.eno === 0) {
              sbtn.attr('disabled', 'disabled');
              for (var i = 0; i < data.solution.length; i++) {
                var v = data.solution[i];
                var c = $(inputs[String(i)]);
                c.val(String(v));
              }
              for (i = 0; i < userin.length; i++) {
                  idx = userin[i];
                  c = $(inputs[String(idx)]);
                  c.css("background-color", "#ccc");
              }
            } else if (data.eno === 1) {
              $(window).alert("Invalid input puzzle, please check again");
            } else if (data.eno === 2) {
              $(window).alert("No proper solution could be found");
            } else {
              return;
            }
          }
	  /*
          error: function (xhr, status) {
            window.alert("Cannot Find Any Solution, Please Check Your Puzzle!");
	  }
	  */
        });
        // $(this).removeAttr('disabled');
      });
  });

<commit_msg>fix alert<commit_after>$(document).ready(
  function () {
    var inputs = $('input');
    var c0 = inputs['0'];
    $('#reset-puzzle').click(
      function () {
        var c, k;
        for (k = 0; k < 81; k++) {
          c = $(inputs[String(k)]);
          c.val("");
          if (c.css("background-color")) {
            c.css("background-color", "");
          }
        }
        c0.focus();
        if ($('#solve-puzzle').attr('disabled')) {
          $('#solve-puzzle').removeAttr('disabled');
          // $('#solve-puzzle').removeClass('toggle-color');
        }
      });

    /* $("#reset-puzzle").hover(
        function () {
            $(this).addClass('toggle-color');
        },
        function () {
            $(this).removeClass('toggle-color');
        }
    );

    $("#solve-puzzle").hover(
        function () {
            if ($(this).attr('disabled')) {
            } else {
                $(this).addClass('toggle-color');
            }
        },
        function () {
            $(this).removeClass('toggle-color');
        }
    ); */

    $('#solve-puzzle').click(
      function () {
        var pz = [];
        var userin = [];
        var c, k, v, vv;
        var sbtn = $(this);
        for (k = 0; k < 81; k++) {
          c = $(inputs[String(k)]);
          vv = c.val();
          if (vv === '' || vv === '0') {
            v = 0;
          } else {
            v = Number(vv);
            if (isNaN(v)) {
                c.css("background-color", "#bf4040");
                sbtn.attr('disabled', 'disabled');
                window.alert('You have input non-digit character!');
                return;
            }
            userin.push(k);
          }
          pz.push(v);
        }
        $.ajax({
          url: 'api/solve',
          type: 'POST',
          data: {
            puzzle: JSON.stringify(pz)
          },
          dataType: 'json',
          success: function (data, status, xhr) {
            var idx;
            if (data.eno === 0) {
              sbtn.attr('disabled', 'disabled');
              for (var i = 0; i < data.solution.length; i++) {
                var v = data.solution[i];
                var c = $(inputs[String(i)]);
                c.val(String(v));
              }
              for (i = 0; i < userin.length; i++) {
                  idx = userin[i];
                  c = $(inputs[String(idx)]);
                  c.css("background-color", "#ccc");
              }
            } else if (data.eno === 1) {
              window.alert("Invalid input puzzle, please check again");
            } else if (data.eno === 2) {
              window.alert("No proper solution could be found");
            } else {
              return;
            }
          }
	  /*
          error: function (xhr, status) {
            window.alert("Cannot Find Any Solution, Please Check Your Puzzle!");
	  }
	  */
        });
        // $(this).removeAttr('disabled');
      });
  });

<|endoftext|>


<commit_before>import React, { PropTypes, Component } from "react";
import classNames from "classnames";

class DropdownContainer extends Component {

  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string
  };

  render() {
    const {children, className} = this.props;
    const cls = classNames("dropdown-container", className);

    return (

    <div className={cls}>
      {children}
    </div>
    );
  }
}

export default DropdownContainer;
<commit_msg>remove obsolete component<commit_after><|endoftext|>


<commit_before>/**
 * Created by dongyancen on 14-3-26.
 */
var fs = require('fs');
var browsers = ['Chrome', 'Firefox', 'PhantomJS', 'IE'];
var result_forBrowser = {};
var jsonFileBasePath = './spec/coverage/json_files/';
var jsonFiles = fs.readdirSync(jsonFileBasePath);
var finalJsonFile = 'defaultFileName';
var curPath = '/spec';
var resultPath = '.';

//找出所有的json文件
for (var i = 0; i < jsonFiles.length; i++) {
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    if (!isJsonFiles(jsonFiles[i])) {
        jsonFiles.splice(i, 1);
        i--;
    }
}
//没有找到合适的文件
if(jsonFiles.length==0)return;

//先排序 按时间从小到大 及从旧到新
jsonFiles.sort(function (f1, f2) {
    var t1 = getFileTime(f1);//形如['-20140326_161249','20140326','161249']
    var t2 = getFileTime(f2);
    var dateDiff = parseInt(t1[1]) - parseInt(t2[1]);
    if (dateDiff != 0)return dateDiff;
    else return parseInt(t1[2]) - parseInt(t2[2]);
});
//以时间命名新的文件
finalJsonFile = getFileTime(jsonFiles[jsonFiles.length-1])[0].substring(1);
//如:20140326_161249

//取最新的
// 按浏览器类型分类 result_forBrowser属性形如:{'Crome':'filename1','Firefox':'filename2'}
for (i = 0; i < jsonFiles.length; i++) {
    for (var j = 0; j < browsers.length; j++) {
        if (eval('/' + browsers[j] + '/.test("' + jsonFiles[i] + '");')) {
            eval('result_forBrowser.' + browsers[j] + '="' + jsonFiles[i] + '";');
        }
    }
}

//以上得到所有要合计的json文件
//读取,合计数字,需要合计的属性: 's' 'b' 'f' 'l'
//修正路径
var jsonToWrite = null;
for (var a in result_forBrowser) {
    var r = fs.readFileSync(jsonFileBasePath + result_forBrowser[a]);
    if (!jsonToWrite) {
        jsonToWrite = JSON.parse(r);
        continue;
    } else {
        jsonToWrite = mergeResult(jsonToWrite, JSON.parse(r));
    }
}

//写文件
fs.writeFileSync(jsonFileBasePath+finalJsonFile+'.json',JSON.stringify(jsonToWrite));

function isJsonFiles(fileName) {
    var e = fileName.substring(fileName.lastIndexOf(".") + 1);
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    //否则无法判断文件生成时间,也就无法合并同一次运行产生的结果
    return e == 'json' && getFileTime(fileName);
}
function getFileTime(fileName) {
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    return fileName.match(/-(\d{8})_(\d{6})/);
}
function mergeResult(allR, addR) {
    var resultR = {};
    for (var allRKey in allR) {

        if (addR[allRKey]) {

            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 's', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'f', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'l', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'b', 2);
        }
        //修正路径
        resultR[fixPath(allRKey)] = allR[allRKey]
    }
    return resultR;
}
//type = 1 合并 s f l ,如:{"1":1,"2":1,"3":1}
//type = 2 合并 b ,如:{"1":[0,0],"2":[0,0]}
function mergeDetail(allEle, addEle, attrName, type) {

    if (allEle[attrName] && addEle[attrName]) {
        if (type == 1) {
            for (var k in allEle[attrName]) {
                //todo 现在没有考虑两个文件中同一项覆盖率的统计行数不一致的问题
                if ( parseInt(allEle[attrName][k])==0 &&  parseInt(addEle[attrName][k]) ==1) {
                    allEle[attrName][k] = 1;
                }
            }
        }
        else if (type == 2) {
            for (var k in allEle[attrName]) {
                //todo 现在没有考虑两个文件中同一项覆盖率的统计行数不一致的问题
                if (addEle[attrName][k]) {
                    if (parseInt(allEle[attrName][k][0])==0 &&parseInt(addEle[attrName][k][0])==1 ) {
                        allEle[attrName][k][0] = 1;
                    }
                    if (parseInt(allEle[attrName][k][1])==0 &&parseInt(addEle[attrName][k][1])==1 ) {
                        allEle[attrName][k][1] = 1;
                    }
                }
            }
        }
    }
    return allEle;
}
//修正路径
function fixPath(oldPath){
    //例如把 "D:/workspace/ufinder/_src/core/finder.js" 修正为
    // ./_src/core/finder.js  注意这里一定要用相对路径(相对于_spec/coverage)
    var s = __dirname.replace(/\\/g,'/');
    if(s.lastIndexOf(curPath)){
        s = s.substring(0,s.lastIndexOf(curPath) );
    }
    oldPath = oldPath.replace(s,resultPath);
    return oldPath;
}
console.log(finalJsonFile);<commit_msg>[test]修改测试配置<commit_after>/**
 * Created by dongyancen on 14-3-26.
 */
var fs = require('fs');
var browsers = ['Chrome', 'Firefox', 'PhantomJS', 'IE'];
var result_forBrowser = {};
var jsonFileBasePath = './spec/coverage/json_files/';
var jsonFiles = fs.readdirSync(jsonFileBasePath);
var finalJsonFile = 'defaultFileName';
var curPath = '/spec';
var resultPath = 'spec/coverage';

//找出所有的json文件
for (var i = 0; i < jsonFiles.length; i++) {
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    if (!isJsonFiles(jsonFiles[i])) {
        jsonFiles.splice(i, 1);
        i--;
    }
}
//没有找到合适的文件
if(jsonFiles.length==0)return;

//先排序 按时间从小到大 及从旧到新
jsonFiles.sort(function (f1, f2) {
    var t1 = getFileTime(f1);//形如['-20140326_161249','20140326','161249']
    var t2 = getFileTime(f2);
    var dateDiff = parseInt(t1[1]) - parseInt(t2[1]);
    if (dateDiff != 0)return dateDiff;
    else return parseInt(t1[2]) - parseInt(t2[2]);
});
//以时间命名新的文件
finalJsonFile = getFileTime(jsonFiles[jsonFiles.length-1])[0].substring(1);
//如:20140326_161249

//取最新的
// 按浏览器类型分类 result_forBrowser属性形如:{'Crome':'filename1','Firefox':'filename2'}
for (i = 0; i < jsonFiles.length; i++) {
    for (var j = 0; j < browsers.length; j++) {
        if (eval('/' + browsers[j] + '/.test("' + jsonFiles[i] + '");')) {
            eval('result_forBrowser.' + browsers[j] + '="' + jsonFiles[i] + '";');
        }
    }
}

//以上得到所有要合计的json文件
//读取,合计数字,需要合计的属性: 's' 'b' 'f' 'l'
//修正路径
var jsonToWrite = null;
for (var a in result_forBrowser) {
    var r = fs.readFileSync(jsonFileBasePath + result_forBrowser[a]);
    if (!jsonToWrite) {
        jsonToWrite = JSON.parse(r);
        continue;
    } else {
        jsonToWrite = mergeResult(jsonToWrite, JSON.parse(r));
    }
}

//写文件
fs.writeFileSync(jsonFileBasePath+finalJsonFile+'.json',JSON.stringify(jsonToWrite));

function isJsonFiles(fileName) {
    var e = fileName.substring(fileName.lastIndexOf(".") + 1);
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    //否则无法判断文件生成时间,也就无法合并同一次运行产生的结果
    return e == 'json' && getFileTime(fileName);
}
function getFileTime(fileName) {
    // json文件名必须是有8位的日期和6位的时间戳如:-20140326_161249
    return fileName.match(/-(\d{8})_(\d{6})/);
}
function mergeResult(allR, addR) {
    var resultR = {};
    for (var allRKey in allR) {

        if (addR[allRKey]) {

            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 's', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'f', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'l', 1);
            allR[allRKey] = mergeDetail(allR[allRKey], addR[allRKey], 'b', 2);
        }
        //修正路径
        resultR[fixPath(allRKey)] = allR[allRKey]
    }
    return resultR;
}
//type = 1 合并 s f l ,如:{"1":1,"2":1,"3":1}
//type = 2 合并 b ,如:{"1":[0,0],"2":[0,0]}
function mergeDetail(allEle, addEle, attrName, type) {

    if (allEle[attrName] && addEle[attrName]) {
        if (type == 1) {
            for (var k in allEle[attrName]) {
                //todo 现在没有考虑两个文件中同一项覆盖率的统计行数不一致的问题
                if ( parseInt(allEle[attrName][k])==0 &&  parseInt(addEle[attrName][k]) ==1) {
                    allEle[attrName][k] = 1;
                }
            }
        }
        else if (type == 2) {
            for (var k in allEle[attrName]) {
                //todo 现在没有考虑两个文件中同一项覆盖率的统计行数不一致的问题
                if (addEle[attrName][k]) {
                    if (parseInt(allEle[attrName][k][0])==0 &&parseInt(addEle[attrName][k][0])==1 ) {
                        allEle[attrName][k][0] = 1;
                    }
                    if (parseInt(allEle[attrName][k][1])==0 &&parseInt(addEle[attrName][k][1])==1 ) {
                        allEle[attrName][k][1] = 1;
                    }
                }
            }
        }
    }
    return allEle;
}
//修正路径
function fixPath(oldPath){
    //例如把 "D:/workspace/ufinder/_src/core/finder.js" 修正为
    // spec/coverage/_src/core/finder.js  注意这里一定要用相对路径(相对于_spec/coverage)
    var s = __dirname.replace(/\\/g,'/');
    if(s.lastIndexOf(curPath)){
        s = s.substring(0,s.lastIndexOf(curPath) );
    }
    oldPath = oldPath.replace(s,resultPath);
    return oldPath;
}
console.log(finalJsonFile);<|endoftext|>


<commit_before>'use strict';
var restler    = require('restler');
var assert     = require('assert');
var http       = require('http');
var fs         = require('fs');

var config     = require('../../config');
var testUtil   = new require('../testUtil').TestUtil(config);
var crypto     = require('../../lib/crypto');
/*
 * Decided to have these tests hit the actual
 * npmjs.org registry, as then we know fo' sho'
 * that all is good.
 * However they're set to skip because Travis shouldn't
 * be hitting external stuff really. Just enable it if
 * you want to test that the app works against an actual repo
 */
describe('NPMZor outside in', function() {

  var endPoint = config.url,
      app,
      fakeNpmEndpoint;

  var retStatus = 200,
      contentType = 'application/json',
      content;

  config.registries = ['http://127.0.0.1:6699'];

  beforeEach(function() {
    testUtil.clearCache();
  });

  before(function(done) {
    testUtil.clearAll();
    app = require('../../app.js');

    fakeNpmEndpoint = http.createServer(function (req, res) {
      res.writeHead(retStatus, {'Content-Type': contentType});
      res.end(content);
    }).listen(6699, function() {
      setTimeout(function() {
        done();
      }, 1000);
    });
  });

  after(function() {
    testUtil.clearAll();
    fakeNpmEndpoint.close();
    app().close();
  });

  this.timeout(3000);

  it('Should return a valid index page', function(done) {
    content = fs.readFileSync(__dirname + '/../data/sample-requests/mkdirp').toString();
    restler.json(endPoint + '/mkdirp')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false, result);
      assert.equal(res.statusCode, 200, 'Incorrect status code returned: ' + res.statusCode);
      assert.equal(result._id, 'mkdirp', 'Result returned did not have an _id of deride');
      done();
    });
  });

  it('Should return a valid specific version page', function(done) {
    content = fs.readFileSync(__dirname + '/../data/sample-requests/mkdirp').toString();
    restler.json(endPoint + '/mkdirp/0.1.0')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(result.name, 'mkdirp');
      assert.equal(result.version, '0.1.0');
      assert.equal(res.statusCode, 200);
      done();
    });
  });

  it('Should return a 404 when requestinga package version that doesnt exist', function(done) {
    content = null;
    retStatus = 404;
    restler.get(endPoint + '/deride/-/deride-0.0.7.tgz')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(res.statusCode, 404);
      done();
    });
  });

  it('Should return a module when the request is valid', function(done) {
    var target  = '/tmp/' + Date.now().toString(12);
    var file    = fs.createWriteStream(target);
    retStatus   = 200;
    content     = fs.readFileSync(__dirname + '/../data/sample-files/simple-empty-app-0.0.1.tgz');
    http.get(endPoint + '/deride/-/deride-0.1.0.tgz', function(response) {
      response.pipe(file);
      file.on('finish', function() {
        file.close(function() {
          crypto.sha1(target, function(error, sum) {
            assert.equal(sum, '4c3f6548fef5305e6ef5029ed7c34c992a707820');
            done();
          });
        });
      });
    });
  });

  it.only('Should accept a TGZ module PUT to it', function(done) {
    var sampleTgz = __dirname + '/../data/sample-files/simple-empty-app-0.0.1.tgz';
    restler.put(endPoint + '/simple-empty-app', {
      multipart: true,
      data: {
        package: restler.file(sampleTgz, null, 592, null, 'application/octet-stream')
      }
    }).on('complete', function(data, res) {
      assert.equal(res.statusCode, 200);
      done();
    });
  });

  it('Should return a 404 on an invalid index page', function(done) {
    content = null;
    retStatus = 404;
    restler.get(endPoint + '/this-repo-doesnt-exist')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(res.statusCode, 404);
      done();
    });
  });

});
<commit_msg>Added API PUT /package<commit_after>'use strict';
var restler    = require('restler');
var assert     = require('assert');
var http       = require('http');
var fs         = require('fs');

var config     = require('../../config');
var testUtil   = new require('../testUtil').TestUtil(config);
var crypto     = require('../../lib/crypto');
/*
 * Decided to have these tests hit the actual
 * npmjs.org registry, as then we know fo' sho'
 * that all is good.
 * However they're set to skip because Travis shouldn't
 * be hitting external stuff really. Just enable it if
 * you want to test that the app works against an actual repo
 */
describe('NPMZor outside in', function() {

  var endPoint = config.url,
      app,
      fakeNpmEndpoint;

  var retStatus = 200,
      contentType = 'application/json',
      content;

  config.registries = ['http://127.0.0.1:6699'];

  beforeEach(function() {
    testUtil.clearCache();
  });

  before(function(done) {
    testUtil.clearAll();
    app = require('../../app.js');

    fakeNpmEndpoint = http.createServer(function (req, res) {
      res.writeHead(retStatus, {'Content-Type': contentType});
      res.end(content);
    }).listen(6699, function() {
      setTimeout(function() {
        done();
      }, 1000);
    });
  });

  after(function() {
    testUtil.clearAll();
    fakeNpmEndpoint.close();
    app().close();
  });

  this.timeout(3000);

  it('Should return a valid index page', function(done) {
    content = fs.readFileSync(__dirname + '/../data/sample-requests/mkdirp').toString();
    restler.json(endPoint + '/mkdirp')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false, result);
      assert.equal(res.statusCode, 200, 'Incorrect status code returned: ' + res.statusCode);
      assert.equal(result._id, 'mkdirp', 'Result returned did not have an _id of deride');
      done();
    });
  });

  it('Should return a valid specific version page', function(done) {
    content = fs.readFileSync(__dirname + '/../data/sample-requests/mkdirp').toString();
    restler.json(endPoint + '/mkdirp/0.1.0')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(result.name, 'mkdirp');
      assert.equal(result.version, '0.1.0');
      assert.equal(res.statusCode, 200);
      done();
    });
  });

  it('Should return a 404 when requestinga package version that doesnt exist', function(done) {
    content = null;
    retStatus = 404;
    restler.get(endPoint + '/deride/-/deride-0.0.7.tgz')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(res.statusCode, 404);
      done();
    });
  });

  it('Should return a module when the request is valid', function(done) {
    var target  = '/tmp/' + Date.now().toString(12);
    var file    = fs.createWriteStream(target);
    retStatus   = 200;
    content     = fs.readFileSync(__dirname + '/../data/sample-files/simple-empty-app-0.0.1.tgz');
    http.get(endPoint + '/deride/-/deride-0.1.0.tgz', function(response) {
      response.pipe(file);
      file.on('finish', function() {
        file.close(function() {
          crypto.sha1(target, function(error, sum) {
            assert.equal(sum, '4c3f6548fef5305e6ef5029ed7c34c992a707820');
            done();
          });
        });
      });
    });
  });

  it.only('Should accept a TGZ module PUT to it', function(done) {
    var sampleTgz = __dirname + '/../data/sample-files/simple-empty-app-0.0.1.tgz';
    restler.put(endPoint + '/simple-empty-app', {
      multipart: true,
      data: {
        package: restler.file(sampleTgz, null, 592, null, 'application/octet-stream')
      }
    }).on('complete', function(data, res) {
      console.log(data);
      assert.equal(res.statusCode, 200);
      done();
    });
  });

  it('Should return a 404 on an invalid index page', function(done) {
    content = null;
    retStatus = 404;
    restler.get(endPoint + '/this-repo-doesnt-exist')
    .on('complete', function(result, res) {
      assert.equal(result instanceof Error, false);
      assert.equal(res.statusCode, 404);
      done();
    });
  });

});
<|endoftext|>


<commit_before>// ==UserScript==
// @include http://*.adressa.no/*
// @include http://*.t-a.no/*
// @include http://*.vg.no/*
// @include http://*.dagbladet.no/*
// @include http://*.dn.no/*
// ==/UserScript==

console.log('running');

// Just fuck these guys.
document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('iframe'), function (el) {
        el.parentNode.removeChild(el);
    });
});

var blandColour = function() {
    return "rgba(" + ((60 + Math.random() * 80)|0) +
        "," + ((60 + Math.random() * 80)|0) +
        "," + ((60 + Math.random() * 80)|0) +
        ",.3)";
};

// Polaris
if (location.hostname.match(/((adressa)|(t-a))\.no/)) {
    document.addEventListener('DOMContentLoaded', function () {
        Array.prototype.forEach.call(document.querySelectorAll('.payed > *'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("vg.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        // Plus and VGtv
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://pluss.vg"], .df-img-skin-play-button, .video-unit, .vgpluss-header'), function (el) {
            console.log(el);
            el.parentNode.style.visibility = "hidden";
            el.parentNode.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("dagbladet.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        // Plus
        Array.prototype.forEach.call(document.querySelectorAll('.plussArticle, .plussbox_article'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
        // DBtv
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://dbtv.no"]'), function (el) {
            el.parentNode.style.visibility = "hidden";
            el.parentNode.parentNode.style.background = blandColour();
        });
        //Se.no
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://se.no"]'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("dn.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        Array.prototype.forEach.call(document.querySelectorAll('.df-skin-paid > div'), function (el) {
            console.log(el);
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

<commit_msg>Update minus.js<commit_after>// ==UserScript==
// @include http://*.adressa.no/*
// @include http://*.t-a.no/*
// @include http://*.vg.no/*
// @include http://*.dagbladet.no/*
// @include http://*.dn.no/*
// ==/UserScript==

console.log('running');

// Just fuck these guys.
document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('iframe'), function (el) {
        el.parentNode.removeChild(el);
    });
});

var blandColour = function() {
    return "rgba(x,x,x,.3)".replace(/x/g,(function(){return (60 + Math.random() * 80)|0;}));
};

// Polaris
if (location.hostname.match(/((adressa)|(t-a))\.no/)) {
    document.addEventListener('DOMContentLoaded', function () {
        Array.prototype.forEach.call(document.querySelectorAll('.payed > *'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("vg.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        // Plus and VGtv
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://pluss.vg"], .df-img-skin-play-button, .video-unit, .vgpluss-header'), function (el) {
            console.log(el);
            el.parentNode.style.visibility = "hidden";
            el.parentNode.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("dagbladet.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        // Plus
        Array.prototype.forEach.call(document.querySelectorAll('.plussArticle, .plussbox_article'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
        // DBtv
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://dbtv.no"]'), function (el) {
            el.parentNode.style.visibility = "hidden";
            el.parentNode.parentNode.style.background = blandColour();
        });
        //Se.no
        Array.prototype.forEach.call(document.querySelectorAll('a[href^="http://se.no"]'), function (el) {
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

if (location.hostname.match("dn.no")) {
    document.addEventListener('DOMContentLoaded', function () {
        Array.prototype.forEach.call(document.querySelectorAll('.df-skin-paid > div'), function (el) {
            console.log(el);
            el.style.visibility = "hidden";
            el.parentNode.style.background = blandColour();
        });
    });
}

<|endoftext|>


<commit_before>// @flow
import {awral} from 'actions/utils'
import {getPostsAPI} from 'api/PostsSvc'
import type {PostItem} from 'types'
// Define action types
export const GET_POSTS_SUCCESS = 'GET_POSTS_SUCCESS'
export const GET_POSTS_FAIL = 'GET_POSTS_FAIL'
export const GET_POSTS_PENDING = 'GET_POSTS_PENDING'

export type GET_POSTS_SUCCESS_TYPE = {
	type: 'GET_POSTS_SUCCESS',
	payload: Array<PostItem>
}

export type GET_POSTS_PENDING_TYPE = {
	type: 'GET_POSTS_FAIL'
}

export type GET_POSTS_FAIL_TYPE = {
	type: 'GET_POSTS_PENDING',
	payload: {
		errors: void | Object
	}
}

export const GET_POSTS = awral(getPostsAPI)('GET_POSTS')
<commit_msg>feat(actions/posts): remove posts actions<commit_after><|endoftext|>