<commit_before>//- JavaScript source code

//- qmachine.js ~~
//                                                      ~~ (c) SRW, 17 Feb 2012

(function () {
    'use strict';

 // Pragmas

    /*jslint indent: 4, maxlen: 80, unparam: true */

 // Prerequisites

    if (Object.prototype.hasOwnProperty('Q') === false) {
        throw new Error('Method Q is missing.');
    }

    if (({}).Q.hasOwnProperty('global') === false) {
        throw new Error('Method Q has no "global" property.');
    }

    if (({}).Q.global.hasOwnProperty('navigator') === false) {
     // Exit early if the current environment is not a web browser.
        return;
    }

    if (({}).Q.global.hasOwnProperty('phantom')) {
     // Exit early if running in PhantomJS (http://www.phantomjs.org).
        return;
    }

    if (({}).Q.global.hasOwnProperty('system')) {
     // Exit early if the current environment is a CommonJS implementation that
     // impersonates a browser, such as the Cappuccino JSC version of Narwhal.
        return;
    }

 // Declarations

    var Q, avar, global, isFunction, parseArgs, ply, queue, read, relaunch,
        request, token, when, write;

 // Definitions

    Q = Object.prototype.Q;

    avar = Q.avar;

    global = Q.global;

    isFunction = function (f) {
     // This function returns 'true' only if and only if 'f' is a Function.
     // The second condition is necessary to return 'false' for a RegExp.
        return ((typeof f === 'function') && (f instanceof Function));
    };

    parseArgs = function () {
     // This function is based on "parseUri" by Steven Levithan (MIT license),
     // but I have modified it here because I only care about parsing the
     // query parameters. It treats the 'location.search' value as a set of
     // ampersand-separated Boolean key=value parameters whose keys are valid
     // JS identifiers and whose values are either "true" or "false" (without
     // quotes). The function accepts an object whose own properties will be
     // used to override flags that are already present.
        /*jslint regexp: true */
        var args, i, m, opts, uri;
        args = {};
        opts = {
            key: [
                'source', 'protocol', 'authority', 'userInfo',
                'user', 'password', 'host', 'port', 'relative',
                'path', 'directory', 'file', 'query', 'anchor'
            ],
            parser: new RegExp('^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@' +
                ']*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((('  +
                '(?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'),
            q: {
                name:   'flags',
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            }
        };
        m = opts.parser.exec(global.location.href);
        uri = {};
        for (i = 14; i > 0; i -= 1) {
            uri[opts.key[i]] = m[i] || '';
        }
        uri[opts.q.name] = {};
        uri[opts.key[12]].replace(opts.q.parser, function ($0, $1, $2) {
            if ($1) {
             // These are "explicit coercions" ;-)
                switch ($2) {
                case '':
                    uri[opts.q.name][$1] = true;
                    break;
                case 'false':
                    uri[opts.q.name][$1] = false;
                    break;
                case 'true':
                    uri[opts.q.name][$1] = true;
                    break;
                default:
                    uri[opts.q.name][$1] = decodeURI($2);
                }
            }
        });
     // Now, we'll copy the "command-line arguments" onto our output object.
        ply(uri.flags).by(function (key, val) {
         // Does this function need documentation?
            args[key] = val;
            return;
        });
     // Before exiting, let's make sure that our query parameters match the
     // values shown in the form's options ...
        (function () {
            if (global.hasOwnProperty('document') === false) {
                return;
            }
            var options = {
                volunteer:  global.document.getElementById('volunteer'),
                pulse:      global.document.getElementById('pulse')
            };
            ply(args).by(function (key, val) {
             // This function needs documentation.
                var flag;
                flag = ((options.hasOwnProperty(key)) &&
                        (options[key] !== null) &&
                        (options[key].checked !== undefined) &&
                        (options[key].checked !== val));
                if (flag === true) {
                    options[key].checked = val;
                }
            });
            return;
        }());
     // Finally, we return our object :-)
        return args;
    };

    ply = function () {
     // This function is a generalized "zippered" iterator that also works
     // extremely well for key-value pairs, and it serves as the "fallback"
     // definition for the generic 'Q.ply' method. It is incredibly useful in
     // JavaScript because hash-like objects are so common in that language.
     // It provides access not only to the values of its input arguments, but
     // also to the index at which each set of values was found.
        var args, i, key, obj, n, toc, x;
        args = Array.prototype.slice.call(arguments);
        n = args.length;
        toc = {};
        x = [];
        for (i = 0; i < n; i += 1) {
            if ((args[i] !== null) && (args[i] !== undefined)) {
                obj = args[i].valueOf();
                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if (toc.hasOwnProperty(key) === false) {
                            toc[key] = x.push([key]) - 1;
                        }
                        x[toc[key]][i + 1] = obj[key];
                    }
                }
            }
        }
        return {
            by: function (f) {
             // This function needs documentation.
                if (isFunction(f) === false) {
                    throw new TypeError('"ply..by" expects a function');
                }
                var i, n;
                n = x.length;
                for (i = 0; i < n; i += 1) {
                    f.apply(this, x[i]);
                }
                return;
            }
        };
    };

    queue = function () {
     // This function needs documentation.
        var y = avar({val: []});
        y.onready = function (evt) {
         // This function needs documentation.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_changes?filter=qmachine/queue&limit=25&status=waiting&' +
                'token=' + token();
            req.onreadystatechange = function () {
             // This function needs documentation.
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).results;
                        ply(temp).by(function (key, val) {
                         // This function needs documentation.
                            y.val.push(val.id);
                            return;
                        });
                        return evt.exit();
                    } else {
                        return evt.fail(req.statusText);
                    }
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        return y;
    };

    read = function (key) {
     // This function needs documentation.
        var y = avar();
        y.onready = function (evt) {
         // This function implements an HTTP GET request.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_all_docs?key="' + key + '"&include_docs=true';
            req.onreadystatechange = function () {
             // This function needs documentation.
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).rows[0];
                        if (temp === undefined) {
                            return evt.fail('Remote missing: ' + url);
                        }
                        y.val = temp.doc.$avar;
                        return evt.exit();
                    } else {
                        return evt.fail(req.statusText);
                    }
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        return y;
    };

    relaunch = function (obj) {
     // This function reloads the current webpage with new query parameters
     // by stringifying its input object, 'obj'.
        var y = [];
        ply(obj).by(function (key, val) {
            y.push(key + '=' + val);
            return;
        });
        global.location.search = y.join('&');
        return;
    };

    request = function () {
     // This function generates a new AJAX request object. I have written it
     // as a separate function so I can handle browser quirks conveniently.
        if (global.location.protocol === 'file:') {
            if (global.hasOwnProperty('ActiveXObject')) {
             // Internet Explorer supports XMLHttpRequest, but that won't work
             // over 'file:', so we'll use an ActiveXObject instead.
                return new global.ActiveXObject('Microsoft.XMLHTTP');
            }
        }
        if (global.hasOwnProperty('XMLHttpRequest')) {
            return new global.XMLHttpRequest();
        }
        if (global.hasOwnProperty('ActiveXObject')) {
            return new global.ActiveXObject('Microsoft.XMLHTTP');
        }
        throw new Error('This browser does not support AJAX.');
    };

    token = function () {
     // This function is mainly a placeholder for more elaborate security
     // measures that we may choose to implement in the future. It needs some
     // more error checking, though ...
        var args, secret;
        args = parseArgs();
        secret = null;
        if (args.hasOwnProperty('token')) {
            if ((typeof args.token === 'string') && (args.token.length > 0)) {
                secret = args.token;
                if (global.hasOwnProperty('localStorage')) {
                    global.localStorage.setItem('QMACHINE_token', secret);
                }
                token = function () {
                    return secret;
                };
                return token();
            }
        }
        if (global.hasOwnProperty('localStorage')) {
            secret = global.localStorage.getItem('QMACHINE_token');
         /*
        } else if (global.hasOwnProperty('moz_indexedDB')) {
         // (placeholder: see http://goo.gl/XArgc)
        } else if (global.hasOwnProperty('webkitIndexedDB')) {
         // (placeholder: see http://goo.gl/XArgc)
        } else if (hOP(global, 'window', 'cookie')) {
         // (placeholder)
        } else {
         // (placeholder)
         */
        }
        args.token = (secret === null) ? Q.uuid() : secret;
        relaunch(args);
        return;
    };

    when = Q.when;

    write = function (key, $val) {
     // This function needs documentation.
     //
     // NOTE: Since 'revision' only exists in this function, how should I pass
     // errors back to the user?
     //
        var revision, y;
        revision = avar({val: undefined});
        y = avar();
        revision.onready = function (evt) {
         // This function reads the revision number from CouchDB in such a way
         // as to avoid 404 errors entirely -- I can't figure out how to keep
         // those from cluttering Chrome's developer console. A more efficient
         // way would use a HEAD request, but efficiency isn't the goal here.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_all_docs?key="' + key + '"&include_docs=false';
            req.onreadystatechange = function () {
             // This function doesn't fail if the status code returned isn't
             // 200 because we're only interested in getting the revision
             // number. If something really important has failed, it is highly
             // probable that it's going to fail again during the 'when' ;-)
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).rows[0];
                        if (temp !== undefined) {
                            revision.val = temp.value.rev;
                        }
                    }
                    return evt.exit();
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        when(revision, y).areready = function (evt) {
         // This function implements an HTTP PUT request.
            /*jslint nomen: true */
            var doc, req, temp, url;
            doc = {
                '_id':  key,
                '_rev': revision.val,
                $avar:  $val,
                token:  token()
            };
            req = request();
            temp = JSON.parse($val).val;
            url = global.location.protocol + '//' + global.location.host +
                '/db/' + key;
            if ((temp !== null) && (temp !== undefined) &&
                    (temp.hasOwnProperty('status'))) {
             // This simplifies Qmachine's 'queue' filter in CouchDB.
                doc.status = temp.status;
            }
            req.onreadystatechange = function () {
             // This function needs documentation.
                if (req.readyState === 4) {
                    if (req.status === 201) {
                        y.val = JSON.parse(req.responseText);
                        return evt.exit();
                    } else {
                        return evt.fail(req.responseText);
                    }
                }
                return;
            };
            req.open('PUT', url, true);
            req.setRequestHeader('Content-type', 'application/json');
            req.send(JSON.stringify(doc));
            return;
        };
        return y;
    };

 // Initialization

    Q.init({
        queue:  queue,
        read:   read,
        write:  write
    });

    token();

 // Browser configuration

    if (global.hasOwnProperty('document')) {
     // This part would probably be cleaner with jQuery ...
        (function () {
            var options = ['volunteer', 'pulse'];
            ply(options).by(function (key, val) {
             // This function is necessary because I need to close inside a
             // loop, which is error-prone without functional iteration.
                var temp = global.document.getElementById(val);
                if (temp !== null) {
                    temp.onclick = function () {
                        var obj = {};
                        obj[val] = this.checked;
                        return relaunch(obj);
                    };
                }
                return;
            });
            return;
        }());
    }

 // Demonstrations

    if (parseArgs().volunteer === true) {
        global.console.log('Thanks for volunteering!');
        (function f() {
         // This function just keeps things moving :-)
            var dt, g, x;
            dt = 1000;
            x = Q.volunteer();
            g = x.onerror;
            x.onerror = function (message) {
             // This function demonstrates that "errors" are not always a big
             // deal, and that Quanah lets you handle errors however you want.
                if ((typeof g === 'function') && (g instanceof Function)) {
                    g(message);
                }
                if (message !== 'Nothing to do ...') {
                    global.console.error(message);
                }
                global.setTimeout(f, dt);
                return;
            };
            x.onready = function (evt) {
             // This function provides instant gratification :-)
                global.console.log('Completed task: ' + x.key);
                global.setTimeout(f, dt);
                return evt.exit();
            };
            if (parseArgs().pulse === true) {
                global.console.log('(pulse)');
            }
            return;
        }());
    } else {
        global.console.log('Run "demo()" for a live example :-)');
        (function f() {
         // This function just keeps things moving :-)
            var x = avar();
            x.onerror = function (message) {
             // I don't how this can possibly go wrong anyway ...
                global.console.error(message);
                global.setTimeout(f, 1000);
                return;
            };
            x.onready = function (evt) {
             // This function runs locally because it closes over 'f' :-)
                global.setTimeout(f, 1000);
                return evt.exit();
            };
            if (parseArgs().pulse === true) {
                global.console.log('(pulse)');
            }
            return;
        }());
    }

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<commit_msg>Condensed the prerequisite checks in the CouchApp version of Qmachine<commit_after>//- JavaScript source code

