text:
"use strict";
var test = require("blue-tape");
var methods = require("methods");
var FormData = require("form-data");
var fs_1 = require("fs");
var path_1 = require("path");
var popsicle = require("../common");
var SHORTHAND_METHODS = [
    'get',
    'post',
    'put',
    'patch',
    'del'
];
var SUPPORTED_METHODS = typeof window === 'object' ? [
    'get',
    'post',
    'put',
    'patch',
    'delete'
] : methods.filter(function (method) { return method !== 'connect'; });
var METHODS_WITHOUT_BODY = ['connect', 'head', 'options'];
var REMOTE_URL = 'http://localhost:' + process.env.PORT;
var REMOTE_HTTPS_URL = 'https://localhost:' + process.env.HTTPS_PORT;
var EXAMPLE_BODY = {
    username: 'blakeembrey',
    password: 'hunter2'
};
var BOUNDARY_REGEXP = /^multipart\/form-data; boundary=([^;]+)/;
var MULTIPART_SEP = '\r\n';
var supportsStatusText = parseFloat(process.version.replace(/^v/, '')) >= 0.12;
test('should expose default functions', function (t) {
    t.equal(typeof popsicle, 'object');
    t.equal(typeof popsicle.Request, 'function');
    t.equal(typeof popsicle.Response, 'function');
    t.equal(typeof popsicle.form, 'function');
    t.equal(typeof popsicle.jar, 'function');
    SHORTHAND_METHODS.forEach(function (method) {
        t.equal(typeof popsicle[method], 'function');
    });
    t.end();
});
test('throw an error when no options are provided', function (t) {
    t.throws(function () { return popsicle.request({}); }, /url must be a string/i);
    t.end();
});
test('create a popsicle#Request instance', function (t) {
    var req = popsicle.request('/');
    t.ok(req instanceof popsicle.Request);
    req.set('Test', 'Test');
    t.equal(req.rawHeaders.length, 2);
    req.remove('Test');
    t.equal(req.rawHeaders.length, 0);
    return req.then(null, function () { return undefined; });
});
test('use the same response in promise chains', function (t) {
    var req = popsicle.get(REMOTE_URL + '/echo');
    t.plan(13);
    return req
        .then(function (res) {
        t.ok(res instanceof popsicle.Response);
        t.ok(typeof res.url === 'string' || res.url == null);
        t.ok(Array.isArray(res.rawHeaders));
        t.equal(typeof res.headers, 'object');
        t.equal(typeof res.status, 'number');
        t.equal(typeof res.get, 'function');
        t.equal(typeof res.name, 'function');
        t.equal(typeof res.type, 'function');
        t.equal(typeof res.statusType, 'function');
        t.equal(typeof res.toJSON, 'function');
        t.deepEqual(Object.keys(req.toJSON()), ['url', 'method', 'headers', 'body', 'timeout']);
        t.deepEqual(Object.keys(res.toJSON()), ['url', 'headers', 'body', 'status', 'statusText']);
        return req
            .then(function (res2) {
            t.equal(res, res2);
        });
    });
});
test('clone a request instance', function (t) {
    var req = popsicle.get(REMOTE_URL + '/echo/header/x-example');
    req.use(function (self, next) {
        self.set('X-Example', 'foobar');
        return next();
    });
    return Promise.all([req, req.clone()])
        .then(function (res) {
        t.notEqual(res[0], res[1]);
        t.equal(res[0].body, 'foobar');
        t.equal(res[0].body, res[1].body);
    });
});
test('methods', function (t) {
    t.test('use node-style callbacks', function (t) {
        t.plan(1);
        return popsicle.request(REMOTE_URL + '/echo')
            .exec(function (err, res) {
            t.ok(res instanceof popsicle.Response);
            t.end(err);
        });
    });
    t.test('allow methods to be passed in', function (t) {
        return Promise.all(SUPPORTED_METHODS.map(function (method) {
            return popsicle.request({
                url: REMOTE_URL + '/echo/method',
                method: method
            })
                .then(function (res) {
                t.equal(res.status, 200);
                t.equal(res.body, METHODS_WITHOUT_BODY.indexOf(method) === -1 ? method.toUpperCase() : '');
            });
        }));
    });
});
test('allow usage of method shorthands', function (t) {
    return Promise.all(SHORTHAND_METHODS.map(function (method) {
        return popsicle[method](REMOTE_URL + '/echo/method')
            .then(function (res) {
            t.equal(res.status, 200);
            t.equal(res.body, method === 'del' ? 'DELETE' : method.toUpperCase());
        });
    }));
});
test('response status', function (t) {
    t.test('5xx', function (t) {
        return popsicle.request(REMOTE_URL + '/error')
            .then(function (res) {
            t.equal(res.status, 500);
            t.equal(res.statusType(), 5);
            if (supportsStatusText) {
                t.equal(res.statusText, 'Internal Server Error');
            }
        });
    });
    t.test('4xx', function (t) {
        return popsicle.request(REMOTE_URL + '/not-found')
            .then(function (res) {
            t.equal(res.status, 404);
            t.equal(res.statusType(), 4);
            if (supportsStatusText) {
                t.equal(res.statusText, 'Not Found');
            }
        });
    });
    t.test('2xx', function (t) {
        return popsicle.request(REMOTE_URL + '/no-content')
            .then(function (res) {
            t.equal(res.status, 204);
            t.equal(res.statusType(), 2);
            if (supportsStatusText) {
                t.equal(res.statusText, 'No Content');
            }
        });
    });
});
test('request headers', function (t) {
    t.test('always send user agent', function (t) {
        return popsicle.request(REMOTE_URL + '/echo/header/user-agent')
            .then(function (res) {
            var regexp = process.browser ?
                /^Mozilla\/.+$/ :
                /^Popsicle \(https:\/\/github\.com\/blakeembrey\/popsicle\)$/;
            t.ok(regexp.test(res.body));
        });
    });
    if (!process.browser) {
        t.test('send a custom user agent header', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/echo/header/user-agent',
                headers: {
                    'User-Agent': 'foobar'
                }
            })
                .then(function (res) {
                t.equal(res.body, 'foobar');
            });
        });
        if (!/^v0\.10/.test(process.version)) {
            t.test('case sensitive headers', function (t) {
                return popsicle.get({
                    url: REMOTE_URL + '/raw-headers',
                    headers: {
                        'Raw-Header': 'test'
                    }
                })
                    .then(function (res) {
                    t.ok(res.body.indexOf('Raw-Header') > -1, 'raw headers sent with original casing');
                });
            });
        }
    }
});
test('response headers', function (t) {
    t.test('parse', function (t) {
        return popsicle.request(REMOTE_URL + '/notfound')
            .then(function (res) {
            t.equal(res.type(), 'text/html');
            t.equal(res.get('Content-Type'), 'text/html; charset=utf-8');
        });
    });
});
test('request body', function (t) {
    t.test('send post data', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: 'example data',
            headers: {
                'content-type': 'application/octet-stream'
            }
        })
            .then(function (res) {
            t.equal(res.body, 'example data');
            t.equal(res.status, 200);
            t.equal(res.type(), 'application/octet-stream');
            if (supportsStatusText) {
                t.equal(res.statusText, 'OK');
            }
        });
    });
    t.test('should automatically send objects as json', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: EXAMPLE_BODY
        })
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            t.deepEqual(res.body, EXAMPLE_BODY);
            t.equal(res.type(), 'application/json');
        });
    });
    t.test('should send as form encoded when header is set', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: EXAMPLE_BODY,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .use(popsicle.plugins.parse('urlencoded'))
            .then(function (res) {
            t.deepEqual(res.body, EXAMPLE_BODY);
            t.equal(res.name('Content-Type'), 'content-type');
            t.equal(res.type(), 'application/x-www-form-urlencoded');
        });
    });
    t.test('host objects', function (t) {
        t.test('form data', function (t) {
            function validateResponse(res) {
                var boundary = BOUNDARY_REGEXP.exec(res.headers['content-type'])[1];
                var body = [
                    '--' + boundary,
                    'Content-Disposition: form-data; name="username"',
                    '',
                    EXAMPLE_BODY.username,
                    '--' + boundary,
                    'Content-Disposition: form-data; name="password"',
                    '',
                    EXAMPLE_BODY.password,
                    '--' + boundary + '--'
                ].join(MULTIPART_SEP) + MULTIPART_SEP;
                t.equal(res.body, body);
            }
            t.test('should create form data instance', function (t) {
                var form = popsicle.form(EXAMPLE_BODY);
                t.ok(form instanceof FormData);
                return popsicle.request({
                    url: REMOTE_URL + '/echo',
                    method: 'POST',
                    body: form
                }).then(validateResponse);
            });
            t.test('should stringify to form data when set as multipart', function () {
                return popsicle.request({
                    url: REMOTE_URL + '/echo',
                    method: 'POST',
                    body: EXAMPLE_BODY,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(validateResponse);
            });
        });
    });
});
test('query', function (t) {
    t.test('should stringify and send query parameters', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo/query',
            query: EXAMPLE_BODY
        })
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            t.deepEqual(res.body, EXAMPLE_BODY);
        });
    });
    t.test('should stringify and append to query object', function (t) {
        var req = popsicle.request({
            url: REMOTE_URL + '/echo/query?query=true',
            query: EXAMPLE_BODY
        });
        var query = {
            query: 'true',
            username: 'blakeembrey',
            password: 'hunter2'
        };
        var fullUrl = REMOTE_URL + '/echo/query?query=true&username=blakeembrey&password=hunter2';
        t.equal(req.url, fullUrl);
        t.deepEqual(req.query, query);
        return req
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            if (typeof window === 'undefined') {
                t.equal(res.url, fullUrl);
            }
            t.deepEqual(res.body, query);
        });
    });
    t.test('should accept query as a string', function (t) {
        var req = popsicle.request({
            url: REMOTE_URL + '/echo/query',
            query: 'query=true'
        });
        t.equal(req.url, REMOTE_URL + '/echo/query?query=true');
        t.deepEqual(req.query, { query: 'true' });
        return req
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            t.deepEqual(res.body, { query: 'true' });
        });
    });
});
test('timeout', function (t) {
    t.test('should timeout the request when set', function (t) {
        t.plan(3);
        return popsicle.request({
            url: REMOTE_URL + '/delay/1500',
            timeout: 500
        })
            .catch(function (err) {
            t.equal(err.message, 'Timeout of 500ms exceeded');
            t.equal(err.code, 'ETIMEOUT');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
});
test('abort', function (t) {
    t.test('abort before it starts', function (t) {
        var req = popsicle.request(REMOTE_URL + '/echo');
        req.abort();
        t.plan(3);
        return req
            .catch(function (err) {
            t.equal(err.message, 'Request aborted');
            t.equal(err.code, 'EABORT');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
    t.test('abort mid-request', function (t) {
        var req = popsicle.request(REMOTE_URL + '/download');
        t.plan(1);
        setTimeout(function () { return req.abort(); }, 100);
        return req
            .catch(function (err) {
            t.equal(err.code, 'EABORT');
        });
    });
    t.test('no side effects of aborting twice', function (t) {
        var req = popsicle.request(REMOTE_URL + '/download');
        t.plan(3);
        req.abort();
        req.abort();
        return req
            .catch(function (err) {
            t.equal(err.message, 'Request aborted');
            t.equal(err.code, 'EABORT');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
    t.test('abort cloned requests', function (t) {
        var req = popsicle.request(REMOTE_URL + '/download');
        var req2 = req.clone();
        t.plan(2);
        req.abort();
        return Promise.all([
            req.catch(function (err) { return t.equal(err.code, 'EABORT'); }),
            req2.catch(function (err) { return t.equal(err.code, 'EABORT'); })
        ]);
    });
});
test('progress', function (t) {
    t.test('download', function (t) {
        t.test('download progress', function (t) {
            var req = popsicle.request(REMOTE_URL + '/download');
            t.plan(typeof window === 'undefined' ? 3 : 2);
            t.equal(req.downloaded, 0);
            if (typeof window === 'undefined') {
                setTimeout(function () {
                    t.equal(req.downloaded, 0.5);
                }, 100);
            }
            return req
                .then(function () {
                t.equal(req.downloaded, 1);
            });
        });
    });
    t.test('event', function (t) {
        t.test('emit progress events', function (t) {
            var req = popsicle.request({
                url: REMOTE_URL + '/echo',
                body: EXAMPLE_BODY,
                method: 'POST'
            });
            t.plan(3);
            var expected = 0;
            req.on('progress', function () {
                expected += 0.5;
                t.equal(this.completed, expected);
            });
            return req
                .use(popsicle.plugins.parse('json'))
                .then(function (res) {
                t.deepEqual(res.body, EXAMPLE_BODY);
            });
        });
    });
});
test('response body', function (t) {
    t.test('parse json responses', function (t) {
        return popsicle.request(REMOTE_URL + '/json')
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            t.equal(res.type(), 'application/json');
            t.deepEqual(res.body, { username: 'blakeembrey' });
        });
    });
    t.test('parse form encoded responses', function (t) {
        return popsicle.request(REMOTE_URL + '/foo')
            .use(popsicle.plugins.parse('urlencoded'))
            .then(function (res) {
            t.equal(res.type(), 'application/x-www-form-urlencoded');
            t.deepEqual(res.body, { foo: 'bar' });
        });
    });
    t.test('string response by default', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/json'
        })
            .then(function (res) {
            t.equal(res.type(), 'application/json');
            t.equal(res.body, '{"username":"blakeembrey"}');
        });
    });
    t.test('empty response bodies', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'post'
        })
            .then(function (res) {
            t.equal(res.body, '');
        });
    });
    t.test('empty response body with json', function (t) {
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .use(popsicle.plugins.parse('json'))
            .then(function (res) {
            t.equal(res.body, null);
            t.equal(res.type(), 'application/json');
        });
    });
    t.test('throw on unsupported type', function (t) {
        t.plan(2);
        return popsicle.request({
            url: REMOTE_URL + '/text',
            transport: popsicle.createTransport({ type: 'foobar' })
        })
            .catch(function (err) {
            t.equal(err.message, 'Unsupported type: foobar');
            t.equal(err.code, 'ETYPE');
        });
    });
    if (!process.browser) {
        var fs_2 = require('fs');
        var concat_1 = require('concat-stream');
        var filename_1 = require('path').join(__dirname, '../../scripts/server.js');
        var filecontents_1 = fs_2.readFileSync(filename_1, 'utf-8');
        t.test('stream the response body', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/json',
                transport: popsicle.createTransport({ type: 'stream' })
            })
                .then(function (res) {
                t.equal(typeof res.body, 'object');
                return new Promise(function (resolve) {
                    res.body.pipe(concat_1(function (data) {
                        t.equal(data.toString(), '{"username":"blakeembrey"}');
                        return resolve();
                    }));
                });
            });
        });
        t.test('should break when response body is bigger than buffer size', function (t) {
            t.plan(1);
            return popsicle.request(REMOTE_URL + '/urandom')
                .catch(function (err) {
                t.equal(err.code, 'ETOOLARGE');
            });
        });
        t.test('pipe streams', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/echo',
                body: fs_2.createReadStream(filename_1)
            })
                .then(function (res) {
                t.equal(res.body, filecontents_1);
            });
        });
        t.test('pipe streams into forms', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/echo',
                body: popsicle.form({
                    file: fs_2.createReadStream(filename_1)
                })
            })
                .then(function (res) {
                var boundary = BOUNDARY_REGEXP.exec(res.get('content-type'))[1];
                t.equal(res.body, [
                    '--' + boundary,
                    'Content-Disposition: form-data; name="file"; filename="server.js"',
                    'Content-Type: application/javascript',
                    '',
                    filecontents_1,
                    '--' + boundary + '--'
                ].join(MULTIPART_SEP) + MULTIPART_SEP);
            });
        });
        t.test('unzip contents', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/echo/zip',
                body: fs_2.createReadStream(filename_1)
            })
                .then(function (res) {
                t.equal(res.get('Content-Encoding'), 'deflate');
                t.equal(res.body, filecontents_1);
            });
        });
        t.test('unzip with gzip encoding', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/echo/zip',
                body: fs_2.createReadStream(filename_1),
                headers: {
                    'Accept-Encoding': 'gzip'
                }
            })
                .then(function (res) {
                t.equal(res.get('Content-Encoding'), 'gzip');
                t.equal(res.body, filecontents_1);
            });
        });
    }
    else {
        t.test('browser response type', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/text',
                transport: popsicle.createTransport({ type: 'arraybuffer' })
            })
                .then(function (res) {
                t.ok(res.body instanceof ArrayBuffer);
            });
        });
    }
});
test('request errors', function (t) {
    t.test('error when requesting an unknown domain', function (t) {
        t.plan(3);
        return popsicle.request('http://fdahkfjhuehfakjbvdahjfds.fdsa')
            .catch(function (err) {
            t.ok(/Unable to connect/i.exec(err.message));
            t.equal(err.code, 'EUNAVAILABLE');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
    t.test('give a parse error on invalid json response', function (t) {
        t.plan(3);
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: 'username=blakeembrey&password=hunter2',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .use(popsicle.plugins.parse('json'))
            .catch(function (err) {
            t.ok(/Unable to parse response body/i.test(err.message));
            t.equal(err.code, 'EPARSE');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
    t.test('give a parse error on invalid response type', function (t) {
        t.plan(3);
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: 'hello world',
            headers: {
                'Content-Type': 'foo/bar'
            }
        })
            .use(popsicle.plugins.parse('json'))
            .catch(function (err) {
            t.equal(err.message, 'Unhandled response type: foo/bar');
            t.equal(err.code, 'EPARSE');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
    t.test('give a stringify error on invalid request body', function (t) {
        var obj = {};
        t.plan(3);
        obj.obj = obj;
        return popsicle.request({
            url: REMOTE_URL + '/echo',
            method: 'POST',
            body: obj
        })
            .catch(function (err) {
            t.ok(/Unable to stringify request body/i.test(err.message));
            t.equal(err.code, 'ESTRINGIFY');
            t.ok(err.popsicle instanceof popsicle.Request);
        });
    });
});
test('plugins', function (t) {
    t.test('modify the request', function (t) {
        var req = popsicle.request(REMOTE_URL + '/echo');
        t.plan(1);
        req.use(function (self, next) {
            t.equal(self, req);
            return next();
        });
        return req;
    });
});
test('request flow', function (t) {
    t.test('before', function (t) {
        t.test('run a function before opening the request', function (t) {
            var req = popsicle.request(REMOTE_URL + '/echo');
            t.plan(2);
            req.use(function (self, next) {
                t.equal(self, req);
                t.equal(typeof next, 'function');
                return next();
            });
            return req;
        });
        t.test('fail the request before starting', function (t) {
            var req = popsicle.request(REMOTE_URL + '/echo');
            t.plan(1);
            req.use(function () {
                throw new Error('Hello world!');
            });
            return req
                .catch(function (err) {
                t.equal(err.message, 'Hello world!');
            });
        });
        t.test('accept a promise to delay the request', function (t) {
            var req = popsicle.request({
                url: REMOTE_URL + '/echo',
                method: 'POST',
                body: 'success'
            });
            t.plan(2);
            req.use(function (self, next) {
                return new Promise(function (resolve) {
                    setTimeout(function () {
                        t.equal(self, req);
                        resolve();
                    }, 10);
                }).then(next);
            });
            return req
                .then(function (res) {
                t.equal(res.body, 'success');
            });
        });
    });
    test('after', function (t) {
        t.test('run after the response', function (t) {
            var req = popsicle.request(REMOTE_URL + '/echo');
            t.plan(1);
            req.use(function (_, next) {
                return next()
                    .then(function (res) {
                    t.ok(res instanceof popsicle.Response);
                    return res;
                });
            });
            return req;
        });
    });
});
if (!process.browser) {
    test('cookie jar', function (t) {
        t.test('should work with a cookie jar', function (t) {
            var cookie;
            var instance = popsicle.defaults({
                transport: popsicle.createTransport({
                    jar: popsicle.jar()
                })
            });
            return instance(REMOTE_URL + '/cookie')
                .then(function (res) {
                t.notOk(res.get('Cookie'));
                t.ok(res.get('Set-Cookie'));
                cookie = res.get('Set-Cookie').split(/ *; */, 1)[0];
                return instance(REMOTE_URL + '/echo');
            })
                .then(function (res) {
                t.equal(res.get('Cookie'), cookie);
                t.notOk(res.get('Set-Cookie'));
            });
        });
        t.test('should update over redirects', function (t) {
            var instance = popsicle.defaults({
                transport: popsicle.createTransport({
                    jar: popsicle.jar()
                })
            });
            return instance(REMOTE_URL + '/cookie/redirect')
                .then(function (res) {
                t.ok(/^new=cookie/.test(res.body));
            });
        });
    });
}
test('override request mechanism', function (t) {
    return popsicle.request({
        url: '/foo',
        transport: {
            open: function () {
                return Promise.resolve({
                    url: '/foo',
                    body: 'testing',
                    headers: {},
                    status: 200,
                    statusText: 'OK'
                });
            }
        }
    })
        .then(function (res) {
        t.equal(res.body, 'testing');
    });
});
if (!process.browser) {
    test('redirect', function (t) {
        t.test('should follow 302 redirect with get', function (t) {
            return popsicle.request(REMOTE_URL + '/redirect')
                .then(function (res) {
                t.equal(res.body, 'welcome get');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
        t.test('should follow 301 redirect with post', function (t) {
            return popsicle.post(REMOTE_URL + '/redirect/code/301')
                .then(function (res) {
                t.equal(res.body, 'welcome get');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
        t.test('should follow 303 redirect with post', function (t) {
            return popsicle.post({
                url: REMOTE_URL + '/redirect/code/303',
                body: { foo: 'bar' }
            })
                .then(function (res) {
                t.equal(res.body, 'welcome get');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
        t.test('disable following redirects', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/redirect',
                transport: popsicle.createTransport({
                    followRedirects: false
                })
            })
                .then(function (res) {
                t.equal(res.status, 302);
                t.ok(/\/redirect$/.test(res.url));
            });
        });
        t.test('default maximum redirects of 5', function (t) {
            t.plan(2);
            return popsicle.request(REMOTE_URL + '/redirect/6')
                .catch(function (err) {
                t.equal(err.message, 'Exceeded maximum of 5 redirects');
                t.equal(err.code, 'EMAXREDIRECTS');
            });
        });
        t.test('change maximum redirects', function (t) {
            return popsicle.request({
                url: REMOTE_URL + '/redirect/6',
                transport: popsicle.createTransport({
                    maxRedirects: 10
                })
            })
                .then(function (res) {
                t.equal(res.body, 'welcome get');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
        t.test('support head redirects with 307', function (t) {
            return popsicle.head(REMOTE_URL + '/redirect/code/307')
                .then(function (res) {
                t.equal(res.body, '');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
        t.test('block 307/308 redirects by default', function (t) {
            return popsicle.post(REMOTE_URL + '/redirect/code/307')
                .then(function (res) {
                t.equal(res.status, 307);
                t.ok(/\/redirect\/code\/307$/.test(res.url));
            });
        });
        t.test('support user confirmed redirects with 308', function (t) {
            return popsicle.post({
                url: REMOTE_URL + '/redirect/code/308',
                transport: popsicle.createTransport({
                    confirmRedirect: function () {
                        return true;
                    }
                })
            })
                .then(function (res) {
                t.equal(res.body, 'welcome post');
                t.equal(res.status, 200);
                t.ok(/\/destination$/.test(res.url));
            });
        });
    });
}
if (!process.browser) {
    test('https reject unauthorized', function (t) {
        t.plan(1);
        return popsicle.get({
            url: "" + REMOTE_HTTPS_URL
        })
            .catch(function (err) {
            t.equal(err.code, 'EUNAVAILABLE');
        });
    });
    test('https ca option', function (t) {
        return popsicle.get({
            url: "" + REMOTE_HTTPS_URL,
            transport: popsicle.createTransport({
                ca: fs_1.readFileSync(path_1.join(__dirname, '../../scripts/support/ca-crt.pem'))
            })
        })
            .then(function (res) {
            t.equal(res.body, 'Success');
        });
    });
    test('https disable reject unauthorized', function (t) {
        return popsicle.get({
            url: "" + REMOTE_HTTPS_URL,
            transport: popsicle.createTransport({
                rejectUnauthorized: false
            })
        })
            .then(function (res) {
            t.equal(res.body, 'Success');
        });
    });
}
//# sourceMappingURL=index.js.map


text:
package rfc

import (
	"strings"

	"github.com/zmap/zcrypto/x509"
	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/util"
)

type invalidEmail struct{}

/************************************************************************
RFC 5280: 4.2.1.6
 When the subjectAltName extension contains an Internet mail address,
   the address MUST be stored in the rfc822Name.  The format of an
   rfc822Name is a "Mailbox" as defined in Section 4.1.2 of [RFC2821].
   A Mailbox has the form "Local-part@Domain".  Note that a Mailbox has
   no phrase (such as a common name) before it, has no comment (text
   surrounded in parentheses) after it, and is not surrounded by "<" and
   ">".  Rules for encoding Internet mail addresses that include
   internationalized domain names are specified in Section 7.5.
************************************************************************/

func init() {
	lint.RegisterLint(&lint.Lint{
		Name:          "e_ext_san_rfc822_format_invalid",
		Description:   "Email MUST NOT be surrounded with `<>`, and there must be no trailing comments in `()`",
		Citation:      "RFC 5280: 4.2.1.6",
		Source:        lint.RFC5280,
		EffectiveDate: util.RFC2459Date,
		Lint:          NewInvalidEmail,
	})
}

func NewInvalidEmail() lint.LintInterface {
	return &invalidEmail{}
}

func (l *invalidEmail) CheckApplies(c *x509.Certificate) bool {
	return util.IsExtInCert(c, util.SubjectAlternateNameOID)
}

func (l *invalidEmail) Execute(c *x509.Certificate) *lint.LintResult {
	for _, str := range c.EmailAddresses {
		if str == "" {
			continue
		}
		if strings.Contains(str, " ") {
			return &lint.LintResult{Status: lint.Error}
		} else if str[0] == '<' || str[len(str)-1] == ')' {
			return &lint.LintResult{Status: lint.Error}
		}
	}
	return &lint.LintResult{Status: lint.Pass}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/flickr_swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/flickr_card"/>
    </android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>


text:
//
//  Vehicle.h
//  Ex102SeekingNeural
//
//  Created by Ilya Rostovtsev on 3/24/14.
//
//

#ifndef __Ex102SeekingNeural__Vehicle__
#define __Ex102SeekingNeural__Vehicle__

#include <vector>
#include "Perceptron.h"

using namespace std;
using namespace ci;

class Vehicle
{
public:
    Vehicle( const int n, const float x, const float y, shared_ptr< Rand > random );
    void update();
    void draw() const;
    void applyForce( const Vec2f& force );
    void steer( const vector< Vec2f >& targets );
    Vec2f seek( const Vec2f& target );

private:
    Perceptron brain;
    Vec2f location;
    Vec2f velocity;
    Vec2f acceleration;
    Vec2f desired;
    float r, maxforce, maxspeed, theta;

};

#endif /* defined(__Ex102SeekingNeural__Vehicle__) */


text:
package uk.nhs.hdn.common.reflection.toString;

public abstract class AbstractToString
{
	protected AbstractToString()
	{
	}

	@Override
	public String toString()
	{
		return ToStringHelper.toString(this);
	}
}


text:
What actions can you take that can do the most to improve your digital security?

For some good background information, check out the Electronic Frontier Foundation's [Surveillance Self-Defence](https://ssd.eff.org/) docs. There's even a fairly comprehensive guide for [activists and protestors](https://ssd.eff.org/en/playlist/activist-or-protester).

There is a more detailed document focusing on strategies for securing your computer [here](guidelines.md).

## Smartphones

 - [ ] Enable an unlock code or passphrase on your phone, preferably more than 4 digits.
 - [ ] Enable encryption on your phone. [iphone](https://ssd.eff.org/en/module/how-encrypt-your-iphone), [android](https://www.howtogeek.com/141953/how-to-encrypt-your-android-phone-and-why-you-might-want-to/)
 - [ ] Install an encrypted communications applications (e.g., [Signal](https://whispersystems.org/)) and move to using this for SMS and phone calls when communicating about sensitive issues.
 - [ ] Turn off location services on your phone for photos. (Posting photos to social media can identify where you live, work, meet, protest, etc.).
 - [ ] Consider removing social media applications from your phone (facebook, twitter, instagram, snapchat, etc.); get in the habit of communicating by other means; be intentional about what you post to social media, and where you post from.
 - [ ] Read up on information related to [attending protests in the USA](https://ssd.eff.org/en/playlist/activist-or-protester#attending-protests-united-states).
   - [ ] Consider pulling your phone battery or SIM card if you are attending a protest where surveillance is likely.

## Computers

 - [ ] Enable a [strong password](https://www.schneier.com/blog/archives/2014/03/choosing_secure_1.html) on your computer. Booting up your computer should require a password. Unlocking your screen saver should require a password. Get in the habit of locking your screen whenever you are not sitting at it.
 - [ ] Encrypt your computer hard drive.
    - [Apple FileVault](https://support.apple.com/en-us/HT204837)
    - For Microsoft Windows, the story is more complicated:
      - "[Encrypting Windows Hard Drives](https://www.schneier.com/blog/archives/2015/06/encrypting_wind.html)"
      - "[Microsoft may have your encryption key; here's how to take it back](https://arstechnica.com/information-technology/2015/12/microsoft-may-have-your-encryption-key-heres-how-to-take-it-back/)"
      - "[How to Enable Full-Disk Encryption on Windows 10](https://www.howtogeek.com/234826/how-to-enable-full-disk-encryption-on-windows-10/)"
 - [ ] Install a [virus scanner](http://www.pcmag.com/article2/0,2817,2372364,00.asp) if you use Microsoft Windows.
 - [ ] Get and use a password manager such as [1Password](https://1password.com/) or [LastPass](https://www.lastpass.com/). Use strong unique passwords for every account.
 - [ ] Enable two-factor authentication (2FA) for your email accounts, DropBox (or Box) account, bank accounts, any domain name registrars.
 - [ ] Install browser tools to disable plugins, ads, and tracking:
   - Chrome:
     - [Adblock Plus](https://adblockplus.org/)
     - [Flashcontrol](https://chrome.google.com/webstore/detail/flashcontrol/mfidmkgnfgnkihnjeklbekckimkipmoe?hl=en)
     - [Ghostery](https://www.ghostery.com/try-us/download-browser-extension/)
     - [Privacy Badger](https://www.eff.org/privacybadger)
     - [uBlock Origin](https://chrome.google.com/webstore/detail/ublock-origin/cjpalhdlnbpafiamejdnhcphjbkeiagm?hl=en)
     - [Vanilla Cookie Manager](https://chrome.google.com/webstore/detail/vanilla-cookie-manager/gieohaicffldbmiilohhggbidhephnjj?hl=en)
 - [ ] Sign up for [ProtonMail](https://protonmail.com/) for secure email communications.

### Guidelines

 - [ ] Use your password manager for all passwords. Make strong unique passwords for every account you use.
 - [ ] Don't share accounts, don't share passwords, don't write down passwords.
 - [ ] Be extremely careful with links received by email. Go to the site in question by typing in the relevant URL, rather than clicking an email link.
 - [ ] Use SSL everywhere. Use your password manager to fill in passwords. If the password manager cannot find your credentials, perhaps you're not at the site you think you're visiting.
 - [ ] Don't share thumb drives and USB devices with people you don't strongly trust.
 - [ ] Try not to use public or shared computers.


text:
import {
  LOAD_ABOUT,
}              from 'redux/about/types';

const defaultState = '';

export default function aboutReducer(state = defaultState, action) {
  switch (action.type) {
    case LOAD_ABOUT:
      return action.payload.text;
    default:
      return state;
  }
}


text:
/* globals describe, beforeEach, it, expect, module, inject, jQuery */

/**
 * @license angularjs-bootstrap-datetimepicker
 * Copyright 2016 Knight Rider Consulting, Inc. http://www.knightrider.com
 * License: MIT
 *
 * @author        Dale "Ducky" Lotts
 * @since        7/21/13
 */

describe('configureOn', function () {
  'use strict'
  var $rootScope
  var $compile
  beforeEach(module('ui.bootstrap.datetimepicker'))
  beforeEach(inject(function (_$compile_, _$rootScope_) {
    $compile = _$compile_
    $rootScope = _$rootScope_
    $rootScope.date = null
  }))

  describe('throws exception', function () {
    it('if value is an empty string', function () {
      function compile () {
        $compile('<datetimepicker data-ng-model="date" data-datetimepicker-config="{ configureOn: \'\' }"></datetimepicker>')($rootScope)
        $rootScope.$digest()
      }

      expect(compile).toThrow(new Error('configureOn must not be an empty string'))
    })
    it('if value is numeric', function () {
      function compile () {
        $compile('<datetimepicker data-ng-model="date" data-datetimepicker-config="{ configureOn: 3 }"></datetimepicker>')($rootScope)
        $rootScope.$digest()
      }

      expect(compile).toThrow(new Error('configureOn must be a string'))
    })
  })
  describe('does NOT throw exception', function () {
    it('if value is a string', function () {
      $compile('<datetimepicker data-ng-model="date" data-datetimepicker-config="{ configureOn: \'foo\' }"></datetimepicker>')($rootScope)
    })
  })
  describe('configureOn event', function () {
    it('causes view to reflect changes to configuration', function () {
      $rootScope.config = {
        data: {
          configureOn: 'config-changed'
        }
      }

      var element = $compile('<datetimepicker data-ng-model="date" data-datetimepicker-config="config.data"></datetimepicker>')($rootScope)
      $rootScope.$digest()

      expect(jQuery('.day-view', element).length).toBe(1)

      $rootScope.config.data.startView = 'minute'

      $rootScope.$broadcast('config-changed')
      $rootScope.$digest()

      expect(jQuery('.day-view', element).length).toBe(0)
    })
  })
})


text:
import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type

from datasets import Dataset
from tqdm import tqdm

from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator

NON_ALPHA = re.compile("[^A-Za-z_0-9]")
# parameters used in DuplicationIndex
MIN_NUM_TOKENS = 10
NUM_PERM = 256

def get_min_hash(tokens: List[str]) -> Optional[MinHash]:
    """Compute the MinHash of a code snippet."""
    if len(tokens) < MIN_NUM_TOKENS:
        return None
    min_hash = MinHash(num_perm=NUM_PERM)
    for token in set(tokens):
        min_hash.update(token.encode())
    return min_hash

def get_tokens(code: str) -> Set[str]:
    """Tokenize a code snippet."""
    return set([t for t in NON_ALPHA.split(code) if len(t.strip()) > 0])

class DuplicationIndex:
    def __init__(
        self,
        *,
        duplication_jaccard_threshold: float = 0.85,
    ):
        self._duplication_jaccard_threshold = duplication_jaccard_threshold
        self._num_perm = NUM_PERM
        self._index = MinHashLSH(threshold=self._duplication_jaccard_threshold, num_perm=self._num_perm)

        self._duplicate_clusters = defaultdict(set)

    def add(self, code_key: Tuple, min_hash: MinHash) -> None:
        """Add a key to _index (MinHashLSH)
        the min_hash is used to query closest matches based on the jaccard_threshold.
        The new key is either added to a existing cluster of one close match,
        or a new cluster is created. The clusters created in this way, depend on the order of add.

        Args:
            code_key (Tuple of (index, repo_name, path)):
                Theoritically any hasbale key. Here we use a tuple to retrieve the information later.
            min_hash: MinHash of the code_key.
        """
        close_duplicates = self._index.query(min_hash)
        if code_key in self._index.keys:
            print(f"Duplicate key {code_key}")
            return

        self._index.insert(code_key, min_hash)
        if len(close_duplicates) > 0:
            for base_duplicate in close_duplicates:
                if base_duplicate in self._duplicate_clusters:
                    self._duplicate_clusters[base_duplicate].add(code_key)
                    break
            else:
                self._duplicate_clusters[close_duplicates[0]].add(code_key)

    def get_duplicate_clusters(self) -> List[List[Dict]]:
        """Export the duplicate clusters.
        For each cluster, the first element is the base element of the cluster.
        The base element has an estimation jaccard similarity higher than the threshold with all the other elements.

        Returns:
            duplicate_clusters (List[List[Dict]]):
                List of duplicate clusters.
        """
        duplicate_clusters = []
        for base, duplicates in self._duplicate_clusters.items():
            cluster = [base] + list(duplicates)
            # reformat the cluster to be a list of dict
            cluster = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster]
            duplicate_clusters.append(cluster)
        return duplicate_clusters

    def save(self, filepath) -> None:
        duplicate_clusters = self.get_duplicate_clusters()
        with open(filepath, "w") as f:
            json.dump(duplicate_clusters, f)

def _compute_min_hash(element):
    index, data = element
    min_hash = get_min_hash([t for t in NON_ALPHA.split(data["content"]) if len(t.strip()) > 0])
    if min_hash is not None:
        return (index, data["repo_name"], data["path"]), min_hash

def minhash_iter(dataset_iterator: Type[Dataset]):
    with mp.Pool() as pool:
        for data in pool.imap_unordered(
            _compute_min_hash,
            ThreadedIterator(dataset_iterator, max_queue_size=10000),
            chunksize=100,
        ):
            if data is not None:
                yield data

def make_duplicate_clusters(dataset_iterator: Type[Dataset], jaccard_threshold: float):
    """Find duplicate clusters in the dataset in two steps:
    1. Compute MinHash for each code snippet. MinHash is a tool for fast jaccard similarity estimation.
    This step is computed using an asynchronous multiprocessing pool, minhash_iter
    2. Find duplicate clusters. The computed MinHash is added sequentially to the DuplicationIndex.
    This step cannot be parallelized. So using asynchronous thread in the previous step helps to speed up the process.
    """
    di = DuplicationIndex(duplication_jaccard_threshold=jaccard_threshold)

    for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(dataset_iterator)), max_queue_size=100)):
        di.add(filename, min_hash)

    # Returns a List[Cluster] where Cluster is List[str] with the filenames.
    return di.get_duplicate_clusters()

def jaccard_similarity(code1: str, code2: str) -> float:
    """Compute the Jaccard similarity of two code snippets."""
    tokens1 = get_tokens(code1)
    tokens2 = get_tokens(code2)
    return len(tokens1 & tokens2) / len(tokens1 | tokens2)

_shared_dataset = None

def _find_cluster_extremes_shared(cluster, jaccard_threshold):
    """Find a reduced cluster such that each code in the origin cluster is similar to at least one code in the reduced cluster.
    Two codes are similar if their Jaccard similarity is above the threshold.

    Args:
        cluster (List[dict]):
           cluster is a list of dict, each dict contains the following keys:
                - base_index
                - repo_name
                - path
            This is a typical output of DuplicationIndex.get_duplicate_clusters()
        jaccard_threshold (float):
            threshold for Jaccard similarity.
            Two codes are similar if their Jaccard similarity is above the threshold.

    Returns:
        extremes (List[dict]):
            A reduced representation of the cluster. The field copies is added to each dict.
            The copies field indicates the number of similar codes in the cluster for a extreme.
    """
    extremes = []
    for element1 in cluster:
        code1 = _shared_dataset[element1["base_index"]]["content"]
        for element2 in extremes:
            code2 = _shared_dataset[element2["base_index"]]["content"]
            if jaccard_similarity(code1, code2) >= jaccard_threshold:
                element2["copies"] += 1
                break
        else:
            element1["copies"] = 1
            extremes.append(element1)
    return extremes

def find_extremes(cluster_list, dataset, jaccard_threshold):
    """Call the _find_cluster_extremes_shared function in a parallel fashion.

    Args:
        cluster_list (List[List[Dict]]):
            each cluster is a list of dicts with the key base_index,
            referring to the index of the base code in the dataset.
        dataset (Type[Dataset]):
            dataset is used to access the content of the code snippets,
            using the base_index from the cluster_list.
            dataset is shared between all the processes using a glabal variable (any other way to share the dataset?),
            otherwise the multi processing is not speeded up.
        jaccard_threshold (float):
            the threshold for the jaccard similarity. The default value is 0.85

    Returns:
        extremes_list (List[Dict]):
            Each cluster is reduced to extremes.
            See _find_cluster_extremes_shared for the definition of extremes.
    """
    global _shared_dataset
    _shared_dataset = dataset
    extremes_list = []
    f = partial(_find_cluster_extremes_shared, jaccard_threshold=jaccard_threshold)
    with mp.Pool() as pool:
        for extremes in tqdm(
            pool.imap_unordered(
                f,
                cluster_list,
            ),
            total=len(cluster_list),
        ):
            extremes_list.append(extremes)
    return extremes_list

def deduplicate_dataset(
    dataset: Type[Dataset], jaccard_threshold: float = 0.85
) -> Tuple[Type[Dataset], List[List[Dict]]]:
    """Deduplicate the dataset using minhash and jaccard similarity.
    This function first generate duplicate clusters, then each cluster
    is reduced to the extremes that are similar to the other elements in the cluster.
    Codes are called similar if their Jaccard similarity is greater than jaccard_threshold (0.85 default).

    Args:
        dataset (Type[Dataset]):
            The dataset to deduplicate.
        jaccard_threshold (float, default=0.85):
            jaccard threshold to determine if two codes are similar

    Returns:
        ds_dedup (Type[Dataset]):
            The deduplicated dataset.
        duplicate_clusters (List[List[Dict]]):
            The list of duplicate clusters.
            Each cluster is a list of dicts with the following keys:
            - base_index : int
                The index of the code in the original dataset.
            - repo_name : str
            - path : str
            - copies : int
                The number of copies of the code in the cluster. (find_cluster_extremes)
            - is_extreme : bool
                Whether the code is an extreme in the cluster.
            All the codes in the cluster are removed from the dataset except the extremes.

    Example:
        >>> from datasets import load_dataset
        >>> from minhash_deduplication import deduplicate_dataset
        >>> ds = load_dataset("lvwerra/codeparrot-clean", split="train")
        >>> ds_dedup, duplicate_clusters = deduplicate_dataset(ds, jaccard_threshold=0.85)
    """
    duplicate_clusters = make_duplicate_clusters(dataset, jaccard_threshold)
    duplicate_indices = set(x["base_index"] for cluster in duplicate_clusters for x in cluster)
    extreme_dict = {}
    extremes_clusters = find_extremes(duplicate_clusters, dataset, jaccard_threshold)
    for extremes in extremes_clusters:
        for element in extremes:
            extreme_dict[element["base_index"]] = element
    remove_indices = duplicate_indices - set(extreme_dict.keys())
    ds_filter = dataset.filter(lambda x, idx: idx not in remove_indices, with_indices=True)

    # update duplicate_clusters
    for cluster in duplicate_clusters:
        for element in cluster:
            element["is_extreme"] = element["base_index"] in extreme_dict
            if element["is_extreme"]:
                element["copies"] = extreme_dict[element["base_index"]]["copies"]

    print(f"Original dataset size: {len(dataset)}")
    print(f"Number of duplicate clusters: {len(duplicate_clusters)}")
    print(f"Files in duplicate cluster: {len(duplicate_indices)}")
    print(f"Unique files in duplicate cluster: {len(extreme_dict)}")
    print(f"Filtered dataset size: {len(ds_filter)}")

    return ds_filter, duplicate_clusters


text:
$.fn.ebPanelNavHashtag = function( options ) {

	var theW = $(window).width(); //console.log(theW);
	var theH = $(window).height(); //console.log(theH);
	var headerH = $("header").innerHeight(); //console.log(headerH);
	var dataHash;
	var settings = $.extend({
		wrapperClass: ".eb-wrapper",
		panelClass: ".eb-panel",
		homePanel: "#eb-panel1",
		linkClass: ".eb-link-item",
		activeClass: ".eb-nav-active",
		navClass: ".eb-nav-item",
		headerHeight: headerH,
		layout: "horizontal", // Options: horizontal, vertical, fade
		rememberPanel: false,
		easing : "swing",
		transitionTime: 500,
		onStart: function() {},
		onEnd: function() {}
	 }, options );

	function intialSet () {
		$(settings.wrapperClass).css({height:theH,width:theW});
		$(settings.panelClass).css({width:theW,height:theH-headerH,top:headerH});
	};
	intialSet ();

	if (settings.rememberPanel === true) {
		var oldPanel = window.location.hash; //console.log(oldPanel);
		if(oldPanel != ''){
			settings.homePanel = oldPanel;
		}
	} else {
		history.pushState(null, null, '#');
	};

	if (settings.layout === "horizontal") {
		$(settings.panelClass).css({left: "100%"});
		$(settings.homePanel).addClass("eb-active").css({left: "0"});
		var activeAni = {left: "-100%"},
		    offAni = {left:"100%", display:"none"},
		    locationAni = {left: "0%"}
	};
	if (settings.layout === "vertical") {
		$(settings.panelClass).css({top: "-100%"});
		$(settings.homePanel).addClass("eb-active").css({top: headerH});
		var activeAni = {top: "100%"},
		    offAni = {top:"-100%", display:"none"},
		    locationAni = {top: headerH}
	};
	if (settings.layout === "fade") {
		$(settings.panelClass).css({opacity: 0});
		$(settings.homePanel).addClass("eb-active").css({top: headerH, opacity:1});
		var activeAni = {opacity: 0},
		    offAni = {},
		    locationAni = {opacity: 1}
	};
	function addActive() {
		var findActivePanel = $(".eb-active").attr("id"); //console.log("findActivePanel: " + findActivePanel);
		$('a[data-hash*='+ findActivePanel + ']').parent().addClass(settings.activeClass.slice(1));
	};
	addActive();

	function changePanel(location) {
		settings.onStart.call(this);
		$(".eb-active").stop(true).animate(activeAni, settings.transitionTime, settings.easing, function() {
			$(this).removeClass("eb-active").css(offAni);
		});
		$(location).stop(true).addClass("eb-move").show().animate(locationAni, settings.transitionTime, settings.easing, function() {
			$(this).toggleClass("eb-move eb-active");
			settings.onEnd.call(this);
			addActive();
		});
	};
	function locationHashChanged() {
		dataHash = document.location.hash; //console.log(dataHash);
		if ( dataHash != ''){
			changePanel(dataHash);
		};
	};

	window.onhashchange = locationHashChanged;

	var linksItems = $(settings.linkClass + ", " + settings.navClass + " a"); //console.log(linksItems);

	linksItems.on("click", function(event){
		event.preventDefault();
		dataHash = $(this).attr("data-hash"); //console.log(dataHash);
		if ( !$(dataHash).hasClass("eb-active") && typeof dataHash != 'undefined' )  {
			linksItems.parent().removeClass(settings.activeClass.slice(1));
			window.location.hash = dataHash;
		}
	});

	$(window).on('resize', function(){
		theW = $(window).width();
		theH = $(window).height();
		headerH = $("header").innerHeight();
		intialSet ();
	});

};


text:
module Google
  module Cloud
    module AIPlatform
      module V1
        module Schema
          module Predict
            module Instance
              # Prediction input format for Text Classification.
              # @!attribute [rw] content
              #   @return [::String]
              #     The text snippet to make the predictions on.
              # @!attribute [rw] mime_type
              #   @return [::String]
              #     The MIME type of the text snippet. The supported MIME types are listed
              #     below.
              #     - text/plain
              class TextClassificationPredictionInstance
                include ::Google::Protobuf::MessageExts
                extend ::Google::Protobuf::MessageExts::ClassMethods
              end
            end
          end
        end
      end
    end
  end
end


text:
package com.vmware.af.interop;

import com.vmware.af.VmAfClientNativeException;

public class VmAfUnknownServerException extends VmAfClientNativeException {

   private static final long serialVersionUID = -569152771232536929L;

   public VmAfUnknownServerException(int errCode) {
      super(errCode);

   }
}


text:
// Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//
// This file implements the "bridge" between Java and C++
// for ROCKSDB_NAMESPACE::TransactionDBOptions.

#include <jni.h>

#include "include/org_rocksdb_TransactionDBOptions.h"

#include "rocksdb/utilities/transaction_db.h"

#include "rocksjni/portal.h"

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    newTransactionDBOptions
 * Signature: ()J
 */
jlong Java_org_rocksdb_TransactionDBOptions_newTransactionDBOptions(
    JNIEnv* /*env*/, jclass /*jcls*/) {
  ROCKSDB_NAMESPACE::TransactionDBOptions* opts =
      new ROCKSDB_NAMESPACE::TransactionDBOptions();
  return reinterpret_cast<jlong>(opts);
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    getMaxNumLocks
 * Signature: (J)J
 */
jlong Java_org_rocksdb_TransactionDBOptions_getMaxNumLocks(JNIEnv* /*env*/,
                                                           jobject /*jobj*/,
                                                           jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  return opts->max_num_locks;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    setMaxNumLocks
 * Signature: (JJ)V
 */
void Java_org_rocksdb_TransactionDBOptions_setMaxNumLocks(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle, jlong jmax_num_locks) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  opts->max_num_locks = jmax_num_locks;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    getNumStripes
 * Signature: (J)J
 */
jlong Java_org_rocksdb_TransactionDBOptions_getNumStripes(JNIEnv* /*env*/,
                                                          jobject /*jobj*/,
                                                          jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  return opts->num_stripes;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    setNumStripes
 * Signature: (JJ)V
 */
void Java_org_rocksdb_TransactionDBOptions_setNumStripes(JNIEnv* /*env*/,
                                                         jobject /*jobj*/,
                                                         jlong jhandle,
                                                         jlong jnum_stripes) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  opts->num_stripes = jnum_stripes;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    getTransactionLockTimeout
 * Signature: (J)J
 */
jlong Java_org_rocksdb_TransactionDBOptions_getTransactionLockTimeout(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  return opts->transaction_lock_timeout;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    setTransactionLockTimeout
 * Signature: (JJ)V
 */
void Java_org_rocksdb_TransactionDBOptions_setTransactionLockTimeout(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle,
    jlong jtransaction_lock_timeout) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  opts->transaction_lock_timeout = jtransaction_lock_timeout;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    getDefaultLockTimeout
 * Signature: (J)J
 */
jlong Java_org_rocksdb_TransactionDBOptions_getDefaultLockTimeout(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  return opts->default_lock_timeout;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    setDefaultLockTimeout
 * Signature: (JJ)V
 */
void Java_org_rocksdb_TransactionDBOptions_setDefaultLockTimeout(
    JNIEnv* /*env*/, jobject /*jobj*/, jlong jhandle,
    jlong jdefault_lock_timeout) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  opts->default_lock_timeout = jdefault_lock_timeout;
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    getWritePolicy
 * Signature: (J)B
 */
jbyte Java_org_rocksdb_TransactionDBOptions_getWritePolicy(JNIEnv* /*env*/,
                                                           jobject /*jobj*/,
                                                           jlong jhandle) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  return ROCKSDB_NAMESPACE::TxnDBWritePolicyJni::toJavaTxnDBWritePolicy(
      opts->write_policy);
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    setWritePolicy
 * Signature: (JB)V
 */
void Java_org_rocksdb_TransactionDBOptions_setWritePolicy(JNIEnv* /*env*/,
                                                          jobject /*jobj*/,
                                                          jlong jhandle,
                                                          jbyte jwrite_policy) {
  auto* opts =
      reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
  opts->write_policy =
      ROCKSDB_NAMESPACE::TxnDBWritePolicyJni::toCppTxnDBWritePolicy(
          jwrite_policy);
}

/*
 * Class:     org_rocksdb_TransactionDBOptions
 * Method:    disposeInternal
 * Signature: (J)V
 */
void Java_org_rocksdb_TransactionDBOptions_disposeInternal(JNIEnv* /*env*/,
                                                           jobject /*jobj*/,
                                                           jlong jhandle) {
  delete reinterpret_cast<ROCKSDB_NAMESPACE::TransactionDBOptions*>(jhandle);
}


text:
package pl.touk.hades.sql.exception;

import pl.touk.hades.exception.LoadMeasuringException;
import pl.touk.hades.sql.timemonitoring.MonitorRunLogPrefix;

/**
 * @author Michał Sokołowski
 */
public class SqlExecException extends LoadMeasuringException {
    public SqlExecException(MonitorRunLogPrefix logPrefix, Exception cause) {
        super(logPrefix, cause);
    }

    public SqlExecException(MonitorRunLogPrefix logPrefix) {
        super(logPrefix);
    }
}


text:
<?php

use Cachet\HttpStatus;

class IntegrationTest extends PHPUnit_Framework_TestCase
{
    public function testDeleteAllCache()
    {
        $client = new GuzzleHttp\Client();
        $response = $client->request('DELETE', 'http://localhost/cache');
        $this->assertEquals(HttpStatus::OK_NO_CONTENT, $response->getStatusCode());

        $response = $client->request('GET', 'http://localhost/cache');
        $this->assertEquals(['cache' => []], json_decode($response->getBody(), true));
    }

    /**
     * @depends testDeleteAllCache
     */
    public function testCreateCache()
    {
        $client = new GuzzleHttp\Client();

        // first post
        $data = [
            'key' => 'foo',
            'value' => 'bar'
        ];
        $response = $client->request('POST', 'http://localhost/cache', [
            'body' => json_encode($data)
        ]);

        $this->assertEquals(HttpStatus::CREATED, $response->getStatusCode());
        // ensure the location header is set when a new cache is created
        $this->assertEquals('/cache/foo', $response->getHeaderLine('Location'));

        // second post
        $data = [
            'key' => 'foo2',
            'value' => 'bar'
        ];
        $response = $client->request('POST', 'http://localhost/cache', [
            'body' => json_encode($data)
        ]);
        $this->assertEquals(HttpStatus::CREATED, $response->getStatusCode());
        $this->assertEquals('/cache/foo2', $response->getHeaderLine('Location'));
    }

    /**
     * @depends testCreateCache
     * @depends testDeleteAllCache
     */
    public function testCreateCacheCollision()
    {
        $client = new GuzzleHttp\Client();
        $data = [
            'key' => 'foo',
            'value' => 'bar2'
        ];

        try {
            $client->request('POST', 'http://localhost/cache', [
                'body' => json_encode($data)
            ]);
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::CONFLICT,
                $e->getResponse()->getStatusCode()
            );
        }
    }

    /**
     * @depends testDeleteAllCache
     */
    public function testInvalidPayload()
    {
        $client = new GuzzleHttp\Client();
        $data = [
            'foo'
        ];

        try {
            $client->request('POST', 'http://localhost/cache', [
                'body' => json_encode($data)
            ]);
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_ACCEPTABLE,
                $e->getResponse()->getStatusCode()
            );
        }
    }

    /**
     * @depends testDeleteAllCache
     */
    public function testCacheNotFound()
    {
        $client = new GuzzleHttp\Client();

        try {
            $client->request('GET', 'http://localhost/cache/does_not_exist');
            $this->fail("GET should have thrown a client exception");
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_FOUND,
                $e->getResponse()->getStatusCode()
            );
        }

        try {
            $response = $client->request('PUT', 'http://localhost/cache/does_not_exist', [
                'body' => json_encode(['key' => 'does_not_exist', 'value' => 'bar'])
            ]);

            $this->fail("PUT should have thrown a client exception: ".$response->getStatusCode());
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_FOUND,
                $e->getResponse()->getStatusCode()
            );
        }

        try {
            $client->request('DELETE', 'http://localhost/cache/does_not_exist');
            $this->fail("DELETE should have thrown a client exception");
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_FOUND,
                $e->getResponse()->getStatusCode()
            );
        }
    }

    /**
     * @expectedException GuzzleHttp\Exception\ClientException
     */
    public function testExpiresCache()
    {
        $client = new GuzzleHttp\Client();

        $client->request('PUT', 'http://localhost/cache/foo', [
            'body' => json_encode([
                'key' => 'foo',
                'value' => 'bar with expires',
                'expires' => 2
            ])
        ]);
        sleep(2);
        try {
            $client->request('GET', 'http://localhost/cache/foo');
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_FOUND,
                $e->getResponse()->getStatusCode()
            );

            throw $e;
        }
    }

    /**
     * @depends testExpiresCache
     */
    public function testExpirePutReset()
    {
        $client = new GuzzleHttp\Client();

        $response = $client->request('POST', 'http://localhost/cache', [
            'body' => json_encode([
                'key' => 'expire_test',
                'value' => 'bar with expires',
                'expires' => 2
            ])
        ]);
        $this->assertEquals(HttpStatus::CREATED, $response->getStatusCode());

        sleep(1);

        $client->request('PUT', 'http://localhost/cache/expire_test', [
            'body' => json_encode([
                'key' => 'expire_test',
                'value' => 'bar with expires'
            ])
        ]);

        sleep(1);

        $response = $client->request('GET', 'http://localhost/cache/expire_test');

        $this->assertEquals(HttpStatus::OK, $response->getStatusCode());
        $data = json_decode($response->getBody(), true);
        $expires = $data['expires'];
        $this->assertEquals(date('Y-m-d H:i:s O e', time() + 1), $expires);

        sleep(1);

        try {
            $client->request('GET', 'http://localhost/cache/expire_test');
            $this->fail("GET should have thrown a client exception");
        } catch (GuzzleHttp\Exception\ClientException $e) {
            $this->assertEquals(
                HttpStatus::NOT_FOUND,
                $e->getResponse()->getStatusCode()
            );
        }
    }
}


text:
! { dg-do compile }
!
! PR fortran/33117, PR fortran/46478
! Procedures of a generic interface must be either
! all SUBROUTINEs or all FUNCTIONs.
!

!
! PR fortran/33117
!
module m1
  interface gen
    subroutine sub()            ! { dg-error "all SUBROUTINEs or all FUNCTIONs" }
    end subroutine sub
    function bar()
      real :: bar
    end function bar
  end interface gen
end module

!
! PR fortran/46478
!
MODULE m2
  INTERFACE new_name
    MODULE PROCEDURE func_name
    MODULE PROCEDURE subr_name
  END INTERFACE
CONTAINS
   LOGICAL FUNCTION func_name()  ! { dg-error "all SUBROUTINEs or all FUNCTIONs" }
   END FUNCTION
   SUBROUTINE subr_name()
   END SUBROUTINE
END MODULE

! { dg-final { cleanup-modules "m1 m2" } }


text:
Ders Ekleme

               <?php echo form_open('panel/dersEkle2');?>

                    Ders Adı
                    <input placeholder="#1 HTML'Ye Giriş" name="isim" id="isim" type="text" class="validate">

                    Permalink
                    <input placeholder="html-ye-giris" name="permalink" id="permalink" type="text" class="validate">

                    <select name="konu" id="konu">
                            <?php foreach ($konu as $row) { ?>
                            <option value="<?php echo $row->id;?>"><?php echo $row->konu;?></option>
                            <?php } ?>
                    </select>
                    Konular

                    <textarea id="aciklama" name="aciklama" class="materialize-textarea" placeholder="Ders içeriği <xmp> kod alanı kullanımı"></textarea>
                    Açıklama

                    Kod Blok
                    <textarea id="kodblok" name="kodblok" class="materialize-textarea" placeholder="eski dersten kalan kod"></textarea>

              <?php echo form_submit('dersEkle','Yolla gitsin!');  ?>
              <?php echo form_close(); ?>


text:
'use strict'

const common = require('../common-tap.js')
const getStream = require('get-stream')
const npm = require('../../')
const test = require('tap').test
const mkdirp = require('mkdirp')
const mr = require('npm-registry-mock')

var _createEntryUpdateStream = require('../../lib/search/all-package-metadata.js')._createEntryUpdateStream

var server

// this test uses a fresh cache for each test block
// create them all in common.cache so that we can verify
// them for root-owned files in sudotest
let CACHE_DIR
let cacheCounter = 1
function setup () {
  CACHE_DIR = common.cache + '/' + cacheCounter++
  mkdirp.sync(CACHE_DIR)
  fixOwner(CACHE_DIR)
}

const chownr = require('chownr')

const fixOwner = (
  process.getuid && process.getuid() === 0 &&
  process.env.SUDO_UID && process.env.SUDO_GID
) ? (path) => chownr.sync(path, +process.env.SUDO_UID, +process.env.SUDO_GID)
  : () => {}

test('setup', function (t) {
  mr({port: common.port, throwOnUnmatched: true}, function (err, s) {
    t.ifError(err, 'registry mocked successfully')
    npm.load({ cache: CACHE_DIR, registry: common.registry }, function (err) {
      t.ifError(err, 'npm loaded successfully')
      server = s
      t.pass('all set up')
      t.done()
    })
  })
})

test('createEntryUpdateStream full request', function (t) {
  setup()
  server.get('/-/all').once().reply(200, {
    '_updated': 1234,
    'bar': { name: 'bar', version: '1.0.0' },
    'foo': { name: 'foo', version: '1.0.0' }
  }, {
    date: Date.now() // should never be used.
  })
  return _createEntryUpdateStream(600, 0, {
    registry: common.registry
  }).then(({
    updateStream: stream,
    updatedLatest: latest
  }) => {
    t.equals(latest, 1234, '`latest` correctly extracted')
    t.ok(stream, 'returned a stream')
    return getStream.array(stream)
  }).then(results => {
    t.deepEquals(results, [{
      name: 'bar',
      version: '1.0.0'
    }, {
      name: 'foo',
      version: '1.0.0'
    }])
    server.done()
  })
})

test('createEntryUpdateStream partial update', function (t) {
  setup()
  var now = Date.now()
  server.get('/-/all/since?stale=update_after&startkey=1234').once().reply(200, {
    'bar': { name: 'bar', version: '1.0.0' },
    'foo': { name: 'foo', version: '1.0.0' }
  }, {
    date: (new Date(now)).toISOString()
  })
  return _createEntryUpdateStream(600, 1234, {
    registry: common.registry
  }).then(({
    updateStream: stream,
    updatedLatest: latest
  }) => {
    t.equals(latest, now, '`latest` correctly extracted from header')
    t.ok(stream, 'returned a stream')
    return getStream.array(stream)
  }).then(results => {
    t.deepEquals(results, [{
      name: 'bar',
      version: '1.0.0'
    }, {
      name: 'foo',
      version: '1.0.0'
    }])
    server.done()
  })
})

test('createEntryUpdateStream authed request', function (t) {
  setup()
  var token = 'thisisanauthtoken'
  server.get('/-/all', { authorization: 'Bearer ' + token }).once().reply(200, {
    '_updated': 1234,
    'bar': { name: 'bar', version: '1.0.0' },
    'foo': { name: 'foo', version: '1.0.0' }
  }, {
    date: Date.now() // should never be used.
  })
  return _createEntryUpdateStream(600, 0, {
    registry: common.registry,
    token
  }).then(({
    updateStream: stream,
    updatedLatest: latest
  }) => {
    t.equals(latest, 1234, '`latest` correctly extracted')
    t.ok(stream, 'returned a stream')
    return getStream.array(stream)
  }).then(results => {
    t.deepEquals(results, [{
      name: 'bar',
      version: '1.0.0'
    }, {
      name: 'foo',
      version: '1.0.0'
    }])
    server.done()
  })
})

test('createEntryUpdateStream bad auth', function (t) {
  setup()
  var token = 'thisisanauthtoken'
  server.get('/-/all', { authorization: 'Bearer ' + token }).once().reply(401, {
    error: 'unauthorized search request'
  })
  return _createEntryUpdateStream(600, 0, {
    registry: common.registry,
    token
  }).then(() => {
    throw new Error('should not succeed')
  }, err => {
    t.ok(err, 'got an error from auth failure')
    t.match(err, /unauthorized/, 'failure message from request used')
  }).then(() => {
    server.done()
  })
})

test('createEntryUpdateStream not stale', function (t) {
  setup()
  var now = Date.now()
  var staleness = 600
  return _createEntryUpdateStream(staleness, now, {
    registry: common.registry
  }).then(({
    updateStream: stream,
    updatedLatest: latest
  }) => {
    t.notOk(stream, 'no stream returned')
    t.notOk(latest, 'no latest returned')
    server.done()
    t.end()
  })
})

test('cleanup', function (t) {
  server.close()
  t.done()
})


text:
GitHubFile = function(ui, data, meta)
{
	DrawioFile.call(this, ui, data);

	this.meta = meta;
	this.peer = this.ui.gitHub;
};

//Extends mxEventSource
mxUtils.extend(GitHubFile, DrawioFile);

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.share = function()
{
	this.ui.editor.graph.openLink('https://github.com/' +
		encodeURIComponent(this.meta.org) + '/' +
		encodeURIComponent(this.meta.repo) +'/settings/access');
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.getId = function()
{
	return encodeURIComponent(this.meta.org) + '/' +
		((this.meta.repo != null) ? encodeURIComponent(this.meta.repo) + '/' +
		((this.meta.ref != null) ? this.meta.ref +
		((this.meta.path != null) ? '/' + this.meta.path : '') : '') : '');
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.getHash = function()
{
	return encodeURIComponent('H' + this.getId());
};

/**
 * Returns true if copy, export and print are not allowed for this file.
 */
GitHubFile.prototype.getPublicUrl = function(fn)
{
	// LATER: Check if download_url is always null for private repos
	if (this.meta.download_url != null)
	{
		mxUtils.get(this.meta.download_url, mxUtils.bind(this, function(req)
		{
			fn((req.getStatus() >= 200 && req.getStatus() <= 299) ? this.meta.download_url : null);
		}), mxUtils.bind(this, function()
		{
			fn(null);
		}));
	}
	else
	{
		fn(null);
	}
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
GitHubFile.prototype.isConflict = function(err)
{
	return err != null && err.status == 409;
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.getMode = function()
{
	return App.MODE_GITHUB;
};

/**
 * Overridden to enable the autosave option in the document properties dialog.
 */
GitHubFile.prototype.isAutosave = function()
{
	return false;
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.getTitle = function()
{
	return this.meta.name;
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.isRenamable = function()
{
	return false;
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
GitHubFile.prototype.getLatestVersion = function(success, error)
{
	this.peer.getFile(this.getId(), success, error);
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.isCompressedStorage = function()
{
	return false;
};

/**
 * Hook for subclassers to update the descriptor from given file
 */
GitHubFile.prototype.getDescriptor = function()
{
	return this.meta;
};

/**
 * Hook for subclassers to update the descriptor from given file
 */
GitHubFile.prototype.setDescriptor = function(desc)
{
	this.meta = desc;
};

/**
 * Adds all listeners.
 */
GitHubFile.prototype.getDescriptorEtag = function(desc)
{
	return desc.sha;
};

/**
 * Adds the listener for automatically saving the diagram for local changes.
 */
GitHubFile.prototype.setDescriptorEtag = function(desc, etag)
{
	desc.sha = etag;
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.save = function(revision, success, error, unloading, overwrite, message)
{
	this.doSave(this.getTitle(), success, error, unloading, overwrite, message);
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.saveAs = function(title, success, error)
{
	this.doSave(title, success, error);
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.doSave = function(title, success, error, unloading, overwrite, message)
{
	// Forces update of data for new extensions
	var prev = this.meta.name;
	this.meta.name = title;

	DrawioFile.prototype.save.apply(this, [null, mxUtils.bind(this, function()
	{
		this.meta.name = prev;
		this.saveFile(title, false, success, error, unloading, overwrite, message);
	}), error, unloading, overwrite]);
};

/**
 * Translates this point by the given vector.
 *
 * @param {number} dx X-coordinate of the translation.
 * @param {number} dy Y-coordinate of the translation.
 */
GitHubFile.prototype.saveFile = function(title, revision, success, error, unloading, overwrite, message)
{
	if (!this.isEditable())
	{
		if (success != null)
		{
			success();
		}
	}
	else if (!this.savingFile)
	{
		var doSave = mxUtils.bind(this, function(message)
		{
			if (this.getTitle() == title)
			{
				try
				{
					// Sets shadow modified state during save
					this.savingFileTime = new Date();
					this.setShadowModified(false);
					this.savingFile = true;

					var savedEtag = this.getCurrentEtag();
					var savedData = this.data;

					this.peer.saveFile(this, mxUtils.bind(this, function(etag)
					{
						// Checks for changes during save
						this.setModified(this.getShadowModified());
						this.savingFile = false;
						this.setDescriptorEtag(this.meta, etag);

						this.fileSaved(savedData, savedEtag, mxUtils.bind(this, function()
						{
							this.contentChanged();

							if (success != null)
							{
								success();
							}
						}), error);
					}),
					mxUtils.bind(this, function(err)
					{
						this.savingFile = false;

						if (this.isConflict(err))
						{
							this.inConflictState = true;

							if (error != null)
							{
								// Passes current commit message to avoid
								// multiple dialogs after synchronize
								error({commitMessage: message});
							}
						}
						else if (error != null)
						{
							error(err);
						}
					}), overwrite, message);
				}
				catch (e)
				{
					this.savingFile = false;

					if (error != null)
					{
						error(e);
					}
					else
					{
						throw e;
					}
				}
			}
			else
			{
				// Sets shadow modified state during save
				this.savingFileTime = new Date();
				this.setShadowModified(false);
				this.savingFile = true;

				this.ui.pickFolder(this.getMode(), mxUtils.bind(this, function(folderId)
				{
					this.peer.insertFile(title, this.getData(), mxUtils.bind(this, function(file)
					{
						// Checks for changes during save
						this.setModified(this.getShadowModified());
						this.savingFile = false;

						if (success != null)
						{
							success();
						}

						this.ui.fileLoaded(file);
					}), mxUtils.bind(this, function()
					{
						this.savingFile = false;

						if (error != null)
						{
							error();
						}
					}), false, folderId, message);
				}));
			}
		});

		if (message != null)
		{
			doSave(message);
		}
		else
		{
			this.peer.showCommitDialog(this.meta.name,
				this.getDescriptorEtag(this.meta) == null ||
				this.meta.isNew, mxUtils.bind(this, function(message)
			{
				doSave(message);
			}), error);
		}
	}
	else if (error != null)
	{
		error({code: App.ERROR_BUSY});
	}
};


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/cp_emperor_2">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/gap_lv3"
        android:layout_marginRight="@dimen/gap_lv3">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/gap_lv4"
                android:layout_marginTop="@dimen/gap_lv3"
                android:background="@drawable/clip_ticket"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/gap_lv3"
                    android:layout_marginRight="@dimen/gap_lv3"
                    android:text="all patrons are .... " />

                <Button
                    android:id="@+id/add"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Add Items addViews" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/gap_lv3"
                    android:layout_marginRight="@dimen/gap_lv3"
                    android:text="all patrons are .... " />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <include layout="@layout/activity_expl_ssep" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/gap_lv3"
                    android:text="Remarks" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/gap_lv3"
                    android:layout_marginRight="@dimen/gap_lv3"
                    android:text="all patrons are .... " />

            </LinearLayout>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>
</RelativeLayout>


text:
```
$ git clone https://github.com/hvenables/thermostat_tueday.git
$ cd thermostat_tueday
$ npm install
```
To run the app
```
$ node server.js
```
Go to http://localhost:3000

#####Something i have learnt
difference between `process.cwd()` and `__dirname`
I found this on stack overflow;

`process.cwd()` returns the current working directory,

i.e. the directory from which you invoked the node command.

`__dirname` returns the directory name of the directory containing the JavaScript source code file

I have learnt about directory structure.
You should put all your css and images and javascript inside a public folder,
This should be put inside a app folder.


text:
<?php

namespace App\Models\Traits\Attributes;

trait EmailTemplateAttributes
{
    /**
     * @return string
     */
    public function getActionButtonsAttribute()
    {
        return '

                    '.$this->getEditButtonAttribute('edit-email-template', 'admin.email-templates.edit').'
                    '.$this->getDeleteButtonAttribute('delete-email-template', 'admin.email-templates.destroy').'

';
    }

    /**
     * @return string
     */
    public function getStatusLabelAttribute()
    {
        if ($this->isActive()) {
            return "".trans('labels.general.active').'';
        }

        return "".trans('labels.general.inactive').'';
    }

    /**
     * @return bool
     */
    public function isActive()
    {
        return $this->status == 1;
    }
}


text:
package com.pokevian.app.smartfleet.ui.rank;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;

import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.pokevian.app.smartfleet.R;
import com.pokevian.app.smartfleet.model.Rank;
import com.pokevian.app.smartfleet.request.GetRankingRequest;
import com.pokevian.app.smartfleet.ui.common.AlertDialogFragment;
import com.pokevian.app.smartfleet.ui.common.AlertDialogFragment.AlertDialogCallbacks;
import com.pokevian.app.smartfleet.ui.common.WaitForDialog;
import com.pokevian.app.smartfleet.volley.VolleyListener;
import com.pokevian.app.smartfleet.volley.VolleySingleton;

import org.apache.log4j.Logger;

public class GetRankingDialogFragment extends DialogFragment implements AlertDialogCallbacks {

    public static final String TAG = "GetRankingDialogFragment";

    private String memberNo;
    private final RequestQueue mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
    private GetRankingDialogCallback mCallback;

    public static GetRankingDialogFragment newInstance(String memberNo) {
        GetRankingDialogFragment fragment = new GetRankingDialogFragment();
        Bundle args = new Bundle();
        args.putString("memberNo", memberNo);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            mCallback = (GetRankingDialogCallback) getParentFragment();
        } catch (ClassCastException e) { }

        if (mCallback == null) {
            try {
                mCallback = (GetRankingDialogCallback) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity + " must implement GetRankingDialogCallback");
            }
        }
    }

    @Override
    public void onDestroy() {
        mRequestQueue.cancelAll(TAG);
        super.onDestroy();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new WaitForDialog(getActivity());
        dialog.setCanceledOnTouchOutside(false);
        setCancelable(false);
        return dialog;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (getArguments() != null) {
            memberNo = getArguments().getString("memberNo");
            request();
        }
    }

    @Override
    public void onDialogButtonClick(DialogFragment fragment, int which) {
        String tag = fragment.getTag();
        if ("load-failure-dialog".equals(tag)) {
            if (which == DialogInterface.BUTTON_POSITIVE) {
               request();
            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                mCallback.onFailure(GetRankingDialogFragment.this);
                dismiss();
            }
        }
    }

    private void request() {
        GetRankingRequest request = new GetRankingRequest(memberNo, new GetRankingListener());
        request.setTag(TAG);
        mRequestQueue.add(request);
    }

    private class GetRankingListener extends VolleyListener<Rank[]> {

        @Override
        public void onErrorResponse(VolleyError error) {
            Logger.getLogger("volley").error(error.getMessage(), error);
            if (error instanceof ServerError) {
                FragmentManager fm = getChildFragmentManager();
                DialogFragment fragment = AlertDialogFragment.newInstance(
                        getString(R.string.dialog_title_server_error),
                        getString(R.string.dialog_message_server_error),
                        getString(R.string.btn_no),
                        getString(R.string.btn_yes));
                fm.beginTransaction().add(fragment, "load-failure-dialog")
                        .commitAllowingStateLoss();
            } else {
                FragmentManager fm = getChildFragmentManager();
                DialogFragment fragment = AlertDialogFragment.newInstance(
                        getString(R.string.dialog_title_network_error),
                        getString(R.string.dialog_message_network_error),
                        getString(R.string.btn_no),
                        getString(R.string.btn_yes));
                fm.beginTransaction().add(fragment, "load-failure-dialog")
                        .commitAllowingStateLoss();
            }
        }

        @Override
        public void onResponse(Rank[] response) {
            Logger.getLogger(TAG).trace("onResponse#" + response);
            mCallback.onSuccess(GetRankingDialogFragment.this, response != null && response.length > 0 ? response[0] : null);
            dismissAllowingStateLoss();
        }
    }

}


text:
const Sequelize = require('sequelize');
require('dotenv').config();
const expect = require('chai').expect;
const seed = require('../../../server/db/seed.js');
const db = require('../../../server/db/index.js');
const crewHelpers = require('../../../server/db/controllers/crewHelpers.js');
const taskHelpers = require('../../../server/db/controllers/taskHelpers.js');
const user_crewHelpers = require('../../../server/db/controllers/user_crewHelpers.js');
const user_taskHelpers = require('../../../server/db/controllers/user_taskHelpers.js');
const userHelpers = require('../../../server/db/controllers/userHelpers.js');

xdescribe('Postgres crewbuilder db', function() {

  beforeEach(function(done) {
    seed().then(function() { done(); });
  });

  it('Should connect to the crewbuilder database', function() {
    return db.sequelize.authenticate();
  });

  it('Should remove a row from the user-crew table when a user requests to leave', function(done) {
    user_crewHelpers.leaveCrew(1, 4)
      .then(deleted => {
        return db.user_crew.findOne({
          where: {
            user_id: 1,
            crew_id: 4
          }
        });
      })
      .then(userCrew => {
        console.log(userCrew);
        expect(!userCrew).to.be.true;
        done();
      })
      .catch(err => {
        done(err);
      });
  });
  /* *************** associations *************** */
  it('Should retrieve a list of a crew\'s unverified tasks for crew leader view', function(done) {
    taskHelpers.getUnverifiedTasks(13)
      .then(tasks => {
        expect(tasks[0].id).to.equal(98);
        done();
      })
      .catch(err => {
        done(err);
      });
  });

  it('Should delete a task and all associated user_tasks', function(done) {
    taskHelpers.deleteTask(5)
      .then(deleted => {
        expect(deleted).to.equal(1);
      })
      .then(() => {
        return db.user_task.findAll({
          where: {
            task_id: 5
          }
        });
      })
      .then((user_tasks => {
        expect(user_tasks.length).to.equal(0);
        done();
      }))
      .catch(err => {
        done(err);
      });
  });

  it('Should delete tasks according to expiry date', function(done) {
    db.task.destroy({
      where: {
        expiry: {
          $lt: new Date()
        }
      }
    })
      .then(destroyed => {
        expect(destroyed).to.equal(60);
        done();
      })
      .catch(err => {
        done(err);
      });
  });

  it('Should delete expired tests after any new task is created', function(done) {
    let id;
    db.task.create({
      name: 'Task that should get deleted',
      expiry: new Date() - 1000,
    })
      .then((created) => {
        return db.task.count();
      })
      .then(count => {
        expect(count).to.equal(116);
        done();
      })
      .catch(err => {
        done(err);
      });
  });

});