//- qmachine.js ~~
//                                                      ~~ (c) SRW, 23 Feb 2012

(function () {
    'use strict';

 // Pragmas

    /*jslint indent: 4, maxlen: 80, unparam: true */

 // Prerequisites

    if (Object.prototype.hasOwnProperty('Q') === false) {
        throw new Error('Method Q is missing.');
    }

    if (({}).Q.hasOwnProperty('global') === false) {
        throw new Error('Method Q has no "global" property.');
    }

    if (({}).Q.global.hasOwnProperty('navigator') === false) {
     // Exit early if the current environment is not a web browser.
        return;
    }

    if (({}).Q.global.hasOwnProperty('phantom') ||
            ({}).Q.global.hasOwnProperty('system')) {
     // Exit early if running in PhantomJS or the Cappuccino JSC version of
     // Narwhal. Both are server-side implementations that embed browsers, and
     // thus both will pass the other checks. Unfortunately, both have security
     // policies that freak out under the current version of Qmachine ...
        return;
    }

 // Declarations

    var Q, avar, global, isFunction, parseArgs, ply, queue, read, relaunch,
        request, token, when, write;

 // Definitions

    Q = Object.prototype.Q;

    avar = Q.avar;

    global = Q.global;

    isFunction = function (f) {
     // This function returns 'true' only if and only if 'f' is a Function.
     // The second condition is necessary to return 'false' for a RegExp.
        return ((typeof f === 'function') && (f instanceof Function));
    };

    parseArgs = function () {
     // This function is based on "parseUri" by Steven Levithan (MIT license),
     // but I have modified it here because I only care about parsing the
     // query parameters. It treats the 'location.search' value as a set of
     // ampersand-separated Boolean key=value parameters whose keys are valid
     // JS identifiers and whose values are either "true" or "false" (without
     // quotes). The function accepts an object whose own properties will be
     // used to override flags that are already present.
        /*jslint regexp: true */
        var args, i, m, opts, uri;
        args = {};
        opts = {
            key: [
                'source', 'protocol', 'authority', 'userInfo',
                'user', 'password', 'host', 'port', 'relative',
                'path', 'directory', 'file', 'query', 'anchor'
            ],
            parser: new RegExp('^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@' +
                ']*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((('  +
                '(?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)'),
            q: {
                name:   'flags',
                parser: /(?:^|&)([^&=]*)=?([^&]*)/g
            }
        };
        m = opts.parser.exec(global.location.href);
        uri = {};
        for (i = 14; i > 0; i -= 1) {
            uri[opts.key[i]] = m[i] || '';
        }
        uri[opts.q.name] = {};
        uri[opts.key[12]].replace(opts.q.parser, function ($0, $1, $2) {
            if ($1) {
             // These are "explicit coercions" ;-)
                switch ($2) {
                case '':
                    uri[opts.q.name][$1] = true;
                    break;
                case 'false':
                    uri[opts.q.name][$1] = false;
                    break;
                case 'true':
                    uri[opts.q.name][$1] = true;
                    break;
                default:
                    uri[opts.q.name][$1] = decodeURI($2);
                }
            }
        });
     // Now, we'll copy the "command-line arguments" onto our output object.
        ply(uri.flags).by(function (key, val) {
         // Does this function need documentation?
            args[key] = val;
            return;
        });
     // Before exiting, let's make sure that our query parameters match the
     // values shown in the form's options ...
        (function () {
            if (global.hasOwnProperty('document') === false) {
                return;
            }
            var options = {
                volunteer:  global.document.getElementById('volunteer'),
                pulse:      global.document.getElementById('pulse')
            };
            ply(args).by(function (key, val) {
             // This function needs documentation.
                var flag;
                flag = ((options.hasOwnProperty(key)) &&
                        (options[key] !== null) &&
                        (options[key].checked !== undefined) &&
                        (options[key].checked !== val));
                if (flag === true) {
                    options[key].checked = val;
                }
            });
            return;
        }());
     // Finally, we return our object :-)
        return args;
    };

    ply = function () {
     // This function is a generalized "zippered" iterator that also works
     // extremely well for key-value pairs, and it serves as the "fallback"
     // definition for the generic 'Q.ply' method. It is incredibly useful in
     // JavaScript because hash-like objects are so common in that language.
     // It provides access not only to the values of its input arguments, but
     // also to the index at which each set of values was found.
        var args, i, key, obj, n, toc, x;
        args = Array.prototype.slice.call(arguments);
        n = args.length;
        toc = {};
        x = [];
        for (i = 0; i < n; i += 1) {
            if ((args[i] !== null) && (args[i] !== undefined)) {
                obj = args[i].valueOf();
                for (key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        if (toc.hasOwnProperty(key) === false) {
                            toc[key] = x.push([key]) - 1;
                        }
                        x[toc[key]][i + 1] = obj[key];
                    }
                }
            }
        }
        return {
            by: function (f) {
             // This function needs documentation.
                if (isFunction(f) === false) {
                    throw new TypeError('"ply..by" expects a function');
                }
                var i, n;
                n = x.length;
                for (i = 0; i < n; i += 1) {
                    f.apply(this, x[i]);
                }
                return;
            }
        };
    };

    queue = function () {
     // This function needs documentation.
        var y = avar({val: []});
        y.onready = function (evt) {
         // This function needs documentation.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_changes?filter=qmachine/queue&limit=25&status=waiting&' +
                'token=' + token();
            req.onreadystatechange = function () {
             // This function needs documentation.
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).results;
                        ply(temp).by(function (key, val) {
                         // This function needs documentation.
                            y.val.push(val.id);
                            return;
                        });
                        return evt.exit();
                    } else {
                        return evt.fail(req.statusText);
                    }
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        return y;
    };

    read = function (key) {
     // This function needs documentation.
        var y = avar();
        y.onready = function (evt) {
         // This function implements an HTTP GET request.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_all_docs?key="' + key + '"&include_docs=true';
            req.onreadystatechange = function () {
             // This function needs documentation.
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).rows[0];
                        if (temp === undefined) {
                            return evt.fail('Remote missing: ' + url);
                        }
                        y.val = temp.doc.$avar;
                        return evt.exit();
                    } else {
                        return evt.fail(req.statusText);
                    }
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        return y;
    };

    relaunch = function (obj) {
     // This function reloads the current webpage with new query parameters
     // by stringifying its input object, 'obj'.
        var y = [];
        ply(obj).by(function (key, val) {
            y.push(key + '=' + val);
            return;
        });
        global.location.search = y.join('&');
        return;
    };

    request = function () {
     // This function generates a new AJAX request object. I have written it
     // as a separate function so I can handle browser quirks conveniently.
        if (global.location.protocol === 'file:') {
            if (global.hasOwnProperty('ActiveXObject')) {
             // Internet Explorer supports XMLHttpRequest, but that won't work
             // over 'file:', so we'll use an ActiveXObject instead.
                return new global.ActiveXObject('Microsoft.XMLHTTP');
            }
        }
        if (global.hasOwnProperty('XMLHttpRequest')) {
            return new global.XMLHttpRequest();
        }
        if (global.hasOwnProperty('ActiveXObject')) {
            return new global.ActiveXObject('Microsoft.XMLHTTP');
        }
        throw new Error('This browser does not support AJAX.');
    };

    token = function () {
     // This function is mainly a placeholder for more elaborate security
     // measures that we may choose to implement in the future. It needs some
     // more error checking, though ...
        var args, secret;
        args = parseArgs();
        secret = null;
        if (args.hasOwnProperty('token')) {
            if ((typeof args.token === 'string') && (args.token.length > 0)) {
                secret = args.token;
                if (global.hasOwnProperty('localStorage')) {
                    global.localStorage.setItem('QMACHINE_token', secret);
                }
                token = function () {
                    return secret;
                };
                return token();
            }
        }
        if (global.hasOwnProperty('localStorage')) {
            secret = global.localStorage.getItem('QMACHINE_token');
         /*
        } else if (global.hasOwnProperty('moz_indexedDB')) {
         // (placeholder: see http://goo.gl/XArgc)
        } else if (global.hasOwnProperty('webkitIndexedDB')) {
         // (placeholder: see http://goo.gl/XArgc)
        } else if (hOP(global, 'window', 'cookie')) {
         // (placeholder)
        } else {
         // (placeholder)
         */
        }
        args.token = (secret === null) ? Q.uuid() : secret;
        relaunch(args);
        return;
    };

    when = Q.when;

    write = function (key, $val) {
     // This function needs documentation.
     //
     // NOTE: Since 'revision' only exists in this function, how should I pass
     // errors back to the user?
     //
        var revision, y;
        revision = avar({val: undefined});
        y = avar();
        revision.onready = function (evt) {
         // This function reads the revision number from CouchDB in such a way
         // as to avoid 404 errors entirely -- I can't figure out how to keep
         // those from cluttering Chrome's developer console. A more efficient
         // way would use a HEAD request, but efficiency isn't the goal here.
            var req, url;
            req = request();
            url = global.location.protocol + '//' + global.location.host +
                '/db/_all_docs?key="' + key + '"&include_docs=false';
            req.onreadystatechange = function () {
             // This function doesn't fail if the status code returned isn't
             // 200 because we're only interested in getting the revision
             // number. If something really important has failed, it is highly
             // probable that it's going to fail again during the 'when' ;-)
                var temp;
                if (req.readyState === 4) {
                    if (req.status === 200) {
                        temp = JSON.parse(req.responseText).rows[0];
                        if (temp !== undefined) {
                            revision.val = temp.value.rev;
                        }
                    }
                    return evt.exit();
                }
                return;
            };
            req.open('GET', url, true);
            req.send(null);
            return;
        };
        when(revision, y).areready = function (evt) {
         // This function implements an HTTP PUT request.
            /*jslint nomen: true */
            var doc, req, temp, url;
            doc = {
                '_id':  key,
                '_rev': revision.val,
                $avar:  $val,
                token:  token()
            };
            req = request();
            temp = JSON.parse($val).val;
            url = global.location.protocol + '//' + global.location.host +
                '/db/' + key;
            if ((temp !== null) && (temp !== undefined) &&
                    (temp.hasOwnProperty('status'))) {
             // This simplifies Qmachine's 'queue' filter in CouchDB.
                doc.status = temp.status;
            }
            req.onreadystatechange = function () {
             // This function needs documentation.
                if (req.readyState === 4) {
                    if (req.status === 201) {
                        y.val = JSON.parse(req.responseText);
                        return evt.exit();
                    } else {
                        return evt.fail(req.responseText);
                    }
                }
                return;
            };
            req.open('PUT', url, true);
            req.setRequestHeader('Content-type', 'application/json');
            req.send(JSON.stringify(doc));
            return;
        };
        return y;
    };

 // Initialization

    Q.init({
        queue:  queue,
        read:   read,
        write:  write
    });

    token();

 // Browser configuration

    if (global.hasOwnProperty('document')) {
     // This part would probably be cleaner with jQuery ...
        (function () {
            var options = ['volunteer', 'pulse'];
            ply(options).by(function (key, val) {
             // This function is necessary because I need to close inside a
             // loop, which is error-prone without functional iteration.
                var temp = global.document.getElementById(val);
                if (temp !== null) {
                    temp.onclick = function () {
                        var obj = {};
                        obj[val] = this.checked;
                        return relaunch(obj);
                    };
                }
                return;
            });
            return;
        }());
    }

 // Demonstrations

    if (parseArgs().volunteer === true) {
        global.console.log('Thanks for volunteering!');
        (function f() {
         // This function just keeps things moving :-)
            var dt, g, x;
            dt = 1000;
            x = Q.volunteer();
            g = x.onerror;
            x.onerror = function (message) {
             // This function demonstrates that "errors" are not always a big
             // deal, and that Quanah lets you handle errors however you want.
                if ((typeof g === 'function') && (g instanceof Function)) {
                    g(message);
                }
                if (message !== 'Nothing to do ...') {
                    global.console.error(message);
                }
                global.setTimeout(f, dt);
                return;
            };
            x.onready = function (evt) {
             // This function provides instant gratification :-)
                global.console.log('Completed task: ' + x.key);
                global.setTimeout(f, dt);
                return evt.exit();
            };
            if (parseArgs().pulse === true) {
                global.console.log('(pulse)');
            }
            return;
        }());
    } else {
        global.console.log('Run "demo()" for a live example :-)');
        (function f() {
         // This function just keeps things moving :-)
            var x = avar();
            x.onerror = function (message) {
             // I don't how this can possibly go wrong anyway ...
                global.console.error(message);
                global.setTimeout(f, 1000);
                return;
            };
            x.onready = function (evt) {
             // This function runs locally because it closes over 'f' :-)
                global.setTimeout(f, 1000);
                return evt.exit();
            };
            if (parseArgs().pulse === true) {
                global.console.log('(pulse)');
            }
            return;
        }());
    }

 // That's all, folks!

    return;

}());

//- vim:set syntax=javascript:
<|endoftext|>


<commit_before>// target elements with the "draggable" class
interact('.draggable')
    .draggable({
        // allow dragging of multple elements at the same time
        max: Infinity,

        // call this function on every dragmove event
        onmove: function (event) {
            var target = event.target,
                // keep the dragged position in the data-x/data-y attributes
                x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
                y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

            // translate the element
            target.style.webkitTransform =
            target.style.transform =
                'translate(' + x + 'px, ' + y + 'px)';

            // update the posiion attributes
            target.setAttribute('data-x', x);
            target.setAttribute('data-y', y);

						target.classList.add('moving');
        },
        // call this function on every dragend event
        onend: function (event) {
            var textEl = event.target.querySelector('p');

            textEl && (textEl.textContent =
                'moved a distance of '
                + (Math.sqrt(event.dx * event.dx +
                             event.dy * event.dy)|0) + 'px');

					event.target.classList.remove('moving');
        }
    })
    // enable inertial throwing
    .inertia(false)
    // keep the element within the area of it's parent
    .restrict({
        drag: "content",
        endOnly: true,
        elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    });

    // allow more than one interaction at a time
    interact.maxInteractions(Infinity);

// enable draggables to be dropped into this
interact('.dropzone').dropzone({
    // only accept elements matching this CSS selector
    accept: ['#module1', '#module2', '#module3'],
    // Require a 75% element overlap for a drop to be possible
    overlap: 0.75,

    // listen for drop related events:

    ondropactivate: function (event) {
        // add active dropzone feedback
        event.target.classList.add('drop-active');
    },
    ondragenter: function (event) {
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

        // feedback the possibility of a drop
        dropzoneElement.classList.add('drop-target');
        draggableElement.classList.add('can-drop');
        //draggableElement.textContent = 'Dragged in';
    },
    ondragleave: function (event) {
        // remove the drop feedback style
        event.target.classList.remove('drop-target');
        event.relatedTarget.classList.remove('can-drop');
        //event.relatedTarget.textContent = 'Dragged out';
    },
    ondrop: function (event) {
        //event.relatedTarget.textContent = 'Dropped';
    },
    ondropdeactivate: function (event) {
        // remove active dropzone feedback
        event.target.classList.remove('drop-active');
        event.target.classList.remove('drop-target');
    }
});
<commit_msg>Added debug messages for modules dropped into dropzones<commit_after>// target elements with the "draggable" class
interact('.draggable')
    .draggable({
        // allow dragging of multple elements at the same time
        max: Infinity,

        // call this function on every dragmove event
        onmove: function (event) {
            var target = event.target,
                // keep the dragged position in the data-x/data-y attributes
                x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
                y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

            // translate the element
            target.style.webkitTransform =
            target.style.transform =
                'translate(' + x + 'px, ' + y + 'px)';

            // update the posiion attributes
            target.setAttribute('data-x', x);
            target.setAttribute('data-y', y);

						target.classList.add('moving');
        },
        // call this function on every dragend event
        onend: function (event) {
            var textEl = event.target.querySelector('p');

            textEl && (textEl.textContent =
                'moved a distance of '
                + (Math.sqrt(event.dx * event.dx +
                             event.dy * event.dy)|0) + 'px');

					event.target.classList.remove('moving');
        }
    })
    // enable inertial throwing
    .inertia(false)
    // keep the element within the area of it's parent
    .restrict({
        drag: "content",
        endOnly: true,
        elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    });

    // allow more than one interaction at a time
    interact.maxInteractions(Infinity);

// enable draggables to be dropped into this
interact('.dropzone').dropzone({
    // only accept elements matching this CSS selector
    accept: ['#module1', '#module2', '#module3'],
    // Require a 75% element overlap for a drop to be possible
    overlap: 0.75,

    // listen for drop related events:

    ondropactivate: function (event) {
        // add active dropzone feedback
        event.target.classList.add('drop-active');
    },
    ondragenter: function (event) {
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

        // feedback the possibility of a drop
        dropzoneElement.classList.add('drop-target');
        draggableElement.classList.add('can-drop');
        //draggableElement.textContent = 'Dragged in';
    },
    ondragleave: function (event) {
        // remove the drop feedback style
        event.target.classList.remove('drop-target');
        event.relatedTarget.classList.remove('can-drop');
        //event.relatedTarget.textContent = 'Dragged out';
    },
    ondrop: function (event) {
        var draggableElement = event.relatedTarget,
            dropzoneElement = event.target;

			console.log(draggableElement.id + " dropped into " + dropzoneElement.id);

    },
    ondropdeactivate: function (event) {
        // remove active dropzone feedback
        event.target.classList.remove('drop-active');
        event.target.classList.remove('drop-target');
    }
});
<|endoftext|>


<commit_before>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Linking,
  Platform,
  Dimensions,
  BackAndroid,
  AsyncStorage,
  Image,
} from 'react-native';

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob

const JSONStream = RNFetchBlob.JSONStream
const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.10.0',
  run : true,
  expand : false,
  timeout : 20000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs
let prefix = ((Platform.OS === 'android') ? 'file://' : '')
let begin = Date.now()

describe('json stream via HTTP', (report, done) => {

  let count = 0
  JSONStream(`${TEST_SERVER_URL}/public/json-dummy.json`).node('name', (name) => {
    count++
    if(Date.now() - begin < 100)
    return
    begin = Date.now()
    report(<Info key="report" uid="100">
      <Text>{count} records</Text>
    </Info>)
    done()
  })

})

describe('json stream via fs', (report, done) => {

  let fetch2 = new RNFetchBlob.polyfill.Fetch({
    auto : true
  })
  let res = null
  let count = 0

  RNFetchBlob.config({
    fileCache : true
  })
  .fetch('GET',`${TEST_SERVER_URL}/public/json-dummy.json`)
  .then((resp) => {
    res = resp
    JSONStream({
      url : RNFetchBlob.wrap(res.path()),
      headers : { bufferSize : 10240 }
    }).node('name', (name) => {
      count++
      if(Date.now() - begin < 100)
      return
      begin = Date.now()
      report(<Info key="report" uid="100">
        <Text>{count} records</Text>
      </Info>)
      done()
    })
  })
})

describe('cookie test', (report, done) => {
  let time = Date.now()
  RNFetchBlob.fetch('GET', `${TEST_SERVER_URL}/cookie/${time}`)
  .then((res) => RNFetchBlob.net.getCookies(`${TEST_SERVER_URL}`))
  .then((cookies) => {
    let result = /cookieName\=[^;]+/.exec(cookies[0])
    console.log(result, 'cookieName=' + time)
    report(<Assert key="cookie should not be empty"
      expect={'cookieName=' + time}
      actual={result[0]}/>)
    done()
  })

})

describe('SSL test #159', (report, done) => {
  RNFetchBlob.config({
    trusty : true
    })
    .fetch('GET', `${TEST_SERVER_URL_SSL}/public/github.png`, {
      'Cache-Control' : 'no-store'
    })
    .then(res => {
      report(<Assert
        key="trusty request should pass"
        expect={true}
        actual={true}/>)
      return RNFetchBlob.fetch('GET',`${TEST_SERVER_URL_SSL}/public/github.png`)
    })
    .catch(e => {
      report(<Assert
        key="non-trusty request should not pass"
        expect={true}
        actual={true}/>)
      done()
    })
})

describe('#171 appendExt verify', (report, done) => {

  RNFetchBlob.config({
    fileCache : true,
    appendExt : 'png'
  })
  .fetch('GET', `${TEST_SERVER_URL}/public/github.png`, {
    'Cache-Control' : 'no-store'
  })
  .then(res => {
    console.log(res.path())
    report(<Assert
      key="extension appended to tmp path"
      actual={/.png$/.test(res.path())}
      expect={true}/>)
    return fs.stat(res.path())
  })
  .then(stat => {
    report(<Assert
      key="verify the file existence"
      expect="23975"
      actual={stat.size} />)
    done()
  })

})

describe('#173 issue with append option', (report, done) => {
  let dest = dirs.DocumentDir + '/tmp' + Date.now()
  RNFetchBlob.config({
    path : dest,
    overwrite : true
  })
  .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #1"
      expect="23975"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
      overwrite : false
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #2"
      expect="47950"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
      overwrite : true
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #3"
      expect="23975"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="it should successfully overwrite existing file without config"
      expect="23975"
      actual={stat.size}/>)
    done()
  })

})

describe('#171 verification ', (report, done) => {

  RNFetchBlob
    .config({
      session: 'SESSION_NAME',
      fileCache: true,
      appendExt: 'mp4'
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/cat-fu.mp4`)
    .then(res => {
      console.log(res.path())
    })

})
<commit_msg>Change test case<commit_after>import RNTest from './react-native-testkit/'
import React from 'react'
import RNFetchBlob from 'react-native-fetch-blob'
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Linking,
  Platform,
  Dimensions,
  BackAndroid,
  AsyncStorage,
  Image,
} from 'react-native';

window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = RNFetchBlob.polyfill.Blob

const JSONStream = RNFetchBlob.JSONStream
const fs = RNFetchBlob.fs
const { Assert, Comparer, Info, prop } = RNTest
const describe = RNTest.config({
  group : '0.10.0',
  run : true,
  expand : false,
  timeout : 20000,
})
const { TEST_SERVER_URL, TEST_SERVER_URL_SSL, FILENAME, DROPBOX_TOKEN, styles } = prop()
const dirs = RNFetchBlob.fs.dirs
let prefix = ((Platform.OS === 'android') ? 'file://' : '')
let begin = Date.now()

describe('json stream via HTTP', (report, done) => {

  let count = 0
  JSONStream(`${TEST_SERVER_URL}/public/json-dummy.json`).node('name', (name) => {
    count++
    if(Date.now() - begin < 100)
    return
    begin = Date.now()
    report(<Info key="report" uid="100">
      <Text>{count} records</Text>
    </Info>)
    done()
  })

})

describe('json stream via fs', (report, done) => {

  let fetch2 = new RNFetchBlob.polyfill.Fetch({
    auto : true
  })
  let res = null
  let count = 0

  RNFetchBlob.config({
    fileCache : true
  })
  .fetch('GET',`${TEST_SERVER_URL}/public/json-dummy.json`)
  .then((resp) => {
    res = resp
    JSONStream({
      url : RNFetchBlob.wrap(res.path()),
      headers : { bufferSize : 10240 }
    }).node('name', (name) => {
      count++
      if(Date.now() - begin < 100)
      return
      begin = Date.now()
      console.log(count);
      // report(<Info key="report" uid="100">
      //   <Text>{count} records</Text>
      // </Info>)
      // done()
    })
  })
})

describe('cookie test', (report, done) => {
  let time = Date.now()
  RNFetchBlob.fetch('GET', `${TEST_SERVER_URL}/cookie/${time}`)
  .then((res) => RNFetchBlob.net.getCookies(`${TEST_SERVER_URL}`))
  .then((cookies) => {
    let result = /cookieName\=[^;]+/.exec(cookies[0])
    console.log(result, 'cookieName=' + time)
    report(<Assert key="cookie should not be empty"
      expect={'cookieName=' + time}
      actual={result[0]}/>)
    done()
  })

})

describe('SSL test #159', (report, done) => {
  RNFetchBlob.config({
    trusty : true
    })
    .fetch('GET', `${TEST_SERVER_URL_SSL}/public/github.png`, {
      'Cache-Control' : 'no-store'
    })
    .then(res => {
      report(<Assert
        key="trusty request should pass"
        expect={true}
        actual={true}/>)
      return RNFetchBlob.fetch('GET',`${TEST_SERVER_URL_SSL}/public/github.png`)
    })
    .catch(e => {
      report(<Assert
        key="non-trusty request should not pass"
        expect={true}
        actual={true}/>)
      done()
    })
})

describe('#171 appendExt verify', (report, done) => {

  RNFetchBlob.config({
    fileCache : true,
    appendExt : 'png'
  })
  .fetch('GET', `${TEST_SERVER_URL}/public/github.png`, {
    'Cache-Control' : 'no-store'
  })
  .then(res => {
    console.log(res.path())
    report(<Assert
      key="extension appended to tmp path"
      actual={/.png$/.test(res.path())}
      expect={true}/>)
    return fs.stat(res.path())
  })
  .then(stat => {
    report(<Assert
      key="verify the file existence"
      expect="23975"
      actual={stat.size} />)
    done()
  })

})

describe('#173 issue with append option', (report, done) => {
  let dest = dirs.DocumentDir + '/tmp' + Date.now()
  RNFetchBlob.config({
    path : dest,
    overwrite : true
  })
  .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #1"
      expect="23975"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
      overwrite : false
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #2"
      expect="47950"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
      overwrite : true
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="file size check #3"
      expect="23975"
      actual={stat.size}/>)
    return RNFetchBlob.config({
      path : dest,
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/github.png`)
  })
  .then((res) => fs.stat(res.path()))
  .then((stat) => {
    report(<Assert
      key="it should successfully overwrite existing file without config"
      expect="23975"
      actual={stat.size}/>)
    done()
  })

})

describe('#171 verification ', (report, done) => {

  RNFetchBlob
    .config({
      session: 'SESSION_NAME',
      fileCache: true,
      appendExt: 'mp4'
    })
    .fetch('GET', `${TEST_SERVER_URL}/public/cat-fu.mp4`)
    .then(res => {
      console.log(res.path())
    })

})
<|endoftext|>


<commit_before>;
(function() {

  var api = "https://jsonplaceholder.typicode.com";
  var userId = 1; // default to JSONPlaceholder API

  var postJquery = function() {
    $("#btn-submit-1").click(function() {
      var title = $("#title-1").val();
      var body = $("#body-1").val();
      $.ajax({
        type: 'POST',
        url: api + '/posts',
        dataType: "json",
        data: {
          title: title,
          body: body,
          userId: userId
        },
        success: function(data) {
          console.log("Content added!", data); //the new item is returned with an ID
          $("#res-1").html("
" + JSON.stringify(data) + "
");
          $("#form-1")[0].reset();
        },
        error: function(data) {
          console.log("Content not added!", data); //the new item is returned with an ID
          $("#res-1").html("
Error " + JSON.stringify(data) + "
");
        }
      });
    });
  }();

  var postJS = function() {
    document.getElementById("btn-submit-2").addEventListener("click", function() {
      var title = document.getElementById("title-2").value;
      var body = document.getElementById("body-2").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title + "&body=" + body + "&userId=" + userId;
      var url = api + "/posts";

      http.open("POST", url, true);

      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 201) {
          console.log("Content added!", http.responseText);
          document.getElementById("res-2").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-2").reset();
        } else {
          console.log("User not added!", http.responseText);
          document.getElementById("res-2").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
    }
      http.send(params);
    });
  }();

  var putJS = function() {
    document.getElementById("btn-submit-3").addEventListener("click", function() {
      var id = document.getElementById("id-3").value;
      var title = document.getElementById("title-3").value;
      var body = document.getElementById("body-3").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title + "&body=" + body + "&userId=" + userId + "&id=" + id;
      var url = api + "/posts/" + id;

      http.open("PUT", url, true);

      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
          console.log("Content updated!", http.responseText);
          document.getElementById("res-3").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-3").reset();
        } else {
          console.log("Content not updated!", http.responseText);
          document.getElementById("res-3").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
    }
      http.send(params);
    });
  }();

  var patchJS = function() {
    document.getElementById("btn-submit-4").addEventListener("click", function() {
      var id = document.getElementById("id-4").value;
      var title = document.getElementById("title-4").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title;
      var url = api + "/posts/" + id;

      http.open("PATCH", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
          console.log("Content updated!", http.responseText);
          document.getElementById("res-4").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-4").reset();
        } else {
          console.log("Content not updated!", http.responseText);
          document.getElementById("res-4").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
      }
      http.send(params);
    });
  }();

  var getOneItemJS = function() {
    document.getElementById("btn-submit-5").addEventListener("click", function() {
      var id = document.getElementById("id-5").value;
      var http = new XMLHttpRequest();
      var url = api + "/posts/" + id;

      http.open("GET", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
            console.log("Content loaded!", http.responseText);
            document.getElementById("res-5").innerHTML = "
" + http.responseText + "
";
            document.getElementById("form-5").reset();
          } else {
            console.log("Content not updated!", http.responseText);
            document.getElementById("res-5").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
          }
        }
      }
      http.send(null);
    });
  }();

  var getAllItensFilterJS = function() {
    document.getElementById("btn-submit-6").addEventListener("click", function() {
      var http = new XMLHttpRequest();
      var url = api + "/users";

      http.open("GET", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
            console.log("Users loaded!", http.responseText);
            var obj = JSON.parse(http.responseText);
            var result = obj.map(function(a) {
              var filterParam = document.getElementById("filter-6").value;
              return a[filterParam];
            });
            document.getElementById("res-6").innerHTML = "
" + result.toString().replace(/,/g, "; ") + "
";
          } else {
            console.log("Users not loaded!", http.responseText);
            document.getElementById("res-6").innerHTML = "
Error " + http.status + "
";
          }
        }
      };

      http.send(null);
    });
  }();

  var oAuthCodeGrant = function(){
    var CLIENT_ID = "NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA";
    var REDIRECT_URI = "//danvitoriano.github.io/rest-api-examples/index.html";
    var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');
    // var REDIRECT_URI = http://localhost:3000/

    document
    .querySelector("#btn-submit-7")
    .addEventListener("click", function(){
      // window.location = "//danvitoriano.auth0.com/auth?response_type=code&client_id=" + CLIENT_ID + "&redirect_uri=" + REDIRECT_URI;
      lock.show();
    });
  }();

})();
<commit_msg>add lock.on authentication<commit_after>;
(function() {

  var api = "https://jsonplaceholder.typicode.com";
  var userId = 1; // default to JSONPlaceholder API

  var postJquery = function() {
    $("#btn-submit-1").click(function() {
      var title = $("#title-1").val();
      var body = $("#body-1").val();
      $.ajax({
        type: 'POST',
        url: api + '/posts',
        dataType: "json",
        data: {
          title: title,
          body: body,
          userId: userId
        },
        success: function(data) {
          console.log("Content added!", data); //the new item is returned with an ID
          $("#res-1").html("
" + JSON.stringify(data) + "
");
          $("#form-1")[0].reset();
        },
        error: function(data) {
          console.log("Content not added!", data); //the new item is returned with an ID
          $("#res-1").html("
Error " + JSON.stringify(data) + "
");
        }
      });
    });
  }();

  var postJS = function() {
    document.getElementById("btn-submit-2").addEventListener("click", function() {
      var title = document.getElementById("title-2").value;
      var body = document.getElementById("body-2").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title + "&body=" + body + "&userId=" + userId;
      var url = api + "/posts";

      http.open("POST", url, true);

      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 201) {
          console.log("Content added!", http.responseText);
          document.getElementById("res-2").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-2").reset();
        } else {
          console.log("User not added!", http.responseText);
          document.getElementById("res-2").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
    }
      http.send(params);
    });
  }();

  var putJS = function() {
    document.getElementById("btn-submit-3").addEventListener("click", function() {
      var id = document.getElementById("id-3").value;
      var title = document.getElementById("title-3").value;
      var body = document.getElementById("body-3").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title + "&body=" + body + "&userId=" + userId + "&id=" + id;
      var url = api + "/posts/" + id;

      http.open("PUT", url, true);

      http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
          console.log("Content updated!", http.responseText);
          document.getElementById("res-3").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-3").reset();
        } else {
          console.log("Content not updated!", http.responseText);
          document.getElementById("res-3").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
    }
      http.send(params);
    });
  }();

  var patchJS = function() {
    document.getElementById("btn-submit-4").addEventListener("click", function() {
      var id = document.getElementById("id-4").value;
      var title = document.getElementById("title-4").value;
      var http = new XMLHttpRequest();
      var params = "title=" + title;
      var url = api + "/posts/" + id;

      http.open("PATCH", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
          console.log("Content updated!", http.responseText);
          document.getElementById("res-4").innerHTML = "
" + http.responseText + "
";
          document.getElementById("form-4").reset();
        } else {
          console.log("Content not updated!", http.responseText);
          document.getElementById("res-4").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
        }
      }
      }
      http.send(params);
    });
  }();

  var getOneItemJS = function() {
    document.getElementById("btn-submit-5").addEventListener("click", function() {
      var id = document.getElementById("id-5").value;
      var http = new XMLHttpRequest();
      var url = api + "/posts/" + id;

      http.open("GET", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
            console.log("Content loaded!", http.responseText);
            document.getElementById("res-5").innerHTML = "
" + http.responseText + "
";
            document.getElementById("form-5").reset();
          } else {
            console.log("Content not updated!", http.responseText);
            document.getElementById("res-5").innerHTML = "
Error " + http.status + ". ID must be from 1 to 100.
";
          }
        }
      }
      http.send(null);
    });
  }();

  var getAllItensFilterJS = function() {
    document.getElementById("btn-submit-6").addEventListener("click", function() {
      var http = new XMLHttpRequest();
      var url = api + "/users";

      http.open("GET", url, true);

      http.onload = function() {
        if (http.readyState === http.DONE) {
          if (http.status === 200) {
            console.log("Users loaded!", http.responseText);
            var obj = JSON.parse(http.responseText);
            var result = obj.map(function(a) {
              var filterParam = document.getElementById("filter-6").value;
              return a[filterParam];
            });
            document.getElementById("res-6").innerHTML = "
" + result.toString().replace(/,/g, "; ") + "
";
          } else {
            console.log("Users not loaded!", http.responseText);
            document.getElementById("res-6").innerHTML = "
Error " + http.status + "
";
          }
        }
      };

      http.send(null);
    });
  }();

  var oAuthCodeGrant = function(){
    var CLIENT_ID = "NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA";
    var REDIRECT_URI = "//danvitoriano.github.io/rest-api-examples/index.html";
    var lock = new Auth0Lock('NhfvAEwAkCzlIzi2iH1NMcSylPTWTxPA', 'danvitoriano.auth0.com');
    // var REDIRECT_URI = http://localhost:3000/

    document
    .querySelector("#btn-submit-7")
    .addEventListener("click", function(){
      // window.location = "//danvitoriano.auth0.com/auth?response_type=code&client_id=" + CLIENT_ID + "&redirect_uri=" + REDIRECT_URI;
      lock.show();
    });

    lock.on("authenticated", function(authResult) {
      lock.getProfile(authResult.idToken, function(error, profile) {
        if (error) {
          // Handle error
          console.log("Handle error");
          return;
        }
        localStorage.setItem('id_token', authResult.idToken);
        // Display user information
        console.log("Display user information");
        show_profile_info(profile);
      });
    });
  }();

})();
<|endoftext|>


<commit_before>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

var Client = require('../'),
    Catbox = require('catbox'),
    expect = require('chai').expect;

// Tests

describe('catbox', function() {

  var getClient = function getClient() {
    return new Catbox.Client(Client, {partition: 'default'});
  };

  it('should create a connection', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);
      done();
    });
  });

  it('should end the connection', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);
      client.stop();
      expect(client.isReady()).to.equal(false);
      done();
    });
  });

  it('should set and get an item', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo', segment: 'test'};
      client.set(key, 'bar', 1000, function(err) {
        expect(err).to.equal(undefined);

        client.get(key, function(err, result) {
          expect(err).to.equal(null);
          expect(result).to.be.a('object');
          expect(result.item).to.equal('bar');
          done();
        });
      });
    });
  });

  it('should set and get an item (30 days)', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo30c', segment: 'test'};
      client.drop(key, function(err) {
        expect(err).to.equal(undefined);

        client.set(key, 'bar', 1000*60*60*24*30, function(err) {
          expect(err).to.equal(undefined);

          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.be.a('object');
            expect(result.item).to.equal('bar');
            done();
          });
        });
      });
    });
  });

  it('should set and get an item (>30 days)', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo31c', segment: 'test'};
      client.drop(key, function(err) {
        expect(err).to.equal(undefined);

        client.set(key, 'bar', 1000*60*60*24*31, function(err) {
          expect(err).to.equal(undefined);

          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.be.a('object');
            expect(result.item).to.equal('bar');
            done();
          });
        });
      });
    });
  });

  it('should fail to set an item due to value', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'bar', segment: 'test'},
          val = {'baz': 'qux'};
      val.val = val;
      client.set(key, val, 1000, function(err) {
        expect(err.message).to.equal('Converting circular structure to JSON');
        done();
      });
    });
  });

  it('should fail to set an item due to key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.set(null, {}, 1000, function(err) {
        expect(err.message).to.equal('Invalid key');
        done();
      });
    });
  });

  it('should fail to set an item due to ttl', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.set({id: 'baz', segment: 'test'}, {}, 'boom', function(err) {
        expect(err.message).to.equal('invalid ttl');
        done();
      });
    });
  });

  it('should fail to get an item due to key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.get({}, function(err, result) {
        expect(err.message).to.equal('Invalid key');
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  it('should drop an item', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'qux', segment: 'test'};
      client.set(key, 'foo', 1000, function(err) {
        expect(err).to.equal(undefined);
        client.drop(key, function(err) {
          expect(err).to.equal(undefined);
          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.equal(null);
            done();
          });
        });
      });
    });
  });

  it('should fail to drop an item due to key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.drop({}, function(err, result) {
        expect(err.message).to.equal('Invalid key');
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  it('should validate segment', function(done) {
    var client = getClient();

    expect(client.validateSegmentName().message).to.equal('invalid segment name');
    expect(client.validateSegmentName('\0').message).to.equal('invalid segment name');
    expect(client.validateSegmentName(' ').message).to.equal('invalid segment name');
    expect(client.validateSegmentName('\t').message).to.equal('invalid segment name');
    done();
  });

  it('should return null - ttl', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foobar', segment: 'test'};
      client.set(key, 'boom', 1, function(err) {
        expect(err).to.equal(undefined);
        setTimeout(function() {
          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.equal(null);
            done();
          });
        }, 2);
      });
    });
  });

});<commit_msg>Update catbox tests<commit_after>/* jslint node: true */
/* global describe: false, it: false */
'use strict';

var Client = require('../'),
    Catbox = require('catbox'),
    expect = require('chai').expect;

// Tests

describe('catbox', function() {

  var getClient = function getClient() {
    return new Catbox.Client(Client);
  };

  it('should create a connection', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);
      done();
    });
  });

  it('should end the connection', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);
      client.stop();
      expect(client.isReady()).to.equal(false);
      done();
    });
  });

  it('should set and get an item', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo', segment: 'test'};
      client.set(key, 'bar', 1000, function(err) {
        expect(err).to.equal(undefined);

        client.get(key, function(err, result) {
          expect(err).to.equal(null);
          expect(result).to.be.a('object');
          expect(result.item).to.equal('bar');
          done();
        });
      });
    });
  });

  it('should set and get an item (30 days)', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo30', segment: 'test'};
      client.drop(key, function(err) {
        expect(err).to.equal(undefined);

        client.set(key, 'bar', 1000*60*60*24*30, function(err) {
          expect(err).to.equal(undefined);

          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.be.a('object');
            expect(result.item).to.equal('bar');
            done();
          });
        });
      });
    });
  });

  it('should set and get an item (>30 days)', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foo31', segment: 'test'};
      client.drop(key, function(err) {
        expect(err).to.equal(undefined);

        client.set(key, 'bar', 1000*60*60*24*31, function(err) {
          expect(err).to.equal(undefined);

          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.be.a('object');
            expect(result.item).to.equal('bar');
            done();
          });
        });
      });
    });
  });

  it('should fail to set an item due to value', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'bar', segment: 'test'},
          val = {'baz': 'qux'};
      val.val = val;
      client.set(key, val, 1000, function(err) {
        expect(err.message).to.equal('Converting circular structure to JSON');
        done();
      });
    });
  });

  it('should fail to set an item due to key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.set(null, {}, 1000, function(err) {
        expect(err.message).to.equal('Invalid key');
        done();
      });
    });
  });

  it('should fail to set an item due to ttl', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.set({id: 'baz', segment: 'test'}, {}, 'boom', function(err) {
        expect(err.message).to.equal('invalid ttl');
        done();
      });
    });
  });

  it('should return error - key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.get(null, function(err, result) {
        expect(err).to.equal(null);
        expect(result).to.equal(null);

        client.get({}, function(err, result) {
          expect(err.message).to.equal('Invalid key');
          expect(result).to.equal(undefined);
          done();
        });
      });
    });
  });

  it('should drop an item', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'qux', segment: 'test'};
      client.set(key, 'foo', 1, function(err) {
        expect(err).to.equal(undefined);
        client.drop(key, function(err) {
          expect(err).to.equal(undefined);
          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.equal(null);
            done();
          });
        });
      });
    });
  });

  it('should fail to drop an item due to key', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      client.drop({}, function(err, result) {
        expect(err.message).to.contain('Invalid key');
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  it('should validate segment', function(done) {
    var client = getClient();

    expect(client.validateSegmentName().message).to.equal('invalid segment name');
    expect(client.validateSegmentName('\n').message).to.equal('invalid segment name');
    expect(client.validateSegmentName('\0').message).to.equal('invalid segment name');
    expect(client.validateSegmentName('\t').message).to.equal('invalid segment name');
    expect(client.validateSegmentName(' ').message).to.equal('invalid segment name');
    done();
  });

  it('should return null - ttl', function(done) {
    var client = getClient();

    client.start(function(err) {
      expect(err).to.equal(undefined);
      expect(client.isReady()).to.equal(true);

      var key = {id: 'foobar', segment: 'test'};
      client.set(key, 'boom', 1, function(err) {
        expect(err).to.equal(undefined);
        setTimeout(function() {
          client.get(key, function(err, result) {
            expect(err).to.equal(null);
            expect(result).to.equal(null);
            done();
          });
        }, 2000);
      });
    });
  });

});<|endoftext|>


<commit_before>var privateToken;

function handleLoginResult(loggedIn, token) {
  privateToken = token;
  jQuery('#login #private-token').val(privateToken); //FIXME remove
}
<commit_msg>Rename login callback<commit_after>var privateToken;

function oauthPluginHandleLoginResult(loggedIn, token) {
  privateToken = token;
  jQuery('#login #private-token').val(privateToken); //FIXME remove
}
<|endoftext|>