commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
68bdfe8bcd963f7fdc5a79e90dcba7d16a73a279 | add missing [ | topicCharacteristic.js | topicCharacteristic.js | var bleno = require('bleno');
function TopicCharacteristic(config, client) {
bleno.Characteristic.call(this, {
uuid: '6bcb06e2747542a9a62a54a1f3ce11e6',
properties: 'read', 'write', 'notify'],
descriptors: [
new bleno.Descriptor({
uuid: '2901',
value: 'Topic: ' + config.topic
})
]
});
this._value = new Buffer(0);
this._updateValueCallback = null;
this._client = client;
this._topic = config.topic;
}
util.inherits(TopicCharacteristic, bleno.Characteristic);
TopicCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
this._value = data;
client.publish(this._topic, data);
callback(this.RESULT_SUCCESS);
}
TopicCharacteristic.prototype.onReadRequest = function(offset, callback) {
callback(this.RESULT_SCCESS, this._value);
}
TopicCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) {
this._updateValueCallback = updateValueCallback;
}
TopicCharacteristic.prototype.onUnsubscribe = function () {
this._updateValueCallback = null;
}
TopicCharacteristic.prototype.update = function(value) {
this._value = value;
if (this._updateValueCallback) {
this._updateValueCallback(this._value);
}
}
module.exports = TopicCharacteristic; | JavaScript | 0.000033 | @@ -164,16 +164,17 @@
erties:
+%5B
'read',
|
d03ecbc5d056f521a2504530ebc9bf15f19af5cc | add support for subscriptions with additional arguments | moo.js | moo.js | "use strict";
function Moo(transport) {
this.transport = transport;
this.reqid = 0;
this.subkey = 0;
this.requests = {};
this.mooid = Moo._counter++;
this.logger = transport.logger;
}
Moo._counter = 0;
Moo.prototype._subscribe_helper = function(svcname, reqname, cb) {
var self = this;
var subkey = self.subkey++;
self.send_request(svcname + "/subscribe_" + reqname,
{ subscription_key: subkey },
function (msg, body) {
if (cb)
cb(msg && msg.name == "Success" ? false : (msg ? msg.name : "NetworkError"), body);
});
return {
unsubscribe: function(ucb) {
self.send_request(svcname + "/unsubscribe_" + reqname,
{ subscription_key: subkey },
ucb);
}
};
};
Moo.prototype.send_request = function() {
var name;
var body;
var content_type;
var cb;
var i = 0;
name = arguments[i++];
if (typeof(arguments[i]) != 'function') { body = arguments[i++]; }
if (typeof(arguments[i]) != 'function') { content_type = arguments[i++]; }
cb = arguments[i++];
var origbody = body;
if (typeof(body) == 'undefined') {
// nothing needed here
} else if (!Buffer.isBuffer(body)) {
body = Buffer.from(JSON.stringify(body), 'utf8');
content_type = content_type || "application/json";
} else {
throw new Error("missing content_type");
}
let header = 'MOO/1 REQUEST ' + name + '\n' +
'Request-Id: ' + this.reqid + '\n';
if (body) {
header += 'Content-Length: ' + body.length + '\n' +
'Content-Type: ' + content_type + '\n';
}
this.logger.log('-> REQUEST', this.reqid, name, origbody ? JSON.stringify(origbody) : "");
const m = Buffer.from(header + '\n');
if (body)
this.transport.send(Buffer.concat([ m, body ], m.length + body.length));
else
this.transport.send(m);
this.requests[this.reqid] = { cb: cb };
this.reqid++;
};
Moo.prototype.parse = function(buf) {
var e = 0;
var s = 0;
var ret = {
is_complete: false,
is_error: false,
bytes_consumed: 0,
msg: {}
};
var msg = {
content_length: 0,
headers: {}
};
if ((typeof ArrayBuffer != 'undefined') && (buf instanceof (ArrayBuffer))) {
// convert to Node Buffer
var view = new Uint8Array(buf);
var buf = new Buffer(buf.byteLength);
for (var i = 0; i < buf.length; ++i) buf[i] = view[i];
}
var state;
while (e < buf.length) {
if (buf[e] == 0xa) {
// parsing headers or first line?
if (state == 'header') {
if (s == e) {
// end of MOO header
if (msg.request_id === undefined) {
this.logger.log('MOO: missing Request-Id header: ', msg);
ret.is_error = true;
return ret;
}
e++;
if (msg.content_length > 0) {
if ((e + msg.content_length) > buf.length) {
this.logger.log("MOO: reached end of buffer while reading body");
return ret;
}
if (msg.content_type == "application/json") {
var json = buf.toString('utf8', e, e+msg.content_length);
try {
msg.body = JSON.parse(json);
} catch (e) {
this.logger.log("MOO: bad json body: ", json, msg);
ret.is_error = true;
return ret;
}
} else {
msg.body = buf.slice(e, e + msg.content_length);
}
ret.bytes_consumed = e + msg.content_length;
} else {
ret.bytes_consumed = e;
}
ret.msg = msg;
ret.is_complete = true;
return ret;
} else {
// parse MOO header line
var line = buf.toString('utf8', s, e);
var matches = line.match(/([^:]+): *(.*)/);
if (matches) {
if (matches[1] == "Content-Type")
msg.content_type = matches[2];
else if (matches[1] == "Content-Length")
msg.content_length = parseInt(matches[2]);
else if (matches[1] == "Request-Id")
msg.request_id = matches[2];
else
msg.headers[matches[1]] = matches[2];
} else {
this.logger.log("MOO: bad header: ", line, msg);
ret.is_error = true;
return ret;
}
}
} else {
// parse MOO first line
var line = buf.toString('utf8', s, e);
var matches = line.match(/^MOO\/([0-9]+) ([A-Z]+) (.*)/);
if (matches) {
msg.verb = matches[2];
if (msg.verb == "REQUEST") {
matches = matches[3].match(/([^\/]+)\/(.*)/);
if (matches) {
msg.service = matches[1];
msg.name = matches[2];
} else {
this.logger.log("MOO: bad request header: ", line, msg);
ret.is_error = true;
return ret;
}
} else {
msg.name = matches[3];
}
state = 'header';
} else {
this.logger.log("MOO: bad header: ", line, msg);
ret.is_error = true;
return ret;
}
}
s = e+1;
}
e++;
}
this.logger.log("MOO: reached end of buffer while parsing header");
return ret;
};
Moo.prototype.handle_response = function(msg, body) {
let cb = this.requests[msg.request_id].cb;
if (cb) cb(msg, body);
if (msg.verb == "COMPLETE") delete(this.requests[msg.request_id]);
};
Moo.prototype.close = function() {
Object.keys(this.requests).forEach(e => {
let cb = this.requests[e].cb;
if (cb) cb();
});
this.requests = {};
};
exports = module.exports = Moo;
| JavaScript | 0 | @@ -302,50 +302,239 @@
ar s
-elf = this;%0A var subkey = self.subkey++
+ubscription_args = %7B%7D;%0A if (arguments.length == 4) %7B%0A cb = arguments%5B3%5D;%0A subscription_args = arguments%5B2%5D;%0A %7D%0A var self = this;%0A var subkey = self.subkey++;%0A subscription_args.subscription_key = subkey
;%0A
@@ -591,38 +591,8 @@
ame,
-%0A %7B
sub
@@ -597,37 +597,28 @@
ubscription_
-key: subkey %7D
+args
,%0A
|
2943f5b75fc93b8087911e29a5fe67d9d262b7ac | update sample | samples/options.cast.js | samples/options.cast.js |
const parse = require('../lib/sync')
const assert = require('assert')
const data = `
2000-01-01,date1
2050-11-27,date2
`.trim()
const records = parse(data, {
cast: function(value, context){
if(context.index === 0){
return `${value}T05:00:00.000Z`
}else{
return context
}
},
trim: true
})
assert.deepEqual(records, [
[ '2000-01-01T05:00:00.000Z', {
quoting: false, lines: 1, count: 0, index: 1, header: false, column: 1 } ],
[ '2050-11-27T05:00:00.000Z', {
quoting: false, lines: 2, count: 1, index: 1, header: false, column: 1 } ]
])
| JavaScript | 0 | @@ -375,39 +375,70 @@
00.000Z', %7B%0A
-quoting
+column: 1, empty_line_count: 0, header
: false, lines:
@@ -434,62 +434,83 @@
se,
-l
in
-es
+dex
: 1,
- count: 0
+%0A quoting: false
,
+l
in
-dex
+es
: 1,
-header: false, column: 1
+records: 0, skipped_line_count: 0%0A
%7D %5D
@@ -553,78 +553,130 @@
-quoting: false, lines: 2, count: 1, index: 1, header: false, column: 1
+column: 1, empty_line_count: 0, header: false, index: 1,%0A quoting: false, lines: 2, records: 1, skipped_line_count: 0%0A
%7D %5D
|
23503f11bd10334eed4c793d4696036a15353125 | Clear the timer in IAB.close to prevent the window from reopening. | patch_window.js | patch_window.js | // Meteor's OAuth flow currently only works with popups. Phonegap does
// not handle this well. Using the InAppBrowser plugin we can load the
// OAuth popup into it. Using the plugin by itself would not work with
// the MeteorRider phonegap method, this fixes it. This has not been
// tested on other Meteor phonegap methods. (tested on PG 3.3, android, iOS)
//
// http://docs.phonegap.com/en/3.3.0/cordova_inappbrowser_inappbrowser.md.html
// https://github.com/zeroasterisk/MeteorRider
window.patchWindow = function () {
// Make sure the InAppBrowser is loaded before patching the window.
var inAppBrowserLoaded = !!(window.cordova && window.cordova.require('org.apache.cordova.inappbrowser.inappbrowser'));
if (!inAppBrowserLoaded) return false;
// Keep a reference to the in app browser's window.open.
var __open = window.open,
oauthWin,
timer;
// Create an object to return from a monkeypatched window.open call. Handles
// open/closed state of popup to keep Meteor happy. Allows one to save window
// reference to a variable and close it later. e.g.,
// `var foo = window.open('url'); foo.close();
window.IAB = {
closed: true,
open: function (url) {
// XXX add options param and append to current options
oauthWin = __open(url, '_blank', 'location=no,hidden=yes');
oauthWin.addEventListener('loadstop', checkIfOauthIsDone);
// use hidden=yes as a hack for Android, allows popup to yield events with
// each #show call. Lets events run on Meteor app, otherwise all listeners
// will *only* run when tapping done button or oauthWin.close
//
// XXX should be a better way to do this
if (device.platform === 'Android') {
timer = setInterval(oauthWin.show, 200);
} else {
oauthWin.show();
}
// check if uri contains an error or code param, then manually close popup
function checkIfOauthIsDone(event) {
// XXX improve this regex to match twitters as well
if (!event.url || !event.url.match(/error|code=/)) return;
// Get the credentialToken and credentialSecret from the InAppBrowser's url hash.
var hashes = event.url.slice(event.url.indexOf('#') + 1).split('&');
var credentialToken = hashes[0].split('=')[1];
var credentialSecret = hashes[1].split('=')[1];
Package.oauth.OAuth._handleCredentialSecret(credentialToken, credentialSecret);
Accounts.oauth.tryLoginAfterPopupClosed(credentialToken);
oauthWin.close();
clearInterval(timer);
oauthWin.removeEventListener('loadstop', checkIfOauthIsDone)
}
this.closed = false;
},
close: function () {
if (!oauthWin) return;
oauthWin.close();
this.closed = true;
}
};
// monkeypatch window.open on the phonegap platform
if (typeof device !== "undefined") {
window.open = function (url) {
IAB.open(url);
// return InAppBrowser so you can set foo = open(...) and then foo.close()
return IAB;
};
}
// Clear patchWindow to prevent it from being called multiple times.
window.patchWindow = function () {
};
return true;
};
// Patch the window after cordova is finished loading
// if the InAppBrowser is not available yet.
if (!window.patchWindow()) document.addEventListener('deviceready', window.patchWindow, false); | JavaScript | 0 | @@ -2964,16 +2964,52 @@
return;%0A
+%0A clearInterval(timer);%0A%0A
|
f64413b6c2da3e2b10e4300eadee612c9df94b63 | Revert "Revert "edit button no longer appears next to undefined in history tab"" | js/history.js | js/history.js | // This tab should list all the transactions you have done with any of your accounts
var HistoryPage = new (function () {
var hist = {};
this.onShowTab = function () {
$('#HistoryTable').empty();
_.each(hist, function (t, hash) {
HistoryPage.renderTransaction(t);
});
};
//<table class="dataTable" ><tr><th>#</th><th>Ledger</th><th>Source</th><th>Destination</th><th>Amount</th><th>Status</th></tr><tbody id="HistoryTable"></tbody></table>
this.onHistoryResponse = function (res, noError) {
res = res.result || res;
if (noError && res) {
_.each(
res.transactions || [],
function (t) {
HistoryPage.addTransaction(t, false);
}
);
}
};
this.addTransaction = function (t, adjust) {
hist[t.hash] = t;
HistoryPage.renderTransaction(t, adjust);
};
this.renderTransaction = function (t, adjust) {
if (t.TransactionType == 'CreditSet') {
var amount = ncc.displayAmount(t.LimitAmount.value);
} else if (t.TransactionType == 'OfferCreate') {
return;
} else {
var amount = ncc.displayAmount(t.Amount);
}
var oldEntry = $('#' + t.hash),
toAcct = t.Destination,
toName = blobVault.addressBook.getName(toAcct) || "",
fromAcct = t.Account,
fromName = blobVault.addressBook.getName(fromAcct) || "",
entry = ( '<td>' + (t.inLedger || t.ledger_current_index || t.ledger_closed_index) + '</td>' +
'<td>' + t.TransactionType + '</td>' +
'<td class="addr" data-acct='+ fromAcct + ' data-name="' + fromName + '">' +
'<span>' + (fromName || fromAcct) + '</span>' +
(fromName == 'you' ? '' : ' <button class="edit" onclick="HistoryPage.editName(this)">edit</button>' +
'<button class="save" onclick="HistoryPage.saveName(this)">save</button>') +
'</td>' +
'<td class="addr" data-acct='+ toAcct + ' data-name="' + toName + '">' +
'<span>' + (toName || toAcct) + '</span>' +
(toName == 'you' ? '' : ' <button class="edit" onclick="HistoryPage.editName(this)">edit</button>' +
'<button class="save" onclick="HistoryPage.saveName(this)">save</button>') +
'</td>' +
'<td>' + amount + '</td>' +
'<td>' + t.status + '</td>' );
if (oldEntry.length) {
oldEntry.html(entry);
} else {
$('#HistoryTable').prepend('<tr id="' + t.hash + '">' + entry + '</tr>');
if (adjust) {
if (t.TransactionType == 'CreditSet' && t.Account == ncc.accountID) {
ncc.changeBalance('XNS', -t.Fee);
return;
}
var curr = t.Amount.currency || 'XNS',
amt = t.Amount.value || t.Amount;
if (t.Account == ncc.accountID) {
ncc.changeBalance(curr, -amt);
ncc.changeBalance('XNS', -t.Fee);
}
if (t.Destination == ncc.accountID) {
ncc.changeBalance(curr, amt);
}
}
}
}
this.editName = function (cellElem) {
var cell = $(cellElem).parent(),
content = cell.find('span'),
saveButton = cell.find('button.save'),
editButton = cell.find('button.edit'),
name = content.text(),
input = $('<input>').val(name)
.keydown(function (e) { if (e.which == 13) saveButton.click(); });
saveButton.show();
editButton.hide();
content.html(input);
input.select();
};
this.saveName = function (cellElem) {
var cell = $(cellElem).parent(),
addr = cell.attr('data-acct'),
newName = cell.find('input').val();
blobVault.addressBook.setEntry(newName, addr);
blobVault.save();
HistoryPage.onShowTab();
};
})();
| JavaScript | 0 | @@ -1264,30 +1264,24 @@
Name(toAcct)
- %7C%7C %22%22
,%0A %0A
@@ -1371,15 +1371,357 @@
cct)
- %7C%7C %22%22,
+,%0A %0A // no button if name matches one of these%0A noBut = %7B 'you': 1, 'undefined': 1%7D;%0A editButtons = (' %3Cbutton class=%22edit%22 onclick=%22HistoryPage.editName(this)%22%3Eedit%3C/button%3E' +%0A '%3Cbutton class=%22save%22 onclick=%22HistoryPage.saveName(this)%22%3Esave%3C/button%3E');%0A %0A console.log(fromName, toName);
%0A
@@ -2083,220 +2083,35 @@
ame
-== 'you' ? '' : ' %3Cbutton class=%22edit%22 onclick=%22HistoryPage.editName(this)%22%3Eedit%3C/button%3E' +%0A '%3Cbutton class=%22save%22 onclick=%22HistoryPage.saveName(this)%22%3Esave%3C/button%3E'
+in noBut ? '' : editButtons
) +%0A
@@ -2325,218 +2325,35 @@
ame
-== 'you' ? '' : ' %3Cbutton class=%22edit%22 onclick=%22HistoryPage.editName(this)%22%3Eedit%3C/button%3E' +%0A '%3Cbutton class=%22save%22 onclick=%22HistoryPage.saveName(this)%22%3Esave%3C/button%3E'
+in noBut ? '' : editButtons
) +%0A
|
ce0347982b058ca8e52b2cc0c362fb21d2e709a2 | Add timestamps to personality schema | models/personality.js | models/personality.js | 'use strict';
const mongoose = require('mongoose');
const personalitySchema = mongoose.Schema({
twitter_handle: String,
raw_response: Object,
api_version: String
});
const Personality = mongoose.model('Personality', personalitySchema);
module.exports = Personality;
| JavaScript | 0.00136 | @@ -163,16 +163,40 @@
String%0A
+%7D, %7B%0A timestamps: true%0A
%7D);%0A%0Acon
|
b7e095e581fb456b21efea51848570a34325d645 | Update test dependencies. | test/deps.js | test/deps.js | // This file was autogenerated by calcdeps.js
goog.addDependency("../../node_modules/closure-dom/src/dom.js", ["dom"], []);
goog.addDependency("../../src/css.js", ["fontface.Css"], []);
goog.addDependency("../../src/descriptors.js", ["fontface.Descriptors"], []);
goog.addDependency("../../src/observer.js", ["fontface.Observer"], ["fontface.Ruler","dom","lang.Promise"]);
goog.addDependency("../../src/ruler.js", ["fontface.Ruler"], ["dom"]);
goog.addDependency("../../node_modules/promis/src/async.js", ["lang.async"], []);
goog.addDependency("../../node_modules/promis/src/promise.js", ["lang.Promise"], ["lang.async"]);
| JavaScript | 0 | @@ -121,70 +121,8 @@
%5D);%0A
-goog.addDependency(%22../../src/css.js%22, %5B%22fontface.Css%22%5D, %5B%5D);%0A
goog
@@ -289,23 +289,8 @@
dom%22
-,%22lang.Promise%22
%5D);%0A
@@ -364,184 +364,4 @@
%5D);%0A
-goog.addDependency(%22../../node_modules/promis/src/async.js%22, %5B%22lang.async%22%5D, %5B%5D);%0Agoog.addDependency(%22../../node_modules/promis/src/promise.js%22, %5B%22lang.Promise%22%5D, %5B%22lang.async%22%5D);%0A
|
ea0d2a88ac4a2d43e3fa127fcf200cbef31f5b95 | Fix notas en decimales | js/plugins.js | js/plugins.js | // Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function noop() {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
var num_campos=3;
function nuevo(){
//alert("nuevo")
$("#tablaUsuarios").append("<tr>"+
"<td><input name='materia[]' type='text' size='15' placeholder='Materia' required/></td>"+
"<td><input name='nota[]' type='text' size='10' placeholder='Nota' required/></td>"+
"<td><input name='creditos[]' type='text' size='10' placeholder='Num. creditos' required/></td>"+
"<td><input type='button' value='Eliminar' onclick='eliminar(this)' class='btn btn-danger eliminar'></td>"+
"</tr>");
}
//Ctrl + Shift + j para ver la consola (consejo: usa chrome)
function guardar(e){
//NOTA: Recuerda SIMPRE VALIDAR los campos del formulario del lado del servidor y el cliente.
e.preventDefault();
var res = $("form#f").serializeArray();
//console.log(res);//descomenta esta linea y mira la consola, así llegan nuestros datos,
var nprod = res.length;
var cont = 0;
$("#result").empty();//limpiar la caja
var materia = [];//array para cada una de las filas
var promedio = 0;
var totalCreditos = 0;
for (i=0;i<nprod;i++){
$("#result").append(res[i].value);
materia.push(parseInt(res[i].value)); //esta linea agrega los datos a nuestro array
if(cont < num_campos-1 ){
cont++;
}
else{
promedio += materia[1] * materia[2];
totalCreditos += parseInt(materia[2]);
console.log("=" + promedio + " cred: "+ totalCreditos);
materia = [];
cont=0;
}
}
$("#result").text(promedio/totalCreditos);
//console.log("materias:" + materias);//materias es un array que contiene n arrays (n materias)
}
function eliminar(e){
$(e).parent().parent().fadeOut(400).remove();
/**
* el boton eliminar esta jerarquicamente asi:
* form > table > tr > td > input.eliminar
* por esta razon se debe subir dos posiciones
*/
}
function iniciar(){
nuevo();
$("#newp").on("click",nuevo);//si dan click a #newp ejecutar nuevo
$("#guardar").on("click",guardar);
$("input").on("keyup",guardar);
}
$(document).on("ready",iniciar); // cuando el document esté 'ready' ejecutar la funcion 'iniciar' | JavaScript | 0.999863 | @@ -1892,25 +1892,16 @@
ia.push(
-parseInt(
res%5Bi%5D.v
@@ -1905,17 +1905,16 @@
%5D.value)
-)
; //esta
@@ -2199,16 +2199,28 @@
ditos);%0A
+
%0A
|
b33afbce36e2b8c37c681853f79542b8a394def5 | test res text | modules/msgHandler.js | modules/msgHandler.js | var weConfig = require('../config')
var OAuth = require('wechat-oauth')
var WechatAPI = require('wechat-api')
var request = require('request')
var client = new OAuth(weConfig.appid, weConfig.secret)
var api = new WechatAPI(weConfig.appid, weConfig.secret)
module.exports = function(req, res, next) {
var msg = req.weixin
if (msg.MsgType === 'event' && msg.Event === 'subscribe') {
var bindingUrl = client.getAuthorizeURL('http://roscoe.cn/info', 'binding', 'snsapi_userinfo');
res.reply('等你好久了!<a href="' + bindingUrl + '">点击这里</a>以完成绑定(ง •_•)ง')
next()
}
if (msg.MsgType === 'text') {
request.post({
url: 'http://dev.hivoice.cn/exp_center/nlu/testService2Demo.action',
form: {
serviceId: 6,
question: '讲个笑话'
}
}, function(err, httpResponse, body) {
if (err) {
res.reply('服务器出了点小问题(´_ゝ`)')
next()
} else {
var chatResMsg = body.match(/text":".+?"/g)[1].slice(7).slice(0, -1)
res.reply(chatResMsg)
next()
}
})
}
if (msg.MsgType === 'voice') {
var recognition = msg.Recognition
// TODO remove this test
if (recognition && recognition !== "") {
api.semantic(msg.FromUserName, {
query: recognition,
category: 'remind,datetime',
city: '上海'
}, function(err, result) {
if (err || result.errcode) {
request.post({
url: 'http://dev.hivoice.cn/exp_center/nlu/testService2Demo.action',
form: {
serviceId: 6,
question: '讲个笑话'
}
}, function(err, httpResponse, body) {
if (err) {
res.reply('服务器出了点小问题(´_ゝ`)')
next()
} else {
var chatResMsg = body.match(/text":".+?"/g)[1].slice(7).slice(0, -1)
res.reply(chatResMsg)
next()
}
})
} else {
var remindText = '已设置提醒:\n' + semantic.datetime.date_ori + semantic.datetime.time_ori + ':' + semantic.event + '\n\n' + '如需取消提醒请<a href="#">点击这里</a>'
res.reply(remindText)
next()
}
})
} else {
res.reply('不好意思没有听清(´_ゝ`)')
next()
}
}
}
| JavaScript | 0.000005 | @@ -852,16 +852,19 @@
+ //
if (err
@@ -870,32 +870,35 @@
r) %7B%0A
+ //
res.reply('
@@ -918,32 +918,35 @@
%60)')%0A
+ //
next()%0A
@@ -952,16 +952,19 @@
+ //
%7D else
@@ -972,24 +972,27 @@
%0A
+ //
var cha
@@ -1060,24 +1060,27 @@
%0A
+ //
res.rep
@@ -1097,32 +1097,35 @@
Msg)%0A
+ //
next()%0A
@@ -1124,33 +1124,84 @@
t()%0A
-%7D
+// %7D%0A%0A res.reply(body)%0A next()
%0A %7D)%0A%09%7D%0A%0A
|
780bf690d6806eb1530039abd6b504232c0f5d04 | fix a bug | js/scripts.js | js/scripts.js | $(window).load(function(){
hideLogo();
arrangeBoxes();
window.setTimeout("preShowModals(0)", 2000);
$('.menu').bind("click", preShowModals);
$('.contact').bind("click", showInfo);
//リロード時、最上部へ移動
$('html,body').animate({ scrollTop: 0 }, '1');
//リサイズ時にボックスの配置をやり直す
$(window).bind("resize", arrangeBoxes);
//右上のAMIDCロゴの設定
$(".over").hide();
$(".out, .over").hover(
function(){
$(".out").hide();
$(".over").show();
},
function(){
$(".out").show();
$(".over").hide();
}
);
});
function arrangeBoxes(){
//ウィンドウサイズ取得
var winWidth = $(window).innerWidth();
var winHeight = $(window).innerHeight();
//コンテンツボックスのサイズ設定
var noBox = Math.floor(winWidth / 180);
if(noBox < 3){
noBox = 3;
}
var navPadding = winWidth * 0.25
var contentBoxWidth = 100 / noBox
$(".menu").css({
"width": contentBoxWidth + "%",
"height": contentBoxWidth + "%",
"margin-right": 0,
"margin-bottom": 0
});
$("nav.mainMenu").css({
"margin-left": navPadding / 2 + "px",
"margin-right": navPadding / 2 + "px"
});
//列最後のボックスのマージン調整
$(".menu:nth-child(" + noBox + "n)").css({
"margin-right": 0,
});
}
function showLogo(){
//ウィンドウサイズ取得
var winWidth = $(window).innerWidth();
var winHeight = $(window).innerHeight();
//ロゴサイズ設定
if(winWidth < winHeight){
var logoWidth = winWidth * 0.5;
//var logoHeight = "auto";
} else {
//var logoWidth = "auto";
var logoHeight = winHeight * 0.1;
}
$("#logo").css({
"width": logoWidth,
"height": logoHeight,
});
$("#logo").css({
"left": ($("header").width() - $("#logo").width()) / 2,
"top": ($("header").height() - $("#logo").height()) / 2,
});
//フェードイン
$("#logo").fadeIn(800);
};
function hideLogo() {
setTimeout(function(){
$("#logo").fadeOut(500, function(){
$("header").hide();
showContent();
});
}, 700);
}
function showContent(){
//コンテンツを1つずつ表示
$('.menu')
.css({opacity: 0})
.each(function(i){
$(this).delay(100 * i).animate({opacity:1}, 800);
});
};
function preShowModals (flag, event) {
console.log(event);
modal = $(".modal");
if (flag === 0) {
if (location.hash) {
modalHash = location.hash.substring(1, location.hash.length);
modalURL = 'http://' + location.host + '/?p=' + modalHash;
showModals(modalURL, modalHash);
} else {
return false;
}
} else {
modalURL = $(this).children("a").attr('href');
modalHash = modalURL.replace("http://meidenid.com/?p=","");
showModals(modalURL, modalHash);
};
//google analytics
ga('send', 'pageview', {
'page': location.pathname + location.search + location.hash
});
};
function showModals(modalURL, modalHash){
//hash追加
location.hash = modalHash;
//ウィンドウサイズ取得
var winWidth = $(window).innerWidth();
var winHeight = $(window).innerHeight();
//背景表示
$(".bg").fadeIn(500);
//ロード画像のプリロード
$("<img>").attr("src", "http://meidenid.com/wp-content/themes/mid/img/loading.gif" );
//ロード
modal.load(modalURL,
function(){
modal.css({
top: $(window).scrollTop() + winHeight * 0.1 + "px",
});
//ローディング画像表示
$('.loading').css({
"top": $(window).scrollTop() + winHeight / 2 - 12 + "px"
});
if (winWidth > winHeight) {
$('.loading > img').css({
"width": winWidth * 0.05 + "px"
});
} else {
$('.loading > img').css({
"height": winHeight * 0.05 + "px"
});
};
$('.loading').show();
//モーダル表示
var movie = modal.children('iframe');
var image = modal.children('img');
if(movie.get(0)) {
movie.css({
"width": winWidth * 0.7,
"height": winWidth * 0.7 * 0.563
});
movie.bind("load", function(){
$('.loading').hide();
modal.fadeIn(500);
});
};
if (image.get(0)) {
image.css({
"max-width": winWidth * 0.8 + "px",
"max-height": winHeight * 0.8 + "px"
});
image.bind("load", function(){
$('.loading').hide();
modal.fadeIn(500);
});
};
//閉じるボタン表示
$('.close').show().unbind();
//モーダル非表示
$('.modal, .close, .bg').click(function() {
modal.fadeOut(500);
$('.bg').hide();
$('.close').hide();
$('.loading').hide();
//再生停止
if (movie.get(0)){
$f(document.getElementById('vimeoPlayer')).api('unload');
};
//hash削除
location.hash='';
});
});
};
function showInfo(){
var movie = $('address').children('iframe');
var winWidth = $(window).innerWidth();
var winHeight = $(window).innerHeight();
//背景表示
$(".bg").show();
//データ表示
$('address').fadeIn(500);
movie.css({
"width": winWidth * 0.7,
"height": winWidth * 0.7 * 0.563
});
$('.close').show();
//モーダル非表示
$("#information").bind("click", function() {
return false;
});
$(".close, .bg, address").click(function(event) {
$('address').hide();
$(".bg").fadeOut(500);
$('.close').fadeOut(500);
$f(document.getElementById('vimeoPlayer')).api('unload');
});
};
| JavaScript | 0.000016 | @@ -327,16 +327,65 @@
es);%0D%0A%0D%0A
+%09$(%22.prev-next%22).bind(%22click%22, arrangeBoxes);%0D%0A%0D%0A
%0D%0A%09//%E5%8F%B3%E4%B8%8A%E3%81%AE
|
3bf2c0f495c17231c7c2a65147800f6199f465cf | Update scripts.js | js/scripts.js | js/scripts.js | /*!
Title: Dev Portfolio Template
Version: 1.2.1
Last Change: 08/27/2017
Author: Ryan Fitzgerald
Repo: https://github.com/RyanFitzgerald/devportfolio-template
Issues: https://github.com/RyanFitzgerald/devportfolio-template/issues
Description: This file contains all the scripts associated with the single-page
portfolio website.
*/
(function($) {
// Remove no-js class
$('html').removeClass('no-js');
// Animate to section when nav is clicked
$('header a').click(function(e) {
// Treat as normal link if no-scroll class
if ($(this).hasClass('no-scroll')) return;
e.preventDefault();
var heading = $(this).attr('href');
var scrollDistance = $(heading).offset().top;
$('html, body').animate({
scrollTop: scrollDistance + 'px'
}, Math.abs(window.pageYOffset - $(heading).offset().top) / 1);
// Hide the menu once clicked if mobile
if ($('header').hasClass('active')) {
$('header, body').removeClass('active');
}
});
// Scroll to top
$('#to-top').click(function() {
$('html, body').animate({
scrollTop: 0
}, 500);
});
// Scroll to first element
$('#lead-down span').click(function() {
var scrollDistance = $('#lead').next().offset().top;
$('html, body').animate({
scrollTop: scrollDistance + 'px'
}, 500);
});
// Create timeline
$('#experience-timeline').each(function() {
$this = $(this); // Store reference to this
$userContent = $this.children('div'); // user content
// Create each timeline block
$userContent.each(function() {
$(this).addClass('vtimeline-content').wrap('<div class="vtimeline-point"><div class="vtimeline-block"></div></div>');
});
// Add icons to each block
$this.find('.vtimeline-point').each(function() {
$(this).prepend('<div class="vtimeline-icon"><i class="fa fa-map-marker"></i></div>');
});
// Add dates to the timeline if exists
$this.find('.vtimeline-content').each(function() {
var date = $(this).data('date');
if (date) { // Prepend if exists
$(this).parent().prepend('<span class="vtimeline-date">'+date+'</span>');
}
});
});
// Open mobile menu
$('#mobile-menu-open').click(function() {
$('header, body').addClass('active');
});
// Close mobile menu
$('#mobile-menu-close').click(function() {
$('header, body').removeClass('active');
});
// Load additional projects
$('#view-more-projects').click(function(e){
e.preventDefault();
$(this).fadeOut(300, function() {
$('#more-projects').fadeIn(300);
});
});
})(jQuery);
| JavaScript | 0.000002 | @@ -1,257 +1,7 @@
/*!
-%0A Title: Dev Portfolio Template%0A Version: 1.2.1%0A Last Change: 08/27/2017%0A Author: Ryan Fitzgerald%0A Repo: https://github.com/RyanFitzgerald/devportfolio-template%0A Issues: https://github.com/RyanFitzgerald/devportfolio-template/issues
%0A%0A
|
106595d0f722a14c4f7ddedd6ae252b9da0e0a74 | Add check functions | js/toolbar.js | js/toolbar.js | function sanitizeInput(string) {
console.log("test");
}
function openNewTicket(ticket) {
addHistory(ticket);
chrome.storage.sync.get(function(items) {
var url = items.useURL;
var defaultProject = items.useDefaultProject;
window.open(url + "/" + defaultProject + "-" + ticket, "_blank", "", false);
});
}
document.addEventListener('keydown', function(key) {
// Keycode 13 is Enter - Reference: https://css-tricks.com/snippets/javascript/javascript-keycodes/
if (key.keyCode == 13) {
var user_input = document.getElementById("ticket").value;
openNewTicket(user_input);
}
});
window.addEventListener('load', function() {
retrieveHistory();
});
function retrieveHistory() {
// Set default useHistory if undefined
chrome.storage.sync.get({"useHistory": []}, function(items) {
var historyStorage = items.useHistory;
var historyList = document.getElementById("historyList");
// Build history list
historyStorage.forEach(function (item) {
var li = document.createElement("li");
li.textContent = item;
historyList.appendChild(li);
}); //end foreach
}); //end sync
} //end retrieveHistory
function addHistory(searchString) {
chrome.storage.sync.get({"useHistory": []}, function (result) {
var useHistory = result.useHistory;
// We only want the last 5 results
while (useHistory.length >= 5) {
useHistory.pop();
chrome.storage.sync.set({useHistory: useHistory}, function () { });
}
// Add 1 to the top of the list
useHistory.unshift(searchString);
chrome.storage.sync.set({useHistory: useHistory}, function () {});
});
}; | JavaScript | 0.000001 | @@ -6,54 +6,577 @@
ion
-sanitizeInput(string) %7B%0A console.log(%22test%22);
+formCustomProject(string) %7B%0A // Default ticket pattern%0A var regex = new RegExp('(%5Ba-z%5D%7B2,%7D-%5C%5Cd+)', 'i');%0A var text_found = string.match(regex);%0A%0A if (text_found) %7B%0A return text_found;%0A %7D%0A%0A // TODO:Ticket pattern, but missing the -%0A var regex = new RegExp('(%5Ba-z%5D%7B2,%7D%5C%5Cd+)', 'i');%0A var text_found = string.match(regex); %0A%0A%7D%0A%0Afunction isDefaultProject(string) %7B%0A // TODO: Only Numbers - use default%0A var regex = new RegExp('(%5E%5C%5Cd+)', 'i');%0A var isDefault = string.match(regex); %0A%0A if (isDefault) %7B%0A return true;%0A %7D else %7B%0A return false;%0A %7D%0A
%0A%7D%0A%0A
@@ -749,16 +749,53 @@
oject;%0A%0A
+ if(isDefaultProject(ticket)) %7B%0A
wind
@@ -870,368 +870,166 @@
se);
-%09%0A%09%09%0A%09%7D);%0A%0A%7D%0A%0Adocument.addEventListener('keydown', function(key) %7B%0A%09// Keycode 13 is Enter - Reference: https://css-tricks.com/snippets/javascript/javascript-keycodes/%0A%09if (key.keyCode == 13) %7B%0A%09%09var user_input = document.getElementById(%22ticket%22).value;%0A%09%09openNewTicket(user_input);%0A%09%7D%0A%7D);%0A%0Awindow.addEventListener('load', function() %7B%0A retrieveHistory();%0A%7D);
+ %0A %7D else %7B%0A // TODO: Form custom url %5E%5E%0A window.open(url + %22/b%22 + defaultProject + %22-%22 + ticket, %22_blank%22, %22%22, false); %0A %7D%0A%0A%09%7D);%0A%0A%7D
%0A%0Afu
@@ -2030,8 +2030,370 @@
%7D);%0A%7D;
+%0A%0Adocument.addEventListener('keydown', function(key) %7B%0A // Keycode 13 is Enter - Reference: https://css-tricks.com/snippets/javascript/javascript-keycodes/%0A if (key.keyCode == 13) %7B%0A var user_input = document.getElementById(%22ticket%22).value;%0A openNewTicket(user_input.trim());%0A %7D%0A%7D);%0A%0Awindow.addEventListener('load', function() %7B%0A retrieveHistory();%0A%7D);
|
64d1f762767d0f289fae93854d8e2b22b3a5b375 | fix bug | modules/monitoring/metrics/cpu-metric.js | modules/monitoring/metrics/cpu-metric.js | 'use strict';
const os = require('os');
class CPUCoreInfo {
constructor(core) {
this.core = core;
}
get usedTime() {
return this.core.user + this.core.nice + this.core.sys;
}
get totalTime() {
return this.core.user + this.core.nice + this.core.sys + this.core.idle;
}
/**
*
* @param {CPUCoreInfo} current
* @param {CPUCoreInfo} previous
*/
static getTotalTime(current, previous) {
return (current.usedTime - previous.usedTime) / (current.totalTime - previous.totalTime) * 100.00;
}
/**
*
* @param {CPUCoreInfo} current
* @param {CPUCoreInfo} previous
*/
static getSystemTime(current, previous) {
return (current.core.sys - previous.core.sys) / (current.totalTime - previous.totalTime) * 100.00;
}
/**
*
* @param {CPUCoreInfo} current
* @param {CPUCoreInfo} previous
*/
static getUserTime(current, previous) {
return (current.core.user - previous.core.user) / (current.totalTime - previous.totalTime) * 100.00;
}
}
class CPUInfo {
constructor() {
const cpus = os.cpus();
this.cores = new Array(cpus.length);
let i = cpus.length;
while (i--) {
this.cores[i] = new CPUCoreInfo(cpus[i].times);
}
}
}
function ignoreMetric(rules, metric, component) {
return rules.hasOwnProperty(metric) || rules.hasOwnProperty(metric + component);
}
exports.usagePerSecond = (rules, cb) => {
let previousInfo = new CPUInfo();
setTimeout(() => {
try {
let currentInfo = new CPUInfo();
const result = {};
let i = currentInfo.cores.length;
let system = 0;
let user = 0;
let total = 0;
const ts = new Date();
while (i--) {
result[`system.cpu.${i}.system`] = {
measure: '%',
ts: ts,
component: i,
value: CPUCoreInfo.getSystemTime(currentInfo.cores[i], previousInfo.cores[i])
};
system += result[`system.cpu.${i}.system`].value;
result[`system.cpu.${i}.user`] = {
measure: '%',
ts: ts,
component: i,
value: CPUCoreInfo.getSystemTime(currentInfo.cores[i], previousInfo.cores[i])
};
user += result[`system.cpu.${i}.user`].value;
result[`system.cpu.${i}.total`] = {
measure: '%',
ts: ts,
component: i,
value: CPUCoreInfo.getSystemTime(currentInfo.cores[i], previousInfo.cores[i])
};
total += result[`system.cpu.${i}.total`].value;
}
result['system.cpu.system'] = {measure: '%', ts: ts, value: system / currentInfo.cores.length};
result['system.cpu.user'] = {measure: '%', ts: ts, value: user / currentInfo.cores.length};
result['system.cpu.total'] = {measure: '%', ts: ts, value: total / currentInfo.cores.length};
currentInfo = null;
previousInfo = null;
for (var k in result) {
if (ignoreMetric(rules, k)) {
delete result[k];
}
}
cb(null, result);
} catch (e) {
cb(e, {});
}
}, 1000)
}; | JavaScript | 0.000001 | @@ -2367,38 +2367,36 @@
CPUCoreInfo.get
-System
+User
Time(currentInfo
@@ -2694,38 +2694,37 @@
CPUCoreInfo.get
-System
+Total
Time(currentInfo
|
2fbb72c25637f7485d405030def449921d2f1cec | fix mistake -.- | roo.js | roo.js | (function( global, factory ){
'use strict';
// Environment Detect
global.document ? factory( global || this ) : console.log('Roo must run in Document !');
})
(
// As Window
this,
// Factory
function( window, undefined ){
var
// Window
w = window,
// Document
d = w.document,
// Body
b = d.body,
// Head
h = d.querySelector ? d.querySelector('head') : d.getElementByTagName('head')[0],
// Noop
noop = function(){},
// Location
location = w.location,
// Store Cache
store = [],
// Roo
r = {
// Version
version: '1.0.2015.0409',
// Console Log
log: function( obj, mode ){
return obj ?
// Console Object
function( info, i ){
if( info.constructor !== String ){
for( i in obj ){
info += i + ': ' + obj[i] + '\n';
}
}
else{
info = obj;
}
mode ?
function( info, pre ){
pre.innerHTML = info,
pre.style.cssText = 'box-sizing: border-box; position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 2147483584; padding: 1rem; background: rgba(255, 255, 255, .88);',
b.appendChild( pre );
}( info, d.createElement('pre') ):
console.debug( info );
}(''):
// Console Error
w.onerror = function(){
return r.log( arguments, true ), true;
};
},
// Manifest
config: function( config ){
return {
// Base Url
base: config.base || ( location.protocol + '//' + location.host + '/' )
}
}
( this.config || {} ),
// Each List
each: function( arr, callback, type ){
return function( len, i, rate ){
rate = type ? ( type.constructor === Number ? type : 2 ) : 1;
if( len ){
if( !~type ){ // -1
for( i = len; i--; ){
callback( i, arr[i] );
}
}
else{
for( i = 0; i < len; i++ ){
if( type == 'odd' ){
if( i % rate == 1 ){
callback( i, arr[i] );
}
}
else{
if( !(i % rate) ){
callback( i, arr[i] );
}
}
}
}
}
else{
for( i in arr ){
callback( i, arr[i] );
}
}
}( arr.length );
},
// Recursive Array
recursive: function( arr, callback ){
return function( fn ){
if( arr.length ){
callback( arr.shift(), function(){ return fn( arr, callback ) });
}
}( arguments.callee );
},
// Tolerance AMD
tolerance: function( store ){
r.each( store, function( index, item ){
switch( item ){
case 'jquery':
store[ index ] = w['jQuery'];
break;
}
});
return store;
},
// Read Resource
read: function( url, callback ){
callback = callback || noop;
return function( type, item ){
switch( type ){
// Json
case 'json':
item = w.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
item.onreadystatechange = function(){
if( item.readyState == 4 && item.status == 200 ){
callback( eval('(' + item.responseText + ')') );
}
};
item.open('GET', url, true);
item.send();
break;
// Image
case 'img':
item = new Image();
item.src = url;
item.complete ? callback( item ) : ( item.onload = function(){
callback( item ), item.onload = null;
});
break;
// Javascript
case 'js':
item = d.createElement('script');
item.type = 'text/javascript',
item.language = 'javascript',
item.defer = false,
item.src = url;
item.onload = item.onreadystatechange = function(){
if( item.ready ){
return false;
}
if( !item.readyState || item.readyState == 'loaded' || item.readyState == 'complete' ){
item.ready = true, callback( item );
}
}
b.appendChild( item );
break;
// Stylesheet
case 'css':
item = d.createElement('link');
item.type = 'text/css',
item.rel = 'stylesheet',
item.href = url;
h.appendChild( item );
callback( item );
break;
default: r.log('unknow type: ' + type);
}
}( function( type ){
return ~['jpg','jpeg','gif','png','bmp'].join(' ').indexOf(type) ? 'img' : type;
}( /\w+$/.exec( url ).toString().toLowerCase() ) );
},
// Preload
preload: function( resource, callback ){
callback = callback || noop;
// Clear Store
store = [];
return function( index ){
switch( resource.constructor ){
case String:
r.read( r.config.base + resource, function( item ){
callback( item, index );
});
break;
case Array:
// Recursive Resource
r.recursive( resource, function( url, recursive ){
r.read( r.config.base + url, function( item ){
callback( item, index ), index++, recursive();
});
});
break;
default: r.log('unknow resource: ' + resource);
}
}( 0 );
},
// Use Javascript Library
use: function( library, holder, callback ){
library = library || [], holder = holder || '', callback = callback || noop;
switch( holder.constructor ){
case Function:
callback = holder, holder = undefined;
break;
case String:
break;
case Array:
break;
default:;
}
r.preload( library, function( item, index ){
if( !library.length ){
callback.apply( this, r.tolerance( store ) );
}
});
}
};
// Define
w.define = function( callback ){
store.push( callback.constructor === Function ? callback.apply( this, r.tolerance( store ) ) : callback );
};
// For AMD
w.define.amd = {
// jQuery
jQuery: true
};
return w.roo = w.r = r;
}); | JavaScript | 0.000262 | @@ -681,20 +681,19 @@
%09%09%09%09if(
-info
+obj
.constru
|
9f6c5ffe0bdf2d06836a7e50e23988b2e2c22ee6 | Increase timeout delay | test/gulp.js | test/gulp.js | import '../src'
import bufferEqual from 'buffer-equal'
import gulp from 'gulp'
import rump from 'rump'
import timeout from 'timeout-then'
import {colors} from 'gulp-util'
import {readFile, writeFile} from 'mz/fs'
import {sep} from 'path'
import {spy} from 'sinon'
const {stripColor} = colors
describe('tasks', function() {
this.timeout(0)
beforeEach(() => {
rump.configure({paths: {
source: {root: 'test/src', static: ''},
destination: {root: 'tmp'},
}})
})
it('are added and defined', () => {
const callback = spy()
rump.on('gulp:main', callback)
rump.on('gulp:static', callback)
rump.addGulpTasks({prefix: 'spec'})
callback.should.be.calledTwice()
gulp.tasks['spec:info:static'].should.be.ok()
gulp.tasks['spec:build:static'].should.be.ok()
gulp.tasks['spec:watch:static'].should.be.ok()
})
it('display correct information in info task', () => {
const logs = [],
{log} = console
console.log = (...args) => logs.push(stripColor(args.join(' ')))
gulp.start('spec:info')
console.log = log
logs.slice(-6).should.eql([
'',
'--- Static v0.7.0',
`Static files from test${sep}src are copied to tmp`,
'Affected files:',
'index.html',
'',
])
})
describe('for building', () => {
let original
before(async(done) => {
original = await readFile('test/src/index.html')
gulp.task('postbuild', ['spec:watch'], () => done())
gulp.start('postbuild')
})
after(async() => await writeFile('test/src/index.html', original))
it('handles updates', async() => {
let content = await readFile('tmp/index.html')
bufferEqual(content, original).should.be.true()
await timeout(800)
await writeFile('test/src/index.html', '<h1>New</h1>')
await timeout(800)
content = await readFile('tmp/index.html')
bufferEqual(content, original).should.be.false()
})
})
})
| JavaScript | 0.000002 | @@ -1735,33 +1735,34 @@
await timeout(
-8
+30
00)%0A await
@@ -1834,9 +1834,10 @@
out(
-8
+30
00)%0A
|
80f1e9081b30f00c39730b0ce132544712c3cf0f | Test readDir | test/hoax.js | test/hoax.js |
var path = require('path')
, load = require('./load').loadModule
, hoax = load(path.resolve(__dirname, '../lib/index.js'))
, assert = require('assert');
// Test fixtures
var flow = path.resolve(__dirname, './fixtures/01 Uppermost - Flow.mp3')
, norm = path.resolve(__dirname, './fixtures/02 Uppermost - The Norm.mp3');
describe('Core functionality', function () {
it('Should be able to read id3 tags with Mutagen', function () {
hoax.readTag(flow, function (err, data) {
assert.equal('Flow', data.title);
assert.equal('Uppermost', data.artist);
assert.equal('21f965c6-5463-44a7-9897-7d9536d2db86', data._id);
});
});
});
| JavaScript | 0.000001 | @@ -184,16 +184,69 @@
ures%0Avar
+ fixtures = path.resolve(__dirname, './fixtures')%0A ,
flow =
@@ -307,16 +307,16 @@
w.mp3')%0A
-
, norm
@@ -431,16 +431,17 @@
on () %7B%0A
+%0A
it('Sh
@@ -709,19 +709,254 @@
%7D);%0A
-
%7D);%0A
+%0A it('Can glob a directory looking for .mp3 files', function () %7B%0A hoax.readDir(fixtures, function (err, data) %7B%0A assert.equal(2, data.length);%0A assert.equal(flow, data%5B0%5D);%0A %7D);%0A %7D);%0A%0A it('Should be more modular')%0A%0A
%7D);%0A%0A
|
ee3623d9e6d407e91209844c87eb807f459f8492 | Fix missing parameter in uncaughtException handler | run.js | run.js | // ## Kumascript server runner
//
// Command line KumaScript server runner
/*jshint node: true, expr: false, boss: true */
// ### Prerequisites
var util = require('util'),
http = require('http'),
fs = require('fs'),
net = require('net'),
_ = require('underscore'),
nconf = require('nconf'),
winston = require('winston'),
kumascript = require(__dirname),
ks_utils = kumascript.utils,
ks_server = kumascript.server,
ks_repl = kumascript.repl;
// ### Default configuration settings
// This could go in `kumascript_settings.json` in the parent project.
var DEFAULT_CONFIG = {
log: {
console: false,
file: {
filename: 'kumascript.log',
maxsize: 1024 * 100, // 100k
maxFiles: 5
}
},
statsd: {
enabled: false,
host: '127.0.0.1',
port: 8125
},
server: {
port: 9080,
numWorkers: 16,
workerConcurrency: 4,
workerTimeout: 1000 * 60 * 10,
workerMaxJobs: 8,
workerRetries: 10,
document_url_template:
"https://developer.mozilla.org/en-US/docs/{path}?raw=1",
template_url_template:
"https://developer.mozilla.org/en-US/docs/en-US/Template:{name}?raw=1",
template_cache_control: 'max-age=3600'
},
repl: {
enabled: true,
host: "127.0.0.1",
port: 9070
}
};
// ### Initialize configuration
//
// Attempt to load from a prioritized series of configuration files.
//
// 1. Environ var `KUMASCRIPT_CONFIG`
// 2. `kumascript_settings_local.json` in current dir
// 3. `kumascript_settings.json` in current dir
var cwd = process.cwd(),
conf_fns = [
cwd + '/kumascript_settings.json',
cwd + '/kumascript_settings_local.json',
process.env.KUMASCRIPT_CONFIG
];
_.each(conf_fns, function (conf_fn) {
if (!conf_fn) { return; }
try { fs.statSync(conf_fn).isFile(); }
catch (e) { return; }
nconf.file({ file: conf_fn });
});
// Include the fallback defaults.
nconf.defaults(DEFAULT_CONFIG);
// ### Initialize logging
var log_conf = nconf.get('log');
if (!log_conf.console) {
winston.remove(winston.transports.Console);
}
if (log_conf.file) {
// TODO: Need a rotating file logger here!
winston.add(winston.transports.File, log_conf.file);
}
// TODO: Accept log line format from config?
// TODO: Use [winston-syslog](https://github.com/indexzero/winston-syslog)?
// Make a nicer alias to the default logger
var log = winston;
var statsd = ks_utils.getStatsD({
statsd_conf: nconf.get('statsd')
});
var server_conf = nconf.get('server');
server_conf.statsd = statsd;
// Start up a server instance.
var port = server_conf.port;
log.info("Worker PID " + process.pid + " starting on port " + port);
var server = new ks_server.Server(server_conf);
server.listen(port);
// Open up a telnet REPL for interactive access to the server.
var repl = null;
var repl_config = nconf.get('repl');
if (repl_config.enabled) {
repl = new ks_repl.REPL(repl_config, {
__: _,
log: log,
server_conf: server_conf,
kill: performExit,
server: server
});
repl.listen(repl_config.host, repl_config.port);
}
function performExit () {
log.info("Master PID " + process.pid + " exiting");
server.close();
if (repl) { repl.close(); }
process.exit(0);
}
// More gracefully handle some common exit conditions...
process.on('SIGINT', function () {
log.info("Received SIGINT, exiting...");
performExit();
});
process.on('SIGTERM', function () {
log.info("Received SIGTERM, exiting...");
performExit();
});
process.on('uncaughtException', function () {
log.error('uncaughtException:', err.message);
log.error(err.stack);
performExit();
});
| JavaScript | 0.000008 | @@ -3705,32 +3705,35 @@
ion', function (
+err
) %7B%0A log.erro
|
43d52eaae45c75c983c9b847fcf619e597af3316 | Add test of passing hogan template options | test/main.js | test/main.js | var compile = require('../');
var should = require('should');
var os = require('os');
var path = require('path');
var gutil = require('gulp-util');
var File = gutil.File;
var Buffer = require('buffer').Buffer;
require('mocha');
describe('gulp-compile-hogan', function() {
var fakeFile, fakeFile2;
before(function() {
fakeFile = new File({
cwd: "",
base: "test",
path: "test/file.js",
contents: new Buffer("hello {{place}}")
});
fakeFile2 = new File({
cwd: "",
base: "test",
path: "test/file2.js",
contents: new Buffer("{{greeting}} world")
});
});
describe('compile()', function() {
it('should compile templates into one file', function(done) {
var stream = compile("test.js");
stream.on('data', function(newFile){
should.exist(newFile);
should.exist(newFile.path);
should.exist(newFile.relative);
should.exist(newFile.contents);
var newFilePath = path.resolve(newFile.path);
var expectedFilePath = path.resolve("test/test.js");
newFilePath.should.equal(expectedFilePath);
newFile.relative.should.equal("test.js");
Buffer.isBuffer(newFile.contents).should.equal(true);
done();
});
stream.write(fakeFile);
stream.write(fakeFile2);
stream.end();
});
it('should compile string templates to amd modules', function(done) {
var stream = compile("test.js");
stream.on('data', function(newFile){
var lines = newFile.contents.toString().split(gutil.linefeed);
lines[0].should.equal('define(function(require) {');
lines[1].should.equal(" var Hogan = require('hogan');");
lines[2].should.equal(" var templates = {};");
lines[3].should.match(/templates\["file"\] = new Hogan.Template/);
lines[4].should.match(/templates\["file2"\] = new Hogan.Template/);
lines.pop().should.equal('})');
lines.pop().should.equal(' return templates;');
done();
});
stream.write(fakeFile);
stream.write(fakeFile2);
stream.end();
});
it('should compile string templates to commonjs modules', function(done) {
var stream = compile("test.js", {
wrapper: 'commonjs'
});
stream.on('data', function(newFile){
var lines = newFile.contents.toString().split(gutil.linefeed);
lines[0].should.equal('module.exports = (function() {');
lines[1].should.equal(" var Hogan = require('hogan');");
lines[2].should.equal(" var templates = {};");
lines[3].should.match(/templates\["file"\] = new Hogan.Template/);
lines[4].should.match(/templates\["file2"\] = new Hogan.Template/);
lines.pop().should.equal('})();');
lines.pop().should.equal(' return templates;');
done();
});
stream.write(fakeFile);
stream.write(fakeFile2);
stream.end();
});
it('should create mustache template objects with a render method', function(done) {
// No wrapper so need to make Hogan (capitalised) available
var Hogan = require('hogan-updated');
var stream = compile("test.js", {
wrapper: false
});
stream.on('data', function(newFile) {
eval(newFile.contents.toString());
var rendered = templates.file.render({ place: 'world'});
rendered.should.equal('hello world');
var rendered2 = templates.file2.render({ greeting: 'hello'});
rendered2.should.equal('hello world');
done();
});
stream.write(fakeFile);
stream.write(fakeFile2);
stream.end();
});
});
});
| JavaScript | 0 | @@ -674,24 +674,206 @@
%7D);%0A%0A
+ fakeFile3 = new File(%7B%0A cwd: %22%22,%0A base: %22test%22,%0A path: %22test/file3.js%22,%0A contents: new Buffer(%22%3C%25 greeting %25%3E world%22)%0A %7D);%0A
%7D);%0A
@@ -3674,81 +3674,8 @@
e) %7B
-%0A%0A // No wrapper so need to make Hogan (capitalised) available
%0A
@@ -3721,17 +3721,16 @@
ated');%0A
-%0A
@@ -4243,32 +4243,32 @@
rite(fakeFile);%0A
-
stre
@@ -4317,29 +4317,695 @@
d();%0A %7D);
+%0A%0A it('should pass options to the hogan rendering engine', function(done) %7B%0A var Hogan = require('hogan-updated');%0A var stream = compile(%22test.js%22, %7B%0A wrapper: false,%0A templateOptions: %7B%0A delimiters: '%3C%25 %25%3E'%0A %7D%0A %7D);%0A stream.on('data', function(newFile) %7B%0A eval(newFile.contents.toString());%0A var rendered = templates.file3.render(%7B greeting: 'hello'%7D);%0A rendered.should.equal('hello world');%0A done();%0A %7D);%0A stream.write(fakeFile3);%0A stream.end();%0A %7D);
%0A %7D);%0A%7D);%0A
|
c1afc1a8ac6f13d5ecbee5d7a85ff6ce7169fc34 | Update init.js | physics/init.js | physics/init.js | const Physics = {
airResistance: 0.99,//The velocity of everything is multiplied by this number each frame.
airResistanceSleeping: 0.9,//The air resistance of something that is "asleep".
gravityForce: 0.7,//The magnitude of gravity
constraintCompensation: 0.2,//The intensity of rigid constraints' compensation for oscillation.
constraintAdjustment: 0.3,//How much rigid constraints adjust the
sleepThreshold: 2,//Maximum velocity at which any circle can be "asleep".
circleAdjustment: 0.3//The intensity of the position adjustment when circles collide
};
| JavaScript | 0.000001 | @@ -1,13 +1,28 @@
-const
+if(!Physics) %7B%0A var
Physics
@@ -26,16 +26,18 @@
ics = %7B%0A
+
airRes
@@ -120,16 +120,18 @@
frame.%0A
+
airRes
@@ -206,16 +206,18 @@
ep%22.%0A %0A
+
gravit
@@ -258,16 +258,18 @@
vity%0A %0A
+
constr
@@ -360,16 +360,18 @@
tion.%0A
+
+
constrai
@@ -432,16 +432,18 @@
the %0A %0A
+
sleepT
@@ -513,16 +513,18 @@
ep%22.%0A %0A
+
circle
@@ -606,7 +606,11 @@
ide%0A
+
%7D;%0A
+%7D%0A
|
e351e73bc6b50b2673f56eb6a67f19e9888435f2 | Update tests to test with Unicode | test/node.js | test/node.js | var test = require('tape');
var crypto = require('crypto');
var cryptoB = require('../');
function assertSame(name, fn) {
test(name, function (t) {
t.plan(1);
fn(crypto, function (err, expected) {
fn(cryptoB, function (err, actual) {
t.equal(actual, expected);
t.end();
});
});
});
}
var algorithms = ['sha1', 'sha256', 'md5'];
var encodings = ['binary', 'hex', 'base64'];
algorithms.forEach(function (algorithm) {
encodings.forEach(function (encoding) {
assertSame(algorithm + ' hash using ' + encoding, function (crypto, cb) {
cb(null, crypto.createHash(algorithm).update('hello', 'utf-8').digest(encoding));
})
assertSame(algorithm + ' hmac using ' + encoding, function (crypto, cb) {
cb(null, crypto.createHmac(algorithm, 'secret').update('hello', 'utf-8').digest(encoding))
})
});
assertSame(algorithm + ' with raw binary', function (crypto, cb) {
var seed = 'hello';
for (var i = 0; i < 1000; i++) {
seed = crypto.createHash(algorithm).update(seed).digest('binary');
}
cb(null, crypto.createHash(algorithm).update(seed).digest('hex'));
});
assertSame(algorithm + ' empty string', function (crypto, cb) {
cb(null, crypto.createHash(algorithm).update('').digest('hex'));
});
});
test('randomBytes', function (t) {
t.plan(5);
t.equal(cryptoB.randomBytes(10).length, 10);
t.ok(cryptoB.randomBytes(10) instanceof Buffer);
cryptoB.randomBytes(10, function(ex, bytes) {
t.error(ex);
t.equal(bytes.length, 10);
t.ok(bytes instanceof Buffer);
t.end();
});
});
| JavaScript | 0 | @@ -681,33 +681,33 @@
hm).update('hell
-o
+%C3%B8
', 'utf-8').dige
@@ -887,17 +887,17 @@
te('hell
-o
+%C3%B8
', 'utf-
@@ -1033,17 +1033,17 @@
= 'hell
-o
+%C3%B8
';%0A
@@ -1125,37 +1125,49 @@
gorithm).update(
+new Buffer(
seed)
+)
.digest('binary'
@@ -1232,21 +1232,33 @@
.update(
+new Buffer(
seed)
+)
.digest(
|
793f6233bd5c6eca82dcf796f6d76dae305e6f98 | append nodes | test/node.js | test/node.js |
/**
* Test dependencies.
*/
var Node = require('../lib/node');
var assert = require('assert');
describe("node api", function() {
it('should create node with type', function() {
var node = new Node(1);
assert.equal(node.nodeType, 1);
});
});
| JavaScript | 0.000136 | @@ -93,17 +93,16 @@
ert');%0A%0A
-%0A
describe
@@ -111,12 +111,8 @@
node
- api
%22, f
@@ -127,11 +127,13 @@
) %7B%0A
-%09%0A%09
+ %0A
it('
@@ -176,18 +176,20 @@
ion() %7B%0A
-%09%09
+
var node
@@ -208,10 +208,12 @@
1);%0A
-%09%09
+
asse
@@ -244,9 +244,284 @@
1);%0A
-%09
+ %7D);%0A%0A describe('append node', function() %7B%0A%0A it('should append an other node', function() %7B%0A var node = new Node(1);%0A node.appendChild(new Node(2));%0A%0A assert.equal(node.childNodes.length, 1);%0A assert.equal(node.childNodes%5B0%5D.nodeType, 2);%0A %7D);%0A%0A
%7D);%0A
|
462bc83b96740bf04d6c06d43ab3251833401b66 | Add test for firewall privacy. | test/open.js | test/open.js | /*jslint node: true */
"use strict";
var dualapi = require('../index');
var _ = require('underscore');
var assert = require('assert');
describe('dualapi', function () {
describe('open', function () {
var dual = dualapi();
describe('send', function () {
it('should listen for dual messages on the socket', function (done) {
dual.open(['rue'], {
on: function (target, cb) {
if (target == 'dual') {
done();
}
}
});
});
it('should listen for disconnect messages on the socket', function (done) {
dual.open(['rue2'], {
on: function (target, cb) {
if (target == 'disconnect') {
done();
}
}
});
});
it('should echo dual messages to the domain with the destination', function (done) {
dual.mount(['voiture'], function () {
done();
});
dual.open(['rue3'], {
on: function (target, cb) {
if (target === 'dual') {
cb({
to: ['voiture']
});
}
}
});
});
it('should echo dual messages to the domain preserving body', function (done) {
dual.mount(['voiture2'], function (ctxt) {
assert.deepEqual(ctxt.body, {prendre: 'gauche'});
done();
});
dual.open(['rue3'], {
on: function (target, cb) {
if (target === 'dual') {
cb({
to: ['voiture2']
, body: {prendre: 'gauche'}
});
}
}
});
});
it('should translate the from field', function (done) {
dual.mount(['voiture3'], function (ctxt) {
assert.deepEqual(ctxt.from, ['rue4', 'amerique']);
done();
});
dual.open(['rue4'], {
on: function (target, cb) {
if (target === 'dual') {
cb({
to: ['voiture3']
, from: ['amerique']
});
}
}
});
});
});
describe('firewall', function () {
it('should be able to filter messages', function (done) {
var called = 0;
dual.mount(['voiture6', '*'], function () {
called++;
});
dual.open(['rue3'], {
on: function (target, cb) {
if (target === 'dual') {
cb({ to: ['voiture6', 'red']});
cb({ to: ['voiture6', 'rouge']});
assert.equal(called, 1);
done();
}
}
}, function (ctxt, pass) {
return pass(ctxt.to[1] === 'rouge');
});
});
});
describe('receive', function () {
it('dual should transfer messages targeted to the mount point on "dual" channel', function (done) {
dual.open(['wormhole'], {
on: function (target, cb) {}
, emit: function (target) {
assert.equal(target, 'dual');
done();
}
});
dual.send(['wormhole']);
});
it('dual should transfer messages targeted below the mount point on "dual" channel', function (done) {
dual.open(['wormhole1'], {
on: function (target, cb) {}
, emit: function (target) {
assert.equal(target, 'dual');
done();
}
});
dual.send(['wormhole1', 'delta']);
});
it('dual should transfer the json context, preserving from field', function (done) {
dual.open(['wormhole2'], {
on: function (target, cb) {}
, emit: function (target, msg) {
assert.deepEqual(msg.from, ['bajor']);
done();
}
});
dual.send(['wormhole2', 'delta'], ['bajor']);
});
it('dual should transfer the json context, preserving body field', function (done) {
dual.open(['wormhole3'], {
on: function (target, cb) {}
, emit: function (target, msg) {
assert.deepEqual(msg.body, {captain: 'sisko'});
done();
}
});
dual.send(['wormhole3', 'delta'], ['bajor'], { captain: 'sisko'});
});
it('dual should transfer the json context, translating the to field', function (done) {
dual.open(['wormhole4'], {
on: function (target, cb) {}
, emit: function (target, msg) {
assert.deepEqual(msg.to, ['delta']);
done();
}
});
dual.send(['wormhole4', 'delta'], { captain: 'sisko'});
});
});
describe('disconnect', function () {
it('dual should stop sending messages to the mounted host after disconnect', function () {
var mockSocket = {};
var called = 0;
dual.mount(['sector'], function () {
called++;
});
dual.open(['deepspace'], {
on: function (target, cb) {
mockSocket[target] = cb;
}
, off: function () {}
, emit: function () {
called++;
}
});
dual.send(['deepspace']);
mockSocket.disconnect();
dual.send(['deepspace']);
assert.equal(called, 1);
});
it('dual should stop sending messages below the mounted host after disconnect', function () {
var mockSocket = {};
var called = 0;
dual.mount(['sector2'], function () {
called++;
});
dual.open(['deepspace2'], {
on: function (target, cb) {
mockSocket[target] = cb;
}
, off: function () {}
, emit: function () {
called++;
}
});
dual.send(['deepspace2', '1']);
mockSocket.disconnect();
dual.send(['deepspace2', '2']);
assert.equal(called, 1);
});
it('dual should stop listening for dual messages on disconnect', function (done) {
var mockSocket = {};
dual.open(['deepspace3'], {
on: function (target, cb) {
mockSocket[target] = cb;
}
, off: function (target, cb) {
if (target == 'dual') {
done();
}
}
});
mockSocket.disconnect();
});
it('dual should stop listening for disconnect messages on disconnect', function (done) {
var mockSocket = {};
dual.open(['deepspace3'], {
on: function (target, cb) {
mockSocket[target] = cb;
}
, off: function (target, cb) {
if (target == 'disconnect') {
done();
}
}
});
mockSocket.disconnect();
});
});
});
});
| JavaScript | 0 | @@ -3594,32 +3594,682 @@
%7D);%0A
+%0A it('ctxt should be private to the firewall', function (done) %7B%0A%0A dual.mount(%5B'voiture7', '*'%5D, function (ctxt) %7B%0A assert.equal(ctxt.to%5B1%5D, 'rouge')%0A done();%0A %7D);%0A dual.open(%5B'rue20'%5D, %7B%0A on: function (target, cb) %7B%0A if (target === 'dual') %7B%0A cb(%7B to: %5B'voiture7', 'rouge'%5D%7D);%0A %7D%0A %7D%0A %7D, function (ctxt, pass) %7B%0A ctxt.to%5B1%5D = 'blue';%0A return pass(true);%0A %7D); %0A %7D);%0A%0A
%7D);%0A%0A
|
4b26c31b3b2816610ccc5a0eff777153b08ec6ec | Remove unnecessary option "repo" from tests | test/page.js | test/page.js | var fs = require('fs');
var path = require('path');
var assert = require('assert');
var page = require('../').parse.page;
function loadPage (name, options) {
var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/' + name + '.md'), 'utf8');
return page(CONTENT, options).sections;
}
var LEXED = loadPage('PAGE', {
dir: 'course',
outdir: '_book'
});
var QUIZ_LEXED = loadPage('QUIZ_PAGE');
var HR_LEXED = loadPage('HR_PAGE');
describe('Page parsing', function() {
it('should detect sections', function() {
assert.equal(LEXED.length, 4);
});
it('should detect section types', function() {
assert.equal(LEXED[0].type, 'normal');
assert.equal(LEXED[1].type, 'exercise');
assert.equal(LEXED[2].type, 'normal');
assert.equal(QUIZ_LEXED[0].type, 'normal');
assert.equal(QUIZ_LEXED[1].type, 'quiz');
assert.equal(QUIZ_LEXED[2].type, 'normal');
assert.equal(QUIZ_LEXED[3].type, 'quiz');
});
it('should gen content for normal sections', function() {
assert(LEXED[0].content);
assert(LEXED[2].content);
});
it('should gen code and content for exercise sections', function() {
assert(LEXED[1].content);
assert(LEXED[1].code);
assert(LEXED[1].code.base);
assert(LEXED[1].code.solution);
assert(LEXED[1].code.validation);
assert(LEXED[1].code.context === null);
assert(LEXED[3].content);
assert(LEXED[3].code);
assert(LEXED[3].code.base);
assert(LEXED[3].code.solution);
assert(LEXED[3].code.validation);
assert(LEXED[3].code.context);
});
it('should merge sections correctly', function() {
// One big section
assert.equal(HR_LEXED.length, 1);
// HRs inserted correctly
assert.equal(HR_LEXED[0].content.match(/<hr>/g).length, 2);
});
it('should detect an exercise\'s language', function() {
assert.equal(LEXED[1].lang, 'python');
});
it('should render a quiz', function() {
assert(QUIZ_LEXED[1].content);
assert(QUIZ_LEXED[1].quiz);
assert(QUIZ_LEXED[1].quiz[0].base);
assert(QUIZ_LEXED[1].quiz[0].solution);
assert(QUIZ_LEXED[1].quiz[0].feedback);
assert(QUIZ_LEXED[1].quiz[1].base);
assert(QUIZ_LEXED[1].quiz[1].solution);
assert(QUIZ_LEXED[1].quiz[1].feedback);
});
});
describe('Relative links', function() {
it('should replace link to .md by link to .html', function() {
var LEXED = loadPage('MARKDOWN_LINKS', {
// GitHub repo ID
repo: 'GitBookIO/javascript',
// Imaginary folder of markdown file
dir: 'course',
outdir: 'course'
});
assert(LEXED[0].content.indexOf('test.html') !== -1);
assert(LEXED[0].content.indexOf('../before.html') !== -1);
});
});
describe('Relative images', function() {
it('should keep image relative with considering output directory in site format', function() {
var LEXED = loadPage('IMAGES', {
// GitHub repo ID
repo: 'GitBookIO/javascript',
// Imaginary folder of markdown file
dir: 'syntax',
outdir: 'syntax'
});
assert(LEXED[0].content.indexOf('"preview.png"') !== -1);
assert(LEXED[0].content.indexOf('"../preview2.png"') !== -1);
});
it('should keep image relative with considering output directory in page format', function() {
var LEXED = loadPage('IMAGES', {
// GitHub repo ID
repo: 'GitBookIO/javascript',
// Imaginary folder of markdown file
dir: 'syntax',
outdir: './'
});
assert(LEXED[0].content.indexOf('"syntax/preview.png"') !== -1);
assert(LEXED[0].content.indexOf('"preview2.png"') !== -1);
});
});
describe('Section parsing', function() {
it('should not have false positive quiz parsing', function() {
var LEXED = loadPage('FALSE_QUIZ');
assert.equal(LEXED[0].type, 'normal');
});
});
| JavaScript | 0.000013 | @@ -2586,81 +2586,8 @@
, %7B%0A
- // GitHub repo ID%0A repo: 'GitBookIO/javascript',%0A%0A
@@ -2623,32 +2623,32 @@
f markdown file%0A
+
dir:
@@ -3027,81 +3027,8 @@
, %7B%0A
- // GitHub repo ID%0A repo: 'GitBookIO/javascript',%0A%0A
@@ -3377,32 +3377,32 @@
', function() %7B%0A
+
var LEXE
@@ -3430,81 +3430,8 @@
, %7B%0A
- // GitHub repo ID%0A repo: 'GitBookIO/javascript',%0A%0A
|
aafb77266ebd4b6c5c0164a774255c25f8f71861 | optimize CircularProgress | src/CircularProgress/CircularProgress.js | src/CircularProgress/CircularProgress.js | /**
* Created by DT314 on 2017/4/7.
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Percent from '../_Percent';
import './CircularProgress.css';
export default class CircularProgress extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
percent: [0, 0]
};
}
render() {
const {children, className, style, r, width, rgba, word, percent, percentStyle} = this.props,
l = 2 * r * Math.PI,
svgStyle = {
width: (r + width) * 2,
height: (r + width) * 2,
...style
},
circleStyle = {
strokeDasharray: percent / 100 * l + ',' + l
};
return (
<div className={'circular-progress' + (className ? ' ' + className : '')}
style={svgStyle}>
<svg className="circular-progress-svg">
<circle className="circular-progress-circle"
cx={r + width}
cy={r + width}
r={r}
strokeWidth={width}
stroke={rgba}
fill="none"
style={circleStyle}>
</circle>
</svg>
{
word ?
<Percent endNum={percent}
style={percentStyle}>
{children}
</Percent>
:
null
}
</div>
);
}
};
CircularProgress.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* The style of the percent text description.
*/
percentStyle: PropTypes.object,
/**
* The radius of the progress in pixels.
*/
r: PropTypes.number,
/**
* Stroke width in pixels.
*/
width: PropTypes.number,
/**
* Override the progress's color.
*/
rgba: PropTypes.string,
/**
* The value of progress.
*/
percent: PropTypes.number,
/**
* If true,there will have a text description.
*/
word: PropTypes.bool
};
CircularProgress.defaultProps = {
className: '',
style: {},
percentStyle: {},
r: 48,
width: 2,
rgba: 'rgb(0, 188, 212)',
percent: 0,
word: true
};
| JavaScript | 0.999998 | @@ -2483,16 +2483,17 @@
es.bool%0A
+%0A
%7D;%0A%0ACirc
@@ -2518,24 +2518,25 @@
ltProps = %7B%0A
+%0A
classNam
@@ -2553,18 +2553,20 @@
style:
-%7B%7D
+null
,%0A%0A p
@@ -2668,12 +2668,13 @@
d: true%0A
+%0A
%7D;%0A%0A
|
6f0195030557740873cb6db32518f25cf0d6b140 | Remove stray log | src/client/components/header.es6 | src/client/components/header.es6 | import Cursors from 'cursors';
import React from 'react';
import * as store from 'client/store';
export default React.createClass({
mixins: [Cursors],
getInitialState: function () {
return {
isLoading: false
};
},
signOut: function () {
store.remove('key');
this.update({
isLoading: {$set: true},
key: {$set: null}
});
this.state.socket.emit('sign-out', null, this.handleSignOut);
},
handleSignOut: function (er) {
var deltas = {isLoading: {$set: false}};
if (!er) deltas.user = {$set: null};
this.update(deltas);
},
componentDidMount: function () {
this.state.socket.on('connect', this.handleConnect);
},
componentWillUnmount: function () {
this.state.socket.off('connect', this.handleConnect);
},
handleConnect: function () {
this.setKey();
},
setKey: function () {
this.update({isLoading: {$set: true}});
this.state.socket.emit('set-key', store.get('key'), this.handleSetKey);
},
handleSetKey: function (er, user) {
console.log(er, user);
if (er) return this.signOut();
store.set('key', user.key);
this.update({isLoading: {$set: false}, user: {$set: user}});
},
handleSignInClick: function () {
this.signIn(this.refs.key.getDOMNode().value);
},
handleChange: function (ev) {
this.update({key: {$set: ev.target.value}});
},
renderSignedIn: function () {
return (
<div>
You are {this.state.user.name}!
</div>
);
},
renderSignedOut: function () {
return (
<div>
<input
placeholder='Your OrgSync API Key'
ref='key'
/>
<button type='button' onClick={this.handleSignInClick}>Sign In</button>
</div>
);
},
render: function () {
return null;
}
});
| JavaScript | 0.000002 | @@ -1031,35 +1031,8 @@
) %7B%0A
- console.log(er, user);%0A
|
99cac3fb59e41403073ed6d6708b8a6fb70e30aa | Fix auto scroll in some cases by adding 10px pad | src/client/containers/Channel.js | src/client/containers/Channel.js | import _ from 'lodash'
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {
isChannelLoadingSelector, getChannelSelector, getMessagesSelector, messageRowsSelector,
} from '../selectors'
import { loadMessages } from '../actions'
import Link from '../components/Link'
import Maybe from '../components/Maybe'
import Text from '../components/Text'
import Message from '../components/Message'
import Loader from '../components/Loader'
import './Channel.css'
const DayHeader = ({ text, isoTimestamp }) => {
return (
<div className='day-header'>
<span className='text bold' title={isoTimestamp}>
{text}
</span>
<div className='divider' />
</div>
)
}
const getMessageRowKey = ({ type, payload }) => {
const keyerMapping = {
loader: () => 'loader',
day: ({ isoTimestamp }) => isoTimestamp,
message: ({ message }) => message.id,
}
return keyerMapping[type](payload)
}
const MessageRow = ({ type, payload = {} }) => {
const componentMapping = {
loader: Loader,
day: DayHeader,
message: Message,
}
const component = componentMapping[type]
const props = payload
return React.createElement(component, props)
}
const Messages = ({ messageRows }) => {
return (
<div className='messages'>
{_.map(messageRows, props => <MessageRow {...props} key={getMessageRowKey(props)} />)}
</div>
)
}
class Channel extends Component {
wrapperNode = null
autoScroll = true
persistScroll = false
scrollHeight = 0
scrollTop = 0
state = {
isTopicExpanded: false,
}
componentDidMount() {
this.props.loadMessages()
this.autoScroll = true
this.scroll()
}
componentWillUpdate(nextProps) {
const { wrapperNode } = this
if (!wrapperNode) {
return
}
this.autoScroll = wrapperNode.scrollTop + wrapperNode.offsetHeight === wrapperNode.scrollHeight
if (!this.autoScroll) {
this.persistScroll = (
!_.isEmpty(nextProps.messages)
&& _.first(nextProps.messages) !== _.first(this.props.messages)
)
if (this.persistScroll) {
this.scrollHeight = wrapperNode.scrollHeight
this.scrollTop = wrapperNode.scrollTop
}
}
}
componentDidUpdate() {
this.props.loadMessages()
this.scroll()
}
scroll() {
const { wrapperNode } = this
if (wrapperNode) {
if (this.autoScroll) {
setTimeout(() => {
wrapperNode.scrollTop = wrapperNode.scrollHeight
})
} else if (this.persistScroll) {
wrapperNode.scrollTop = this.scrollTop + (wrapperNode.scrollHeight - this.scrollHeight)
}
}
}
onRef = node => {
this.wrapperNode = node
}
onScroll = ev => {
const { target: wrapperNode } = ev
const threshold = document.documentElement.clientHeight
if (wrapperNode.scrollTop <= threshold) {
const messageFirst = _.first(this.props.messages)
this.props.loadMessages(messageFirst ? messageFirst.timestamp : null)
}
}
onTopicClick = () => {
this.setState({ isTopicExpanded: !this.state.isTopicExpanded })
}
render() {
if (this.props.isChannelLoading) {
return null
}
const { channel, messageRows } = this.props
return (
<div id='channel'>
<div className='header'>
<Link href='/'>
<h2 className='name bold'>{channel.name}</h2>
</Link>
<Maybe when={channel.topic}>
<p className='topic-wrapper'>
<Maybe when={this.state.isTopicExpanded}>
<span className='topic'>
<Text>{channel.topic}</Text>
</span>
</Maybe>
<span className='topic-ellipsis' onClick={this.onTopicClick}>…</span>
</p>
</Maybe>
</div>
<div className='messages-wrapper' ref={this.onRef} onScroll={this.onScroll}>
<Messages messageRows={messageRows} />
</div>
</div>
)
}
}
const mapStateToProps = (state, props) => ({
isChannelLoading: isChannelLoadingSelector(state),
channel: getChannelSelector()(state),
messages: getMessagesSelector()(state),
messageRows: messageRowsSelector(state),
})
const mapDispatchToProps = dispatch => ({
loadMessages: timestamp => dispatch(loadMessages(timestamp)),
})
export default connect(mapStateToProps, mapDispatchToProps)(Channel)
| JavaScript | 0 | @@ -1826,16 +1826,24 @@
Scroll =
+ (%0A
wrapper
@@ -1853,21 +1853,24 @@
e.scroll
-Top +
+Height -
wrapper
@@ -1878,49 +1878,62 @@
ode.
-offsetHeight === wrapperNode.scrollHeight
+scrollTop%0A %3C= wrapperNode.clientHeight + 10%0A )
%0A%0A
|
ffb161dc4217d12bd07dda59bbb67aa07190c269 | Fix tests | test/test.js | test/test.js | /*global afterEach, beforeEach, describe, it */
'use strict';
var assert = require('assert');
var binCheck = require('bin-check');
var BinBuild = require('bin-build');
var execFile = require('child_process').execFile;
var fs = require('fs');
var path = require('path');
var rm = require('rimraf');
describe('mozjpeg()', function () {
afterEach(function (cb) {
rm(path.join(__dirname, 'tmp'), cb);
});
beforeEach(function () {
fs.mkdirSync(path.join(__dirname, 'tmp'));
});
it('should rebuild the mozjpeg binaries', function (cb) {
var tmp = path.join(__dirname, 'tmp');
var builder = new BinBuild()
.src('https://github.com/mozilla/mozjpeg/archive/v1.0.1.tar.gz')
.cfg('autoreconf -fiv && ./configure --prefix="' + tmp + '" --bindir="' + tmp + '" --libdir="' + tmp + '"')
.make('make && make install');
builder.build(function (err) {
assert(!err);
assert(fs.existsSync(path.join(tmp, 'mozjpeg')));
cb();
});
});
it('should return path to binary and verify that it is working', function (cb) {
var binPath = require('../').path;
var args = [
'-outfile', path.join(__dirname, 'tmp/test.jpg'),
path.join(__dirname, 'fixtures/test.jpg')
];
binCheck(binPath, args, function (err, works) {
cb(assert.equal(works, true));
});
});
it('should minify a JPG', function (cb) {
var binPath = require('../').path;
var args = [
'-outfile', path.join(__dirname, 'tmp/test.jpg'),
path.join(__dirname, 'fixtures', 'test.jpg')
];
execFile(binPath, args, function () {
var src = fs.statSync(path.join(__dirname, 'fixtures/test.jpg')).size;
var dest = fs.statSync(path.join(__dirname, 'tmp/test.jpg')).size;
cb(assert(dest < src));
});
});
});
| JavaScript | 0.000003 | @@ -1003,23 +1003,24 @@
n(tmp, '
-moz
jpeg
+tran
')));%0A
|
ae71193e63172f427ed13a71deaedce666ca3010 | Clean up karma.conf.js | karma.conf.js | karma.conf.js | const path = require('path');
const webpackConfiguration = require('./webpack.config.js');
delete webpackConfiguration.entry;
webpackConfiguration.module.postLoaders = [
// instrument only testing sources with Istanbul
{
test: /\.js$/,
include: path.resolve('src/'),
loader: 'istanbul-instrumenter',
query: {
esModules: true,
},
},
];
module.exports = function (config) {
// Karma configuration
const configuration = {
files: [
// only specify one entry point
// and require all tests in there
'test/test-main.js',
],
preprocessors: {
// add webpack as preprocessor
'test/test-main.js': ['webpack'],
},
frameworks: ['mocha'],
reporters: ['mocha', 'coverage'],
coverageReporter: {
reporters: [
{ type: 'text' },
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' },
],
},
istanbulReporter: {
},
webpack: webpackConfiguration,
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
logLevel: config.LOG_WARN,
autoWatch: true,
singleRun: false,
colors: true,
webpackMiddleware: {
// webpack-dev-middleware configuration
// i. e.
stats: 'errors-only',
},
};
if (process.env.TRAVIS) {
configuration.browsers = ['Chrome_travis_ci'];
}
config.set(configuration);
};
| JavaScript | 0.000345 | @@ -90,89 +90,113 @@
);%0A%0A
-delete webpackConfiguration.entry;%0AwebpackConfiguration.module.postLoaders = %5B%0A
+// Remove default entry point since we're using test-main.js instead%0Adelete webpackConfiguration.entry;%0A%0A
// i
@@ -244,14 +244,53 @@
bul%0A
- %7B%0A
+webpackConfiguration.module.postLoaders = %5B%7B%0A
te
@@ -304,18 +304,16 @@
js$/,%0A
-
-
include:
@@ -335,18 +335,16 @@
src/'),%0A
-
loader
@@ -370,18 +370,16 @@
enter',%0A
-
query:
@@ -385,18 +385,16 @@
: %7B%0A
-
esModule
@@ -406,20 +406,14 @@
ue,%0A
- %7D,%0A
%7D,%0A
+%7D
%5D;%0A%0A
@@ -1156,16 +1156,17 @@
ox'%5D
+,
%0A %7D
%0A
@@ -1161,16 +1161,17 @@
%0A %7D
+,
%0A %7D,%0A
|
d158a5a8fffd4a6db1ff5266baff838387d27000 | Add bower back to ignore | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'browserify', 'chai'],
// list of files / patterns to load in the browser
files: [
'app/**/*.js'
],
// list of files to exclude
exclude: [
// 'app/bower_components/**/*.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/**/*.js': ['browserify']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
browserify: {
debug: true,
transform: []
}
});
};
| JavaScript | 0 | @@ -500,19 +500,16 @@
- //
'app/bo
|
301149a14576fa5a072264e4b06c639f5b19e1c2 | fix build scripts | karma.conf.js | karma.conf.js | module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha'],
files: [
{ pattern: 'https://cdn.polyfill.io/v2/polyfill.js?features=default,WeakMap,WeakSet&flags=gated', watched: false, served: false, included: true },
{ pattern: 'node_modules/power-assert/build/power-assert.js', watched: true, served: true, included: true },
{ pattern: 'node_modules/typed-dom/dist/typed-dom.js', watched: true, served: true, included: true },
{ pattern: 'node_modules/spica/dist/spica.js', watched: true, served: true, included: true },
{ pattern: 'node_modules/localsocket/dist/localsocket.js', watched: true, served: true, included: true },
{ pattern: 'dist/*.js', watched: true, served: true, included: true },
{ pattern: 'test/integration/usecase/**/*.{html,css,js}', watched: true, served: true, included: true },
{ pattern: 'test/unit/fixture/**/*', watched: true, served: true, included: false }
],
exclude: [
],
espowerPreprocessor: {
options: {
emitActualCode: false,
ignoreUpstreamSourceMap: true
}
},
reporters: ['dots'],
coverageReporter: {
dir: 'coverage',
subdir: function (browser, platform) {
return browser.toLowerCase().split(' ')[0];
},
reporters: [
{ type: 'lcov' },
{ type: 'text-summary', subdir: '.', file: 'summary.txt' }
]
},
autoWatch: true,
autoWatchBatchDelay: 500,
customLaunchers: {
IE11: {
base: 'IE',
'x-ua-compatible': 'IE=EmulateIE11'
}
},
browsers: ['Chrome']
});
};
| JavaScript | 0.000006 | @@ -192,16 +192,69 @@
,WeakSet
+,Array.prototype.findIndex,Array.prototype.@@iterator
&flags=g
|
a6972b819eb941ce0abda8fbac60cfa6dc87ac1f | add port 5757 | karma.conf.js | karma.conf.js | module.exports = function (config) {
var customLaunchers = require('./test/browsers');
var configuration = {
frameworks: ['mocha', 'chai'],
files: [
'node_modules/jquery/dist/jquery.js',
'node_modules/lodash/lodash.js',
'node_modules/backbone/backbone.js',
'node_modules/idb-wrapper/idbstore.js',
'dist/backbone-indexeddb.js',
'test/spec.js'
],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
reporters: ['mocha', 'saucelabs'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-mocha-reporter',
'karma-sauce-launcher'
],
sauceLabs: {
testName: 'Unit Tests',
connectOptions: {
logfile: 'sauce_connect.log'
},
},
captureTimeout: 120000,
customLaunchers: customLaunchers,
client: {
captureConsole: true,
mocha: {
bail: true
}
}
};
if (process.env.TRAVIS) {
configuration.browsers = Object.keys(customLaunchers);
configuration.singleRun = true;
}
config.set(configuration);
};
| JavaScript | 0.000002 | @@ -709,24 +709,44 @@
tOptions: %7B%0A
+ port: 5757,%0A
logf
|
326dd582bf5851bbea076fb087198d8c4291b076 | fix the karma refernce to the old define.debug file | karma.conf.js | karma.conf.js | // Karma configuration file
//
// For all available config options and default values, see:
// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54
module.exports = function (config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: [
'mocha'
],
// list of files / patterns to load in the browser
files: [
'bower_components/chai/chai.js',
'define.debug.js',
'test/define.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress', 'junit', 'teamcity'
// CLI --reporters progress
reporters: ['dots'],
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// start these browsers
// CLI --browsers Chrome,Firefox,Safari
browsers: [
'Chrome',
'Firefox',
'PhantomJS'
],
// if browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
plugins: [
'karma-mocha',
'karma-requirejs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-safari-launcher',
'karma-phantomjs-launcher'
]
});
};
| JavaScript | 0.000202 | @@ -475,14 +475,8 @@
ine.
-debug.
js',
|
70b286a7a471ad5b3f3edc29d4409e488c36003a | fix nested test assertion | test/test.js | test/test.js | var path = require('path');
var assert = require('assert');
var glob = require('glob');
var exec = require('child_process').exec;
var npmLinkCheck = require('../index.js');
var CMD = 'node ' + path.join(__dirname, '..', 'cmd.js') + ' ';
var DELAY = 1000;
describe('simple project', function() {
var makeProject = require('./cases/project_simple');
var pathToProject = path.join(__dirname, 'build', 'project_simple');
var pkgList = [];
var foundPathList = [];
function cb(pkgName, foundPath) {
pkgList.push(pkgName);
foundPathList.push(foundPath);
}
before(function(done) {
makeProject();
npmLinkCheck(pathToProject, cb);
setTimeout(done, DELAY);
});
it('should have 2 linked module detected', function() {
assert.equal(pkgList.length, 2);
});
it('should have 2 linked paths detected', function() {
assert.equal(foundPathList.length, 2);
});
it('should list the linked module names', function() {
['module4', 'module5'].forEach(function(moduleName) {
assert.ok(pkgList.indexOf(moduleName) !== -1);
});
});
it('should list the linked paths', function() {
['module4', 'module5'].forEach(function(moduleName) {
var pathToModule = path.join(pathToProject, 'node_modules', moduleName);
assert.ok(foundPathList.indexOf(pathToModule) !== -1);
});
});
});
describe('nested project', function() {
var makeProject = require('./cases/project_nested');
var pathToProject = path.join(__dirname, 'build', 'project_nested');
var pkgList = [];
var foundPathList = [];
function cb(pkgName, foundPath) {
pkgList.push(pkgName);
foundPathList.push(foundPath);
}
before(function(done) {
makeProject();
npmLinkCheck(pathToProject, cb);
setTimeout(done, DELAY);
});
it('should have 3 linked module detected', function() {
assert.equal(pkgList.length, 3);
});
it('should have 3 linked paths detected', function() {
assert.equal(foundPathList.length, 3);
});
it('should list the linked module names', function() {
['module1111', 'module23', 'module3'].forEach(function(moduleName) {
assert.ok(pkgList.indexOf(moduleName) !== -1);
});
});
it('should list the linked paths', function(done) {
['module1111', 'module23', 'module3'].forEach(function(moduleName) {
glob(pathToProject + '/**/' + 'module1111', function(err, files) {
if(err) throw err;
var pathToModule = files[0];
assert.ok(foundPathList.indexOf(pathToModule) !== -1);
});
});
setTimeout(done, DELAY);
});
});
describe('clean project', function() {
var makeProject = require('./cases/project_clean');
var pathToProject = path.join(__dirname, 'build', 'project_clean');
var pkgList = [];
var foundPathList = [];
function cb(pkgName, foundPath) {
pkgList.push(pkgName);
foundPathList.push(foundPath);
}
before(function(done) {
makeProject();
npmLinkCheck(pathToProject, cb);
setTimeout(done, DELAY);
});
it('should have 0 linked module detected', function() {
assert.equal(pkgList.length, 0);
});
it('should have 0 linked paths detected', function() {
assert.equal(foundPathList.length, 0);
});
it('should not make cmd.js throw an error', function(done) {
exec(CMD + pathToProject, function(err) {
assert.equal(err, null);
done();
});
});
});
describe('error handling', function() {
it('should throw an error when targeted project does not have a node_modules folder', function(done) {
exec(CMD + 'build/', function(err, stdout, stderr) {
assert.ok(/build\/ does not have a node_modules folder./.test(stderr));
done();
});
});
});
| JavaScript | 0.000015 | @@ -2529,28 +2529,26 @@
/**/' +
-'
module
-1111'
+Name
, functi
|
386f876d49f3a89a09aef5b318ea9dafffc083f6 | add karma for all browsers | karma.conf.js | karma.conf.js | 'use strict';
/**
* Module dependencies.
*/
var applicationConfiguration = require('./config/config');
// Karma configuration
module.exports = function(config) {
config.set({
// Frameworks to use
frameworks: ['jasmine'],
// List of files / patterns to load in the browser
files: applicationConfiguration.assets.lib.js.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests),
// Test results reporter to use
// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
//reporters: ['progress'],
reporters: ['progress'],
// Web server port
port: 9876,
// Enable / disable colors in the output (reporters and logs)
colors: true,
// Level of logging
// Possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// Enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// If true, it capture browsers, run tests and exit
singleRun: true
});
}; | JavaScript | 0 | @@ -1152,16 +1152,43 @@
sers: %5B'
+Chrome', 'Firefox' , 'IE','
PhantomJ
|
3f9c17f1556af64e476b90234197073ee0885cfb | Update test.js | test/test.js | test/test.js | /*
* BotFather
* Copyright(c) 2016 Aleki
* MIT Licensed
*/
'use strict';
const TOKEN = process.env.TOKEN;
const BotFather = require('../index.js');
const bf = new BotFather(TOKEN);
bf.api('getMe')
.then((json) => {
if(json.ok) {
const bot = json.result;
console.info(`All right! Your @${bot.username} ready for use :)`);
} else {
console.error(json.description);
}
})
.catch((reason) => {
console.error(reason);
}); | JavaScript | 0.000001 | @@ -412,20 +412,23 @@
.catch((
-reas
+excepti
on) =%3E %7B
@@ -450,14 +450,23 @@
ror(
-reason
+exception.stack
);%0A
|
b1fc2079a01037e0d948a8ba85bb088440205fe7 | create object should return object with default domain | test/test.js | test/test.js | var assert = require('assert');
describe('NIS', function() {
describe('require', function() {
it('should return object', function() {
var nis = require('../build/Release/nis');
assert.equal('object', typeof(nis));
})
})
});
| JavaScript | 0.000011 | @@ -24,16 +24,96 @@
ssert');
+%0Avar nis = require('../build/Release/nis');%0Aassert.equal('object', typeof(nis));
%0A%0Adescri
@@ -149,23 +149,29 @@
scribe('
+c
re
-quire
+ate object
', funct
@@ -206,24 +206,44 @@
eturn object
+ with default domain
', function(
@@ -266,44 +266,17 @@
var
-nis = require('../build/Release/nis'
+yp = nis(
);%0A
@@ -312,27 +312,26 @@
ct', typeof(
-nis
+yp
));%0A
|
c76463b8b9818788376f93f8f51ea6434bada420 | update karma config | karma.conf.js | karma.conf.js | // Karma configuration
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: './',
// frameworks to use
frameworks: ['jasmine', 'systemjs'],
// list of files / patterns to load in the browser
files: [],
systemjs: {
configFile: 'system.config.js',
// File patterns for your application code, dependencies, and test suites
files: [
'bower_components/**/*',
'./*.js'
],
config: {
baseURL: '/',
transpiler: null
}
},
// list of files to exclude
exclude: [
'bower_components/**/*.spec.js'
],
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'block.js': ['coverage']
},
coverageReporter: {
type : 'lcovonly',
dir : 'reporters',
subdir : '.'
},
junitReporter: {
outputFile: 'reporters/junit.xml'
},
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
| JavaScript | 0 | @@ -774,17 +774,17 @@
nts/**/*
-.
+_
spec.js'
|
b8b8f147d1a1ebbc1ea07c4eb55b5716f39b2833 | fix karma.conf.js | karma.conf.js | karma.conf.js | module.exports = function(config) {
var webdriverConfig = {
hostname: 'fe.nhnent.com',
port: 4444,
remoteHost: true
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
// karma runner 의 웹 서버 root를 변경할 수 있음
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
reporters: [
'dots',
'coverage',
'junit'
],
/*
karma runner 의 웹 서버에 포함될 파일들을 적어주세요.
included: false 가 아닌 항목은 전부 자동으로 테스트 페이지에 include 됩니다.
테스트 코드 파일들은 전부 포함되어야 합니다.
files: [
'lib/jquery/jquery.js', // JS 추가
'src/css/test.css', // CSS 추가
{ pattern: 'test/app/model/*.test.js', included: false } // 웹서버에 포함은 하지만 테스트 페이지에 include안함
{ pattern: 'test/fixtures/*.html', included: false } // 웹서버에 올라가지만 jasmine.loadFixture 로 쓸것이므로 include안함.
]
*/
files: [
'bower_components/jquery/jquery.js',
'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
'src/common/*.js',
'src/js/datepicker.js',
'src/js/calendar.js',
'src/js/calendarUtil.js',
'test/*.js',
{
pattern: 'test/fixture/**/*.html',
included: false
},
{
pattern: 'test/css/**/*.css',
included: false
}
],
/*
무시할 파일들
특정 테스트를 제외하고 수행할 때 유용합니다.
*/
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/js/*.js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
coverageReporter: {
dir : 'report/coverage/',
reporters: [
{
type: 'html',
subdir: function(browser) {
return 'report-html/' + browser;
}
},
{
type: 'cobertura',
subdir: function(browser) {
return 'report-cobertura/' + browser;
},
file: 'cobertura.txt'
}
]
},
junitReporter: {
outputFile: 'report/junit-result.xml',
suite: ''
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [
'IE7',
'IE8',
'IE9',
'IE10',
'IE11',
'Chrome-WebDriver',
'Firefox-WebDriver'
],
/*
사용가능한 테스트 브라우저 목록
추가를 원하시면 말씀주세요
*/
customLaunchers: {
'IE7': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'IE7'
},
'IE8': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'IE8'
},
'IE9': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'IE9'
},
'IE10': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'IE10'
},
'IE11': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'IE11'
},
'Chrome-WebDriver': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'chrome'
},
'Firefox-WebDriver': {
base: 'WebDriver',
config: webdriverConfig,
browserName: 'firefox'
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
}; | JavaScript | 0.000755 | @@ -1118,31 +1118,40 @@
ents/jquery/
+dist/
jquery.
+min.
js',%0A
@@ -1243,44 +1243,8 @@
s',%0A
- 'src/js/datepicker.js',%0A
|
52b0b84ce4e897af7822ddb0ed74db6feaa9ff2c | Add negative tie test case | test/test.js | test/test.js | 'use strict';
// MODULES //
var test = require( 'tape' );
var round = require( './../lib' );
// TESTS //
test( 'main export is a function', function test( t ) {
t.ok( typeof round === 'function', 'main export is a function' );
t.end();
});
test( 'the function rounds a numeric value to the nearest integer', function test( t ) {
t.equal( round( -4.2 ), -4, 'equals -4' );
t.equal( round( 4.2 ), 4, 'equals 4' );
t.equal( round( 9.99999 ), 10, 'equals 10' );
t.equal( round( 9.5 ), 10, 'equals 10' );
t.equal( round( 9.4 ), 9, 'equals 10' );
t.equal( round( 0 ), 0, 'equals 0' );
t.end();
});
test( 'the function returns `NaN` if provided a `NaN`', function test( t ) {
var val = round( NaN );
t.ok( val !== val, 'returns NaN' );
t.end();
});
test( 'the function returns `+infinity` if provided a `+infinity`', function test( t ) {
var val = round( Number.POSITIVE_INFINITY );
t.equal( val, Number.POSITIVE_INFINITY, 'returns +infinity' );
t.end();
});
test( 'the function returns `-infinity` if provided a `-infinity`', function test( t ) {
var val = round( Number.NEGATIVE_INFINITY );
t.equal( val, Number.NEGATIVE_INFINITY, 'returns -infinity' );
t.end();
});
| JavaScript | 0.99983 | @@ -370,24 +370,68 @@
uals -4' );%0A
+%09t.equal( round( -4.5 ), -4, 'equals -4' );%0A
%09t.equal( ro
|
e08418021e8e73385c7d9c5336f8ebd9567a41e1 | test that the processes can be restarted more than once | test/test.js | test/test.js | var fs = require('fs')
, child = require('child_process')
, expect = require('expect.js')
var dir = __dirname + '/fixture'
, bin = __dirname + '/../bin/node-dev'
, msgFile = dir + '/message.js'
, msg = 'module.exports = "Please touch message.js now"\n'
function touch() {
fs.writeFileSync(msgFile, msg)
}
function spawn(cmd, cb) {
var ps = child.spawn('node', [bin].concat(cmd.split(' ')), { cwd: dir })
, out = ''
if (cb) ps.stdout.on('data', function(data) {
out += data.toString()
var ret = cb.call(ps, out)
if (typeof ret == 'function') cb = ret
else if (ret && ret.exit) {
ps.stdout.removeAllListeners('data')
ps.on('exit', function() { setTimeout(ret.exit, 1000) })
ps.kill()
}
})
return ps
}
function run(cmd, done) {
spawn(cmd, function(out) {
if (out.match(/touch message.js/)) {
setTimeout(touch, 500)
return function(out) {
if (out.match(/Restarting/)) {
return { exit: done }
}
}
}
})
}
describe('node-dev', function() {
it('should restart the server', function(done) {
run('server.js', done)
})
it('should restart the cluster', function(done) {
run('cluster.js', done)
})
it('should support vm functions', function(done) {
run('vmtest.js', done)
})
it('should support coffee-script', function(done) {
run('server.coffee', done)
})
it('should restart when a file is renamed', function(done) {
var tmp = dir + '/message.tmp'
fs.writeFileSync(tmp, msg)
spawn('log.js', function(out) {
if (out.match(/touch message.js/)) {
fs.renameSync(tmp, msgFile)
return function(out) {
if (out.match(/Restarting/)) {
return { exit: done }
}
}
}
})
})
it('should handle errors', function(done) {
spawn('error.js', function(out) {
if (out.match(/ERROR/)) {
setTimeout(touch, 500)
return function(out) {
if (out.match(/Restarting/)) {
return { exit: done }
}
}
}
})
})
it('should watch if no such module', function(done) {
spawn('noSuchModule.js', function(out) {
expect(out).to.match(/ERROR/)
return { exit: done }
})
})
it('should ignore caught errors', function(done) {
spawn('catchNoSuchModule.js', function(out) {
expect(out).to.match(/Caught/)
return { exit: done }
})
})
it('should not show up in argv', function(done) {
spawn('argv.js foo', function(out) {
var argv = JSON.parse(out.replace(/'/g, '"'))
expect(argv[0]).to.match(/.*?node(\.exe)?$/)
expect(argv[1]).to.equal('argv.js')
expect(argv[2]).to.equal('foo')
return { exit: done }
})
})
it('should pass through the exit code', function(done) {
spawn('exit.js').on('exit', function(code) {
expect(code).to.be(101)
done()
})
})
it('should conceil the wrapper', function(done) {
// require.main should be main.js not wrap.js!
spawn('main.js').on('exit', function(code) {
expect(code).to.be(0)
done()
})
})
it('should relay stdin', function(done) {
spawn('echo.js', function(out) {
expect(out).to.equal('foo')
return { exit: done }
}).stdin.write('foo')
})
it('should kill the forked processes', function(done) {
spawn('pid.js', function(out) {
var pid = parseInt(out, 10)
this.on('exit', function() {
setTimeout(function() {
try {
process.kill(pid)
done('child must no longer run')
}
catch(e) {
done()
}
}, 500)
})
return { exit: done }
})
})
})
| JavaScript | 0 | @@ -1129,32 +1129,500 @@
s', done)%0A %7D)%0A%0A
+ it('should restart the server twice', function(done) %7B%0A spawn('server.js', function(out) %7B%0A if (out.match(/touch message.js/)) %7B%0A setTimeout(touch, 500)%0A return function(out) %7B%0A if (out.match(/Restarting/)) %7B%0A setTimeout(touch, 500)%0A return function(out) %7B%0A if (out.match(/Restarting/)) %7B%0A return %7B exit: done %7D%0A %7D%0A %7D%0A %7D%0A %7D%0A %7D%0A %7D)%0A %7D)%0A%0A
it('should res
|
7a93ca1b367ef5c2150e00531a2dae5584b8d74a | Fix reference | test/test.js | test/test.js | 'use strict'
var test = require('ava')
var eslint = require('eslint')
var extend = require('extend')
var path = require('path')
var tempWrite = require('temp-write')
var configs = {default: require('../default')}
configs.browser = extend(true, {}, configs.default, require('../browser'))
configs.esnext = extend(true, {}, configs.default, require('../esnext'))
configs.babel = extend(true, {}, configs.esnext, require('../babel'))
test(function testDefault(t) {
var result = lint('default.js', configs.default)
t.is(result.warningCount, 0)
t.is(result.errorCount, 0)
t.end()
})
test(function testBadDefault(t) {
var result = lint('default-bad.js', configs.default)
var rules = getRules(result)
t.is(result.warningCount, 1)
t.is(result.errorCount, 3)
t.same(rules, [
'no-mixed-requires',
'no-process-exit',
'no-unused-vars',
'one-var',
])
t.end()
})
test(function testBrowser(t) {
var result = lint('browser.js', configs.browser)
t.is(result.warningCount, 0)
t.is(result.errorCount, 0)
t.end()
})
test(function testBadBrowser(t) {
var result = lint('browser-bad.js', configs.browser)
var rules = getRules(result)
t.is(result.warningCount, 0)
t.is(result.errorCount, 4)
t.same(rules, [
'no-process-env',
'no-undef',
'no-undef',
'no-undef',
])
t.end()
})
test(function testESNext(t) {
var result = lint('esnext.js', configs.esnext)
t.is(result.warningCount, 0)
t.is(result.errorCount, 0)
t.end()
})
test(function testBadESNext(t) {
var result = lint('esnext-bad.js', configs.esnext)
var rules = getRules(result)
t.is(result.warningCount, 1)
t.is(result.errorCount, 4)
t.same(rules, [
'func-names',
'no-process-exit',
'no-unused-vars',
'no-var',
'prefer-arrow-callback',
])
t.end()
})
test(function testBabel(t) {
var result = lint('esnext.js', configs.babel)
t.is(result.warningCount, 0)
t.is(result.errorCount, 0)
t.end()
})
test(function testBadBabel(t) {
var result = lint('esnext-bad.js', configs.babel)
var rules = getRules(result)
t.is(result.warningCount, 1)
t.is(result.errorCount, 4)
t.same(rules, [
'func-names',
'no-process-exit',
'no-unused-vars',
'no-var',
'prefer-arrow-callback',
])
t.end()
})
function lint(fixture, config) {
var fixtureFile = path.join(__dirname, 'fixtures', fixture)
var linter = new eslint.CLIEngine({
useEslintrc: false,
configFile: tempWrite.sync(JSON.stringify(config)),
})
return linter.executeOnFiles([fixtureFile]).results[0]
}
function getRules(result) {
return result.messages
.map(function(message) { return message.ruleId })
.sort()
}
| JavaScript | 0.000002 | @@ -199,16 +199,8 @@
('..
-/default
')%7D%0A
|
a18885b995ec0ac6fecc62fe4ca319cdbff4f407 | .catch(done.fail), not .catch(done) | test/test.js | test/test.js | var expect = require('chai').expect;
var rollup = require('..');
var Readable = require('stream').Readable;
var hypothetical = require('rollup-plugin-hypothetical');
function collect(stream) {
return new Promise(function(resolve, reject) {
var data = '';
stream.on('end', function() {
resolve(data);
});
stream.on('error', function(err) {
reject(err);
});
stream.on('data', function(chunk) {
data += chunk.toString();
});
});
}
describe("rollup-stream", function() {
it("should export a function", function() {
expect(rollup).to.be.a('function');
});
it("should return a readable stream", function() {
expect(rollup()).to.be.an.instanceof(Readable);
});
it("should emit an error if options isn't passed", function(done) {
var s = rollup();
s.on('error', function(err) {
expect(err.message).to.equal("options must be an object or a string!");
done();
});
s.on('data', function() {
done(Error("No error was emitted."));
});
});
it("should emit an error if options.entry isn't present", function(done) {
var s = rollup({});
s.on('error', function(err) {
expect(err.message).to.equal("You must supply options.entry to rollup");
done();
});
s.on('data', function() {
done(Error("No error was emitted."));
});
});
it("should take a snapshot of options when the function is called", function() {
var options = {
entry: './entry.js',
format: 'es',
plugins: [hypothetical({
files: {
'./entry.js': 'import x from "./x.js"; console.log(x);',
'./x.js': 'export default "Hello, World!";'
}
})]
};
var s = rollup(options);
options.entry = './nonexistent.js';
return collect(s).then(function(data) {
expect(data).to.have.string('Hello, World!');
});
});
it("should use a custom Rollup if options.rollup is passed", function() {
var options = {
rollup: {
rollup: function(options) {
expect(options).to.equal(options);
return Promise.resolve({
generate: function(options) {
expect(options).to.equal(options);
return Promise.resolve({ code: 'fake code' });
}
});
}
}
};
return collect(rollup(options)).then(function(data) {
expect(data).to.equal('fake code');
});
});
it("shouldn't raise an alarm when options.rollup is passed", function() {
return collect(rollup({
entry: './entry.js',
format: 'es',
rollup: require('rollup'),
plugins: [{
resolveId: function(id) {
return id;
},
load: function() {
return 'console.log("Hello, World!");';
}
}]
})).then(function(data) {
expect(data).to.have.string('Hello, World!');
});
});
it("should import config from the specified file if options is a string", function() {
return collect(rollup('test/fixtures/config.js')).then(function(data) {
expect(data).to.have.string('Hello, World!');
});
});
it("should reject with any error thrown by the config file", function(done) {
var s = rollup('test/fixtures/throws.js');
s.on('error', function(err) {
expect(err.message).to.include("bah! humbug");
done();
});
s.on('data', function() {
done(Error("No error was emitted."));
});
});
it("should emit a 'bundle' event when the bundle is output", function(done) {
var s = rollup({
entry: './entry.js',
format: 'es',
plugins: [{
resolveId: function(id) {
return id;
},
load: function() {
return 'console.log("Hello, World!");';
}
}]
});
var bundled = false;
s.on('bundle', function(bundle) {
bundled = true;
bundle.generate({ format: 'es' }).then(function(result) {
if(/Hello, World!/.test(result.code)) {
done();
} else {
done(Error("The bundle doesn't contain the string \"Hello, World!\""));
}
}).catch(done);
});
s.on('error', function(err) {
done(Error(err));
});
s.on('data', function() {
if(!bundled) {
done(Error("No 'bundle' event was emitted."));
}
});
});
});
describe("sourcemaps", function() {
it("should be added when options.sourceMap is true", function() {
return collect(rollup({
entry: './entry.js',
format: 'es',
sourceMap: true,
plugins: [{
resolveId: function(id) {
return id;
},
load: function() {
return 'console.log("Hello, World!");';
}
}]
})).then(function(data) {
expect(data).to.have.string('\n//# sourceMappingURL=data:application/json;');
});
});
it("should not be added otherwise", function() {
return collect(rollup({
entry: './entry.js',
format: 'es',
plugins: [{
resolveId: function(id) {
return id;
},
load: function() {
return 'console.log("Hello, World!");';
}
}]
})).then(function(data) {
expect(data).to.not.have.string('//# sourceMappingURL=');
});
});
});
| JavaScript | 0.999996 | @@ -4147,16 +4147,21 @@
tch(done
+.fail
);%0A %7D
|
1a51a406c3fc28bcc0cbcd42a691a0727974811f | Fix `Customers` test | test/test.js | test/test.js | 'use strict';
var auth = require('./auth.json');
var expect = require('chai').expect;
var should = require('chai').should();
var sap = require('../index')(auth);
describe('Access Token', function() {
this.timeout(30000);
it('Should create authentication token', function(done) {
setTimeout(function() {
should.exist(sap.access_token);
done();
}, 1000)
});
});
describe('Customers', function() {
it('Should get all Customers', function(done) {
sap.getCustomers(function(err, res, body) {
expect(body.length).to.not.equal(0);
})
});
});
| JavaScript | 0.000304 | @@ -196,18 +196,16 @@
ion() %7B%0A
-
this.t
@@ -220,18 +220,16 @@
0000);%0A%0A
-
it('Sh
@@ -276,28 +276,24 @@
ion(done) %7B%0A
-
setTimeo
@@ -314,22 +314,16 @@
%7B%0A
-
-
should.e
@@ -346,22 +346,16 @@
token);%0A
-
do
@@ -360,20 +360,16 @@
done();%0A
-
%7D, 1
@@ -377,16 +377,13 @@
00)%0A
-
%7D);
-
%0A%7D);
@@ -419,18 +419,16 @@
ion() %7B%0A
-
it('Sh
@@ -465,28 +465,24 @@
ion(done) %7B%0A
-
sap.getC
@@ -517,22 +517,16 @@
body) %7B%0A
-
ex
@@ -568,17 +568,25 @@
+ done();%0A
%7D)%0A
-
%7D)
|
ef0c8ed18ecbaeea8d5610798ae84b2070c5b1fb | Make event proxy test more robust | test/test.js | test/test.js | require('chai').should();
var Person = require('./models/person');
var describe = global.describe;
var it = global.it;
describe('People', function () {
var mom = new Person({id: 1});
var dad = new Person({id: 2});
var childA = new Person({id: 3});
var childB = new Person({id: 4});
var childC = new Person({id: 5});
var rockstar = new Person({id: 6, name: 'Elvis'});
mom.set({childJoins: [{child: childA}, {child: childB}]});
dad.set('childJoins', [{child: childB}, {child: childC}]);
childA.set('friendships', [{friender: childB}, {friender: childC}]);
mom.set('idol', rockstar);
rockstar.set('fans', childA);
it('sets children', function () {
mom.resolve('children').include(childA).should.be.ok;
mom.resolve('children').include(childB).should.be.ok;
dad.resolve('children').include(childB).should.be.ok;
dad.resolve('children').include(childC).should.be.ok;
});
it('sets friends', function () {
childA.resolve('friends').models.should.include(childB, childC);
});
it('always has a default hasOne', function () {
(new Person()).get('idol').should.be.ok;
});
it('sets idol', function () {
mom.get('idol').should.equal(rockstar);
childA.get('idol').id.should.equal(rockstar.id);
});
it('sets fans', function () {
rockstar.get('fans').include(childA).should.be.ok;
});
it('updates ids', function () {
rockstar.set('id', 7);
childA.get('idolId').should.equal(7);
mom.get('idolId').should.equal(7);
});
it('ditchs old instances', function () {
mom.set('idolId', 6);
mom.get('idol').id.should.equal(6);
});
it('does not mutate objects passed to set', function () {
var obj = {idol: rockstar};
mom.set(obj);
obj.should.have.property('idol');
});
it('does not hold on to old reverse relations', function () {
mom.resolve('children').models.should.include(childA)
.and.not.include(childC);
childA.resolve('parents').models.should.include(mom);
childC.resolve('parents').models.should.not.include(mom);
mom.get('childJoins').findWhere({childId: childA.id}).set('child', childC);
mom.resolve('children').models.should.include(childC)
.and.not.include(childA);
childA.resolve('parents').models.should.not.include(mom);
childC.resolve('parents').models.should.include(mom);
});
it('does not wipe out a model with null is passed', function () {
var person = new Person();
person.get('idol').should.not.be.falsey;
person.set('idol', null);
person.get('idol').should.not.be.falsey;
});
it('does not set a 1 element collection when null is passed', function () {
var person = new Person();
person.get('children').should.have.length(0);
person.set('children', null);
person.get('children').should.have.length(0);
});
it('allows url to be passed as an option', function () {
(new Person()).get('friends').url.should.equal('this-is-a-test-url');
});
it('follows deeply nested relation setters', function () {
(new Person({
friends: [{
idol: {
manager: {
name: 'Jerry'
}
}
}]
})).get('friends').first().get('idol').get('manager').get('name')
.should.equal('Jerry');
});
it('proxies change events', function () {
var a = new Person();
var b = new Person();
a.set('idol', b);
b.set('idol', a);
var calls = 0;
a.on('change:idol', function (model) {
model.should.equal(b);
++calls;
});
a.on('change:idol:name', function (model, val) {
model.should.equal(b);
val.should.equal('Billy');
++calls;
});
b.set('name', 'Billy');
calls.should.equal(2);
});
});
| JavaScript | 0.000029 | @@ -3348,24 +3348,50 @@
w Person();%0A
+ var c = new Person();%0A
a.set('i
@@ -3430,21 +3430,146 @@
-var calls = 0
+b.set('manager', c);%0A var calls = 0;%0A b.once('change:manager', function (model) %7B%0A model.should.equal(c);%0A ++calls;%0A %7D)
;%0A
@@ -3566,32 +3566,34 @@
%7D);%0A a.on
+ce
('change:idol',
@@ -3585,24 +3585,32 @@
'change:idol
+:manager
', function
@@ -3636,33 +3636,176 @@
el.should.equal(
-b
+c);%0A ++calls;%0A %7D);%0A b.once('change:manager:name', function (model, val) %7B%0A model.should.equal(c);%0A val.should.equal('Billy'
);%0A ++calls
@@ -3822,16 +3822,18 @@
a.on
+ce
('change
@@ -3838,16 +3838,24 @@
ge:idol:
+manager:
name', f
@@ -3902,17 +3902,17 @@
d.equal(
-b
+c
);%0A
@@ -3962,25 +3962,25 @@
%7D);%0A
-b
+c
.set('name',
@@ -4013,17 +4013,17 @@
d.equal(
-2
+4
);%0A %7D);
|
8b8362369fe48144b4e1742f185f8a75155f7d2c | Fix logging message when errors are thrown in tests | test/test.js | test/test.js | const chalk = require('chalk');
const basicTests = require('./basicTests.js');
const docTests = require('./docTests.js');
const selectorTests = require('./selectorTests.js');
const tests = [
...basicTests,
...docTests,
...selectorTests
];
let totalTests = 0;
let numPassed = 0;
let index = 0;
(async () => {
while (tests.length > 0) {
let testFunc = tests.shift();
index += 1;
let testResults;
try {
testResults = await testFunc();
} catch (err) {
testResults = [{
passed: false,
result: {
name: 'Error thrown in test ' + index,
details: JSON.stringify(err, null, 2)
}
}];
}
totalTests += testResults.length;
numPassed += testResults.reduce((subCount, subTest, subIndex) => {
let testName = subTest.name || 'Test ' + index + '.' + subIndex;
let mainMessage = subTest.result.passed ? chalk`{bold.hex('#666666') Passed ${testName}}` : chalk`{bold.hex('#e7298a') Failed ${testName}}`;
console.log(mainMessage);
if (subTest.result.details) {
console.log('Details:\n' + subTest.result.details);
}
console.log('');
return subTest.result.passed ? subCount + 1 : subCount;
}, 0);
}
if (numPassed === totalTests) {
console.log(chalk`{bold.hex('#666666') Passed ${numPassed} out of ${totalTests} tests\n\n}`);
process.exit(0);
} else {
console.error(chalk`{bold.hex('#e7298a') Failed ${totalTests - numPassed} of ${totalTests} tests\n\n}`);
process.exit(1);
}
})();
| JavaScript | 0.000004 | @@ -511,88 +511,86 @@
-passed: false,%0A result: %7B%0A name: 'Error thrown in test ' + index
+name: %60test $%7Bindex%7D; error thrown%60,%0A result: %7B%0A passed: false
,%0A
|
2ef20cf19635fe056e8690b2204f05e3b0ee4c62 | update test files | test/test.js | test/test.js | var stream = require("stream");
var router = require("../");
router.setMap({
"/my/**/*":"func:testFun",
"index":"url:index.html",
"test?v=*":"url:my*.html",
"nihao/**/ho*eo":"url:**/*.html",
"/public/bi*/**/*":"url:public/**/*"
});
router.on("notmatch" , function(){
console.log('not match');
});
router.on("path" , function(path , requestpath){
console.log("请求路径:"+requestpath);
console.log("路由转换: "+path);
});
router.on("error" , function(err){
console.log(err);
});
router.set("testFun" , function(req , res , requestpath){
console.log("请求路径:" + requestpath);
console.log("执行方法:testFun");
});
describe("check" , function(){
it("test1" , function(done){
test("/public/biz009/stylesheets/css/man.css");
done();
});
it("test2" , function(done){
test("/my/1/2/3/4/abs.html?v=22");
done();
});
it("test3" , function(done){
test("/index");
done();
});
it("test4" , function(done){
test("/test?v=index");
done();
});
it("test5" , function(done){
test("/nihao/asd/asd/asd/homemeeo");
done();
});
});
function test(url){
var res = new stream.Writable();
res.writeHead = function(){};
res._write = function(chunk , enc , done){
done();
};
var req = {
url:url,
headers:{
'accept-encoding':''
}
};
router.route(req , res);
} | JavaScript | 0 | @@ -116,20 +116,16 @@
index%22:%22
-url:
index.ht
@@ -146,20 +146,16 @@
t?v=*%22:%22
-url:
my*.html
@@ -180,20 +180,16 @@
ho*eo%22:%22
-url:
**/*.htm
@@ -217,20 +217,16 @@
/**/*%22:%22
-url:
public/*
|
baf897d1fdc004a45ba46fbf2f75e305291611c0 | fix standard complaints | examples/js/components/headerRoute.js | examples/js/components/headerRoute.js |
import React from 'react'
import Playground from 'component-playground'
import {Header, Icon} from '../../../'
const defaultHeader =
`
<Header title='title' subtitle='subtitle' />
`
const headerWithColorAndChildren =
`
<Header title='title' subtitle='subtitle' className='custom'>
<Icon.Button>
<Icon.Search fill='#fff' />
</Icon.Button>
<Icon.Button>
<Icon.Person fill='#fff' />
</Icon.Button>
<Icon.Button>
<Icon.Language fill='#fff' />
</Icon.Button>
</Header>
`
export default class HeaderRoute extends React.Component {
render () {
return (
<div className='HeaderRoute'>
<section>
<h2>Header component</h2>
<p>
The header component content has some left margin on large screens. It allows the navigation component to be on top of the header without hiding content. On smaller screens the margin is gone and just enough space is left to show the hamburger button.
</p>
<Playground
docClass={Header}
codeText={defaultHeader}
scope={{React, Header}}
collapsableCode
/>
</section>
<section>
<h2>Advanced header</h2>
<p>
The advanced header has a custom CSS class name. It allows setting custom background and font colors. It also has some buttons with icons on the right side of the header.
</p>
<Playground
codeText={headerWithColorAndChildren}
scope={{React, Header, Icon}}
collapsableCode
/>
</section>
<section>
<p>Specification</p>
<a href='http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing'>
http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing
</a>
</section>
</div>
)
}
}
| JavaScript | 0.000006 | @@ -211,17 +211,16 @@
hildren
-
=%0A%60%0A%3CHea
|
379bc577c29a366fb81a6a4b7295bee7eb6656fd | correct error message | longlist.js | longlist.js | // longlist 2.0 - a minimalist javascript list pager
// Copyright 2011, 2012, 2013, 2014, 2015 Chris Forno
// Copyright 2016 Dennis Rohner
// Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
// Unsupported browsers:
// Internet Explorer <= 8
// Assumptions:
// * The list has a single <ul>.
(function () {
// Fire a custom event named "name" from element "element" with
// extra data "data" attached to the details of the event.
function customEvent(name, element, data) {
if (window.CustomEvent) {
var event = new CustomEvent(name, {detail: data});
} else {
var event = document.createEvent('CustomEvent');
event.initCustomEvent(name, true, true, data);
}
element.dispatchEvent(event);
}
window.longlist = function (parent, list, options) {
if (list.children.length === 0) throw new Error('longlist: Missing list <tbody>.');
// How many items per page should we display?
var perPage = options !== undefined && 'perPage' in options ? options.perPage : 10;
// Which page should we start on?
var startPage = options !== undefined && 'startPage' in options ? options.startPage : 1;
// What's the maximum number of on either side of the current page?
var maxLinks = options !== undefined && 'maxLinks' in options ? options.maxLinks : 9;
var currentPage = null;
var items = list.children;
var nPages = Math.max(1, Math.ceil(items.length / perPage));
var prev = document.createElement('a');
prev.className = 'page prev';
prev.setAttribute('href', '');
var next = document.createElement('a');
next.className = 'page next';
next.setAttribute('href', '');
var leftElipsis = document.createElement('span');
leftElipsis.className = 'elipsis';
var rightElipsis = document.createElement('span');
rightElipsis.className = 'elipsis';
var links = [];
for (var i = 1; i <= nPages; i++) {
var link = document.createElement('a');
link.className = 'page direct';
link.setAttribute('href', '');
link.textContent = i;
links.push(link);
}
var controls = document.createElement('div');
controls.className = 'paging-controls';
controls.appendChild(prev);
controls.appendChild(links[0]);
controls.appendChild(leftElipsis);
controls.appendChild(document.createTextNode(' '));
for (var i = 2; i < nPages; i++) {
controls.appendChild(links[i - 1]);
controls.appendChild(document.createTextNode(' '));
}
controls.appendChild(rightElipsis);
controls.appendChild(links[links.length - 1]);
controls.appendChild(next);
parent.appendChild(controls);
list.gotoPage = function (n) {
if (n < 1 || n > nPages) throw new RangeError('longlist: gotoPage number must be between 1 and ' + nPages);
// Hide or show the previous/next controls if we're moving to the first/last page.
prev.style.visibility = n === 1 ? 'hidden' : '';
next.style.visibility = n === nPages ? 'hidden' : '';
// Display up to maxLinks links.
var nLinksLeft = Math.min(n, maxLinks - Math.min(nPages - n, Math.floor(maxLinks / 2))) - 1;
var nLinksRight = Math.min(nPages - n, maxLinks - nLinksLeft - 1);
for (var i = 1; i <= links.length; i++) {
if (i === n) { // current page
links[i-1].style.display = '';
links[i-1].removeAttribute('href');
} else if (i === 1 || // Always show the first page number.
i === nPages || // Always show the last page number.
(i > n - nLinksLeft && i < n + nLinksRight)) {
links[i-1].setAttribute('href', '');
links[i-1].style.display = '';
} else {
links[i-1].style.display = 'none';
}
}
// Hide or show elipses based on how far away we are from the ends.
leftElipsis.style.display = n > nLinksLeft + 1 ? '' : 'none';
rightElipsis.style.display = n < nPages - nLinksRight ? '' : 'none';
if (currentPage !== null) { // Hide currently displayed items.
for (var i = (currentPage - 1) * perPage; i < Math.min(currentPage * perPage, items.length); i++) {
items[i].style.display = 'none';
}
} else { // Hide all items
for (var i = 0; i < items.length; i++) {
items[i].style.display = 'none';
}
}
// Display new items.
for (var i = (n - 1) * perPage; i < Math.min(n * perPage, items.length); i++) {
items[i].style.display = '';
}
currentPage = n;
customEvent('longlist.pageChange', list, {page: n});
};
controls.addEventListener('click', function (event) {
if (event.target.tagName === 'A') {
event.preventDefault();
if (event.target.className == 'page prev') {
list.gotoPage(currentPage - 1);
} else if (event.target.className == 'page next') {
list.gotoPage(currentPage + 1);
} else {
list.gotoPage(parseInt(event.target.textContent, 10));
}
}
});
list.gotoPage(startPage);
};
})();
| JavaScript | 0.000049 | @@ -901,16 +901,13 @@
ist
-%3Ctbody%3E.
+items
');%0A
|
3cde96ebb5a36f13efb779afc8157251a3750993 | Improve module naming tests | test/test.js | test/test.js | /*global describe:true, beforeEach:true, it:true */
var assert = require('assert');
var helpers = require('yeoman-generator').test;
var path = require('path');
describe('Generator test', function () {
var jsmodule;
beforeEach(function (cb) {
helpers.testDirectory(path.join(__dirname, './tmp'), function (err) {
if (err) cb(err);
cb();
});
});
describe('jsmodule:app', function () {
var jsmoduleBrowser;
beforeEach(function (cb) {
var deps = ['../../lib/generators/app'];
jsmodule = helpers.createGenerator('jsmodule:app', deps, ['myComponent']);
jsmodule.options['skip-install'] = true;
cb();
});
it('runs sucessfully', function () {
jsmodule.run();
});
it('creates expected files', function (cb) {
var expected = [
// dotfiles
'.gitignore',
'.jshintrc',
'.travis.yml',
// config files
'package.json',
// docs
'CHANGELOG.md',
'LICENSE.md',
'README.md',
// component
'myComponent.js',
// test
'test/test.js'
];
jsmodule.run([], function() {
helpers.assertFiles(expected);
cb();
});
});
});
describe('jsmodule:browser', function () {
var jsmoduleBrowser;
beforeEach(function (cb) {
var deps = ['../../lib/generators/browser'];
jsmoduleBrowser = helpers.createGenerator('jsmodule:browser', deps, ['myComponent']);
jsmoduleBrowser.options['skip-install'] = true;
cb();
});
it('runs sucessfully', function () {
jsmoduleBrowser.run();
});
it('creates expected files', function (cb) {
var expected = [
// dotfiles
'.gitignore',
'.jshintrc',
'.travis.yml',
// config files
'bower.json',
'karma.conf.js',
'package.json',
// docs
'CHANGELOG.md',
'LICENSE.md',
'README.md',
// component
'myComponent.js',
// test
'test/test.js'
];
jsmoduleBrowser.run([], function() {
helpers.assertFiles(expected);
cb();
});
});
});
});
| JavaScript | 0 | @@ -575,33 +575,34 @@
, deps, %5B'my
-Component
+-module.js
'%5D);%0A j
@@ -916,32 +916,33 @@
g files%0A
+%5B
'package.json',%0A
@@ -932,32 +932,59 @@
%5B'package.json',
+ /%22name%22: %22my-module.js%22/%5D,
%0A // docs
@@ -1080,32 +1080,48 @@
+%5B
'my
-Component.js'
+-module.js', /myModule%5C(%5C)/%5D
,%0A
@@ -1508,25 +1508,26 @@
ps, %5B'my
-Component
+-module.js
'%5D);%0A
@@ -1867,16 +1867,17 @@
+%5B
'bower.j
@@ -1877,24 +1877,51 @@
bower.json',
+ /%22name%22: %22my-module.js%22/%5D,
%0A 'ka
@@ -1917,16 +1917,17 @@
+%5B
'karma.c
@@ -1930,24 +1930,41 @@
ma.conf.js',
+ /my-module.js/%5D,
%0A 'pa
@@ -1960,16 +1960,17 @@
+%5B
'package
@@ -1976,16 +1976,43 @@
e.json',
+ /%22name%22: %22my-module.js%22/%5D,
%0A
@@ -2120,24 +2120,40 @@
+%5B
'my
-Component.js'
+-module.js', /myModule%5C(%5C)/%5D
,%0A
|
7649c2183d769f912149d7aba8dba0255de39aa1 | test render without options | test/test.js | test/test.js | 'use strict'
const toHTML = require('vdom-to-html')
const parse5 = require('parse5-utils')
const assert = require('assert')
const path = require('path')
const fs = require('fs')
const render = require('..')
function renderFixture(fixtureName, locals) {
const compiled = render(fixture(fixtureName), {
filename: path.join(__dirname, 'fixtures', fixtureName),
})
const fn = eval(`(${compiled})`)
const root = fn.call({class: 'asdf'}, locals)
const html = toHTML(root)
parse5.parse(html, true)
return html
}
describe('Render', function () {
it('should render a template', function () {
const html = renderFixture('item', {
item: {
id: '1234',
title: 'some title',
description: 'some description',
active: true,
}
})
assert(~html.indexOf('item active'))
assert(~html.indexOf('class="title"'))
assert(~html.indexOf('<h3'))
assert(~html.indexOf('</h3>'))
assert(~html.indexOf('some title'))
assert(~html.indexOf('some description'))
})
it('should beautify when option is set', function () {
const fn = render(fixture('item'), {pretty: true})
const lines = fn.split('\n')
assert(lines.length > 15)
assert(lines[lines.length - 1].trim() === '}')
})
it('should run while loops correctly', function () {
const html = renderFixture('while')
assert(html.match(/<div class=\"item\">/g).length === 5)
})
it('should insert included files', function () {
const html = renderFixture('include')
assert(html.includes('<p>Hello</p>'))
assert(html.includes('<div class="included-content">llamas!!!</div>'))
assert(html.includes('<p>world</p>'))
})
it('should insert extended files', function () {
const html = renderFixture('extends')
assert(html.includes('<div class="foo">'))
assert(html.includes('capybara'))
assert(html.includes('default content'))
})
describe('attributes', function () {
it('should add arbitrary attributes', function () {
const html = renderFixture('attributes')
assert(html.includes('required'))
assert(!html.includes('something'))
})
it('should add class attributes in array notation', function () {
let html = renderFixture('attributes')
assert(html.includes('1 2'))
html = renderFixture('attributes', {variable: 'meow'})
assert(html.includes('1 2 meow'))
})
it('should add class attributes in object notation', function () {
let html = renderFixture('attributes')
assert(html.includes('obj1'))
assert(!html.includes('obj2'))
html = renderFixture('attributes', {variable: 'doge'})
assert(html.includes('obj1'))
assert(html.includes('obj2'))
})
it('should combine class attributes in different notations gracefully', function () {
let html = renderFixture('attributes')
assert(html.includes('mixed'))
assert(html.includes('mixedArray1'))
assert(!html.includes('mixedObj1'))
html = renderFixture('attributes', {var2: 'doge'})
assert(html.includes('mixed'))
assert(html.includes('mixedArray1'))
assert(html.includes('mixedObj1'))
assert(html.includes('doge'))
})
})
describe('case statements', function () {
it('should not execute any cases when none match', function () {
const html = renderFixture('case')
assert(!html.includes('foo'))
assert(!html.includes('bar'))
})
it('should execute default when no others match', function () {
const html = renderFixture('case')
assert(html.includes('llama'))
})
it('should execute only one match', function () {
const html = renderFixture('case', {variable: 1})
assert(html.includes('span'))
assert(!html.includes('input'))
assert(!html.includes('textarea'))
})
it('should fall through from the first case in a chain', function () {
const html = renderFixture('case', {variable2: 'd'})
assert(html.includes('bar'))
assert(!html.includes('foo'))
})
it('should fall through from the middle case in a chain', function () {
const html = renderFixture('case', {variable2: 'e'})
assert(html.includes('bar'))
assert(!html.includes('foo'))
})
it('should fall through from the last case in a chain', function () {
const html = renderFixture('case', {variable2: 'f'})
assert(html.includes('bar'))
assert(!html.includes('foo'))
})
})
describe('code blocks', function() {
let html;
beforeEach(function () {
html = renderFixture('code')
})
it('should run unbuffered code correctly', function () {
assert(~html.indexOf('<div class="example bar">'))
})
it('should use locals when evaluating', function () {
html = renderFixture('code', {x: 0})
assert(~html.indexOf('<div class="baz">'))
html = renderFixture('code', {x: -1})
assert(!~html.indexOf('<div class="baz">'))
})
it('should output inline buffered code', function () {
assert(html.includes('<div class="inline-script"><div class="raw-inline">within another div'))
})
it('should output standalone buffered code', function () {
assert(html.includes('<div class="raw-buffered">raw so raw'))
})
it('should not output unbuffered code', function () {
assert(!html.includes('should not be output'))
})
})
})
function fixture(name) {
return fs.readFileSync(path.resolve(__dirname, 'fixtures/' + name + '.jade'), 'utf8')
}
| JavaScript | 0.000001 | @@ -553,16 +553,251 @@
on () %7B%0A
+ it('should render a template without options', function () %7B%0A const compiled = render(fixture('attributes'))%0A assert(compiled.includes('class1'))%0A assert(compiled.includes('foo'))%0A assert(compiled.includes('doge'))%0A %7D)%0A%0A
it('sh
|
5f779db54f0b46af58b064ba2925da387464fd6d | Add tests for point.distanceTo and rectangle.round | test/test.js | test/test.js | var test = require('tape');
var shapes = require('..');
var Point = shapes.Point;
var Rect = shapes.Rectangle;
var Circle = shapes.Circle;
var Square = shapes.Square;
test('Point constructor', function (t) {
t.plan(2);
var p = new Point(400,42);
t.equal(p.x,400);
t.equal(p.y,42);
});
test('Circle constructor', function (t) {
t.plan(1);
var c = new Circle(new Point(50,50),10);
t.equal(c.radius,10);
});
test('Rectangle constructor', function (t) {
t.plan(2);
var r = new Rect(new Point(44,66),32,45);
t.equal(r.width,32);
t.equal(r.height,45);
});
test('Point#moveBy', function (t) {
t.plan(4);
var p = new Point(144,333);
var p2 = p.moveBy(33,9);
t.equal(p2.x,177);
t.equal(p2.y,342);
var p3 = p2.moveBy(-30,-10);
t.equal(p3.x,147);
t.equal(p3.y,332);
});
test('Square#centerAt', function (t) {
t.plan(2);
var s = Square.centerAt(new Point(100,150),46);
t.equal(s.point.x,77);
t.equal(s.point.y,127);
});
| JavaScript | 0.000054 | @@ -957,9 +957,510 @@
);%0A%7D);%0A%0A
+test('Rectangle#round', function (t) %7B%0A t.plan(4);%0A var r = new Rect(new Point(33.4,2.1),44.7,88.9999).round();%0A t.equal(r.point.x,33);%0A t.equal(r.point.y,2);%0A t.equal(r.width,45);%0A t.equal(r.height,89);%0A%7D);%0A%0A%0Atest('Point#distaceTo', function (t) %7B%0A t.plan(3);%0A var p1 = new Point(10,50);%0A var p2 = new Point(10,60);%0A var p3 = new Point(20,50);%0A var p4 = new Point(20,60);%0A t.equals(p1.distanceTo(p2),10);%0A t.equals(p1.distanceTo(p3),10);%0A t.equals(Math.round(p1.distanceTo(p4)),14);%0A%7D);
%0A
|
f73ef4d5464a56939b9500dd51d0cea51a278ed4 | rename test packages.json to bundles.json | test/test.js | test/test.js | /* global describe, it */
'use strict';
var should = require('chai').should(); // eslint-disable-line no-unused-vars
var path = require('path');
var gp = require('../index.js').init({
applicationPath: '',
yiiPackagesCommand: 'cat ' + path.join(__dirname, 'data', 'packages.json'),
isAbsoluteCommandPath: false
});
var validDatas = require(path.join(__dirname, 'data', 'validDatas.json'));
describe('get-packages', function() {
it('’get’ function', function(done) {
validDatas.get.should.deep.equal(gp.get());
done();
});
it('’getPackagesDistPath’ function', function(done) {
validDatas.getPackagesDistPath.should.deep.equal(gp.getPackagesDistPath());
done();
});
it('’getPackagesDistPathWithoutImageDir’ function', function(done) {
validDatas.getPackagesDistPathWithoutImageDir.should.deep.equal(gp.getPackagesDistPathWithoutImageDir());
done();
});
it('’getStylesPaths’ function', function(done) {
validDatas.getStylesPaths.should.deep.equal(gp.getStylesPaths());
done();
});
it('’getStylesPathsByFilepath’ function without params', function(done) {
validDatas.getStylesPathsByFilepath.should.deep.equal(gp.getStylesPathsByFilepath());
done();
});
it('’getStylesPathsByFilepathWithFilePath’ function with filepath', function(done) {
validDatas.getStylesPathsByFilepathWithFilePath.should.deep.equal(gp.getStylesPathsByFilepath('/sample/protected/assets/desktop/src/scss/main.scss'));
done();
});
it('’getStylesPathsByFilepathWithFilePathAndGlob’ function with filepath and glob', function(done) {
validDatas.getStylesPathsByFilepathWithFilePathAndGlob.should.deep.equal(gp.getStylesPathsByFilepath('/sample/protected/assets/mobile/src/scss/main.less', path.join('**', '*.less')));
done();
});
it('’getStylesSourcePath’ function', function(done) {
validDatas.getStylesSourcePath.should.deep.equal(gp.getStylesSourcePath());
done();
});
it('’getStylesSourcePathWithGlob’ function without params', function(done) {
validDatas.getStylesSourcePathWithGlob.should.deep.equal(gp.getStylesSourcePathWithGlob());
done();
});
it('’getStylesSourcePathWithGlob’ function with glob', function(done) {
validDatas.getStylesSourcePathWithGlobWithGlob.should.deep.equal(gp.getStylesSourcePathWithGlob(path.join('**', '*.less')));
done();
});
it('’getScriptsSourcePath’ function', function(done) {
validDatas.getScriptsSourcePath.should.deep.equal(gp.getScriptsSourcePath());
done();
});
it('’getScriptsSourcePathWithoutFile’ function', function(done) {
validDatas.getScriptsSourcePathWithoutFile.should.deep.equal(gp.getScriptsSourcePathWithoutFile());
done();
});
it('’getScriptsSourcePathWithGlob’ function without params', function(done) {
validDatas.getScriptsSourcePathWithGlob.should.deep.equal(gp.getScriptsSourcePathWithGlob());
done();
});
it('’getScriptsSourcePathWithGlob’ function with glob', function(done) {
validDatas.getScriptsSourcePathWithGlobWithGlob.should.deep.equal(gp.getScriptsSourcePathWithGlob(path.join('**', '*.es6')));
done();
});
it('’getScriptsToBuild’ function', function(done) {
validDatas.getScriptsToBuild.should.deep.equal(gp.getScriptsToBuild());
done();
});
it('’getImagesPaths’ function', function(done) {
validDatas.getImagesPaths.should.deep.equal(gp.getImagesPaths());
done();
});
it('’getImagesSourcePath’ function', function(done) {
validDatas.getImagesSourcePath.should.deep.equal(gp.getImagesSourcePath());
done();
});
it('’getImagesSourcePathWithGlob’ function without params', function(done) {
validDatas.getImagesSourcePathWithGlob.should.deep.equal(gp.getImagesSourcePathWithGlob());
done();
});
it('’getImagesSourcePathWithGlob’ function with glob', function(done) {
validDatas.getImagesSourcePathWithGlobWithGlob.should.deep.equal(gp.getImagesSourcePathWithGlob(path.join('**', '*.svg')));
done();
});
it('’getFontsPaths’ function', function(done) {
validDatas.getFontsPaths.should.deep.equal(gp.getFontsPaths());
done();
});
it('’getExtraParamsByModule’ function', function(done) {
validDatas.getExtraParamsByModule.should.deep.equal(gp.getExtraParamsByModule('app.mobile'));
done();
});
it('’getExtraParamsByModule’ function with no exists package', function(done) {
gp.getExtraParamsByModule('app.tablet').should.false; // eslint-disable-line no-unused-expressions
done();
});
});
| JavaScript | 0.999576 | @@ -266,22 +266,21 @@
data', '
-packag
+bundl
es.json'
|
8192e3db806e0f9bc799b4b1e0f29f55b6a20dfd | Add test for json2csv | test/test.js | test/test.js | // var expect = require("chai").expect;
var chai = require('chai');
var chaiHttp = require('chai-http');
var app = require("../app.js");
var json2csv = require("../lib/routes/json2csv.js");
var csv2json = require("../lib/routes/csv2json.js");
chai.use(chaiHttp);
describe("Converting JSON to CSV", function() {
describe("/json2csv", function() {
it("should give a 400 code for empty POST requests", function() {
chai.request(app)
.post('/user/me')
.send({})
.end(function (err, res) {
expect(err).to.have.status(400);
});
});
it("should convert JSON to CSV", function() {
});
});
});
describe("Converting CSV to JSON", function() {
describe("/csv2json", function() {
it("should convert CSV to JSON", function() {
});
});
});
| JavaScript | 0.000047 | @@ -1,7 +1,32 @@
-//
+var chai = require('chai');%0A
var
@@ -62,36 +62,8 @@
ct;%0A
-var chai = require('chai');%0A
var
@@ -296,32 +296,33 @@
%22, function() %7B%0A
+%0A
describe(%22/jso
@@ -334,32 +334,33 @@
%22, function() %7B%0A
+%0A
it(%22should g
@@ -401,32 +401,36 @@
ests%22, function(
+done
) %7B%0A chai.r
@@ -461,15 +461,23 @@
t('/
-user/me
+api/v1/json2csv
')%0A
@@ -514,17 +514,16 @@
function
-
(err, re
@@ -541,19 +541,18 @@
-
expect(
-err
+res
).to
@@ -570,16 +570,34 @@
s(400);%0A
+ done();%0A
@@ -604,24 +604,25 @@
%7D);%0A %7D);%0A
+%0A
it(%22shou
@@ -647,36 +647,896 @@
CSV%22, function(
-) %7B%0A
+done) %7B%0A chai.request(app)%0A .post('/api/v1/json2csv')%0A .send(%5B%7B%0A %22name%22: %22Adam%22,%0A %22lastName%22: %22Smith%22,%0A %22gender%22: %22male%22,%0A %22country%22: %22Scotland%22%0A %7D, %7B%0A %22name%22: %22George%22,%0A %22lastName%22: %22Washington%22,%0A %22gender%22: %22male%22,%0A %22country%22: %22USA%22%0A %7D, %7B%0A %22name%22: %22Marie%22,%0A %22lastName%22: %22Curie%22,%0A %22gender%22: %22female%22,%0A %22country%22: %22France%22%0A %7D%5D)%0A .end(function(err, res) %7B%0A // console.log(res);%0A expect(res).to.have.status(200);%0A var csv = 'name,lastName,gender,country%5Cn' +%0A 'Adam,Smith,male,Scotland%5Cn' +%0A 'George,Washington,male,USA%5Cn' +%0A 'Marie,Curie,female,France%5Cn';%0A expect(res.text).to.equal(csv);%0A done();%0A %7D);
%0A %7D);%0A %7D);%0A%7D
@@ -1524,30 +1524,32 @@
%7D);%0A %7D);%0A
+%0A
%7D);%0A
+%0A
%7D);%0A%0Adescrib
@@ -1672,24 +1672,189 @@
unction() %7B%0A
+ chai.request(app)%0A .post('/')%0A .send()%0A .end(function(err, res) %7B%0A expect(res).to.have.status(200);%0A done();%0A %7D);
%0A %7D);%0A %7D
|
a887413d17692f9275c40b78404738b6836e2b2b | update test to write error.json | test/test.js | test/test.js | var assert = require('assert')
, tv4 = require('tv4')
, esschema = require('../esschema.json')
, Empty = require('./fixtures/Empty.json')
, FortyTwo = require('./fixtures/FortyTwo.json')
function valid(data, done) {
var result = tv4.validateResult(data, esschema)
if (result.error) {
console.log(result.error);
}
assert.equal(result.valid, true);
done();
}
function invalid(data, expect, done) {
var result = tv4.validateResult(data, esschema)
// console.log(result.error.message);
assert.equal(result.valid, false);
assert.equal(result.error.code, expect.code);
assert.equal((result.error.message.indexOf(expect.message) > -1), true);
done();
}
function checkMessageMissingRequiredProperty(property) {
return 'Missing required property: ' + property;
}
function checkMessageStringDoesNotMatchPattern(pattern) {
return 'String does not match pattern: ' + pattern
}
function checkMessageInvalidType(found, expected) {
return 'invalid type: ' + found + ' (expected ' + expected + ')';
}
function checkMessageDataDoesNotMatchAnySchemasFrom(keyword) {
return 'Data does not match any schemas from "' + keyword + '"';
}
function clone(object) {
return JSON.parse(JSON.stringify(object));
}
describe('esschema.json', function() {
describe('definitions', function() {
describe('Program', function() {
describe('#type', function() {
it('should be invalid when not \'Program\'', function(done) {
var data = clone(Empty);
data.type = 'Programm';
var expect = {
code: tv4.errorCodes.STRING_PATTERN,
message: checkMessageStringDoesNotMatchPattern('^Program$')
};
invalid(data, expect, done);
});
it('should be invalid when not a string', function(done) {
var data = clone(Empty);
data.type = 1;
var expect = {
code: tv4.errorCodes.INVALID_TYPE,
message: checkMessageInvalidType('number', 'string')
};
invalid(data, expect, done);
});
it('should be required', function(done) {
var data = clone(Empty);
delete data.type;
var expect = {
code: tv4.errorCodes.OBJECT_REQUIRED,
message: checkMessageMissingRequiredProperty('type')
};
invalid(data, expect, done);
});
});
describe('#body', function() {
it('should be invalid if not an array', function(done) {
var data = clone(Empty);
data.body = 1;
var expect = {
code: tv4.errorCodes.INVALID_TYPE,
message: checkMessageInvalidType('number', 'array')
};
invalid(data, expect, done);
});
it('should be an array of a valid type', function(done) {
var data = clone(FortyTwo);
data.body[0].type = 'VariableDeclarationn';
var expect = {
code: tv4.errorCodes.ONE_OF_MISSING,
message: checkMessageDataDoesNotMatchAnySchemasFrom('oneOf')
};
invalid(data, expect, done);
});
});
});
});
});
describe('Empty.json', function() {
it('should be valid against esschema.json', function(done) {
valid(Empty, done);
});
});
describe('FortyTwo.json', function() {
it('should be valid against esschema.json', function(done) {
valid(FortyTwo, done);
});
});
| JavaScript | 0.000001 | @@ -24,16 +24,39 @@
ssert')%0A
+ , fs = require('fs')%0A
, tv4
@@ -321,32 +321,145 @@
-console.log(result.error
+fs.writeFile(%0A './error.json', %0A JSON.stringify(result.error, null, 2), %0A function(err) %7B%0A console.err(err);%0A %7D
);%0A
|
e3f0ddb6d696f86bf27198ece001260932e3ee19 | update test case | test/test.js | test/test.js | /**
* @module test
* @license MIT
* @version 2017/11/09
*/
'use strict';
const fs = require('fs');
const path = require('path');
const arch = require('arch');
const ADODB = require('../index');
const expect = require('chai').expect;
const source = path.join(__dirname, 'node-adodb.mdb');
const mdb = fs.readFileSync(path.join(__dirname, '../examples/node-adodb.mdb'));
fs.writeFileSync(source, mdb);
// variable declaration
const x64 = arch() === 'x64';
const sysroot = process.env['systemroot'] || process.env['windir'];
const cscript = path.join(sysroot, x64 ? 'SysWOW64' : 'System32', 'cscript.exe');
if (fs.existsSync(cscript) && fs.existsSync(source)) {
console.log('Use:', cscript);
console.log('Database:', source);
// variable declaration
const connection = ADODB.open('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + source + ';');
describe('ADODB', () => {
it('query', (next) => {
connection
.query('SELECT * FROM Users')
.then((data) => {
expect(data.length).to.equal(3);
expect(data[0].UserName).to.equal('Nuintun');
expect(data[0]).to.have.ownProperty('UserBirthday');
expect(data[2].UserName).to.equal('张三');
next();
})
.catch((error) => {
next(error);
});
});
it('schema', (next) => {
connection
.schema(20)
.then((data) => {
expect(data).to.be.an('array');
if (data.length) {
expect(data[0]).to.include.all.keys(['TABLE_NAME', 'TABLE_TYPE']);
}
next();
})
.catch((error) => {
next(error);
});
});
it('Invaid sql syntax', (next) => {
connection
.query('SELECT * FROM Users-non-exist')
.catch((error) => {
expect(error).to.exist;
next();
});
});
describe('execute', () => {
it('no scalar', (next) => {
connection
.execute('INSERT INTO Users(UserName, UserSex, UserBirthday, UserMarried) VALUES ("Bill", "Male", "1991/3/9", 0)')
.then((data) => {
expect(data.length).to.equal(0);
next();
})
.catch((error) => {
next(error);
});
});
it('with scalar', (next) => {
connection
.execute('INSERT INTO Users(UserName, UserSex, UserBirthday, UserMarried) VALUES ("Alice", "Female", "1986/3/9", 0)', 'SELECT @@Identity AS id')
.then(function(data) {
expect(data.length).to.equal(1);
expect(data[0].id).to.equal(5);
next();
})
.catch((error) => {
next(error);
});
});
});
});
} else {
console.log('This OS not support node-adodb.');
}
| JavaScript | 0.000007 | @@ -1824,16 +1824,19 @@
ror).to.
+be.
exist;%0A
|
ac85b5b48c3f24f6af0a2caa88f9562c2e3c4256 | Load events don't bubble from detached node. | test/test.js | test/test.js | MockXHR.responses = {
'/hello': function(xhr) {
xhr.respond(200, '<div id="replaced">hello</div>')
},
'/one-two': function(xhr) {
xhr.respond(200, '<p id="one">one</p><p id="two">two</p>')
},
'/boom': function(xhr) {
xhr.respond(500, 'boom')
}
}
window.XMLHttpRequest = MockXHR
test('create from document.createElement', function() {
var el = document.createElement('deferred-content')
equal('DEFERRED-CONTENT', el.nodeName)
})
test('create from constructor', function() {
var el = new window.DeferredContentElement()
equal('DEFERRED-CONTENT', el.nodeName)
})
test('src property', function() {
var el = document.createElement('deferred-content')
equal(null, el.getAttribute('src'))
equal('', el.src)
el.src = 'content.html'
equal('content.html', el.getAttribute('src'))
var link = document.createElement('a')
link.href = 'content.html'
equal(link.href, el.src)
})
asyncTest('replaces element on 200 status', 2, function() {
var div = document.createElement('div')
div.innerHTML = '<deferred-content src="/hello">loading</deferred-content>'
document.getElementById('qunit-fixture').appendChild(div)
div.addEventListener('load', function(event) {
equal(document.querySelector('deferred-content'), null)
equal(document.querySelector('#replaced').textContent, 'hello')
start()
})
})
asyncTest('replaces with several new elements on 200 status', 3, function() {
var div = document.createElement('div')
div.innerHTML = '<deferred-content src="/one-two">loading</deferred-content>'
document.getElementById('qunit-fixture').appendChild(div)
div.addEventListener('load', function(event) {
equal(document.querySelector('deferred-content'), null)
equal(document.querySelector('#one').textContent, 'one')
equal(document.querySelector('#two').textContent, 'two')
start()
})
})
asyncTest('adds is-error class on 500 status', 1, function() {
var div = document.createElement('div')
div.innerHTML = '<deferred-content src="/boom">loading</deferred-content>'
document.getElementById('qunit-fixture').appendChild(div)
div.addEventListener('error', function(event) {
event.stopPropagation()
ok(document.querySelector('deferred-content').classList.contains('is-error'))
start()
})
})
asyncTest('adds is-error class on xhr error', 1, function() {
var div = document.createElement('div')
div.innerHTML = '<deferred-content src="/boom">loading</deferred-content>'
document.getElementById('qunit-fixture').appendChild(div)
div.addEventListener('error', function(event) {
event.stopPropagation()
ok(document.querySelector('deferred-content').classList.contains('is-error'))
start()
})
})
| JavaScript | 0 | @@ -1151,32 +1151,43 @@
ild(div)%0A%0A div.
+firstChild.
addEventListener
@@ -1621,32 +1621,43 @@
ild(div)%0A%0A div.
+firstChild.
addEventListener
|
122c5616a107c8e099b439de747b2a5a7073f7ee | revert to use of var, until test script is updated to es6 | test/test.js | test/test.js | const assert = require("assert");
const tfs = require("tfs-unlock");
const gutil = require("gulp-util");
const through = require("through2");
const prefixer = require("../");
describe("gulp-tfs-checkout", function() {
it("should return true if file is empty", function(done) {
const fakeFile = new gutil.File({
path: "/this/file/is/empty"
});
const testPrefixer = prefixer();
testPrefixer.write(fakeFile);
testPrefixer.once("data", function(file) {
assert.equal(file.isNull(), true);
done();
});
});
});
| JavaScript | 0 | @@ -1,13 +1,11 @@
-const
+var
assert
@@ -25,21 +25,19 @@
sert%22);%0A
-const
+var
tfs = r
@@ -58,21 +58,19 @@
lock%22);%0A
-const
+var
gutil =
@@ -92,21 +92,19 @@
util%22);%0A
-const
+var
through
@@ -127,21 +127,19 @@
ugh2%22);%0A
-const
+var
prefixe
@@ -267,21 +267,19 @@
) %7B%0A
-const
+var
fakeFil
@@ -350,13 +350,11 @@
-const
+var
tes
|
ecef6154098644bedadbff3292c923ca116234af | optimize code and bug fixed | test/test.js | test/test.js | var udeps = require('../index');
var expect = require('expect.js');
describe('get the right deps', function (){
var s = 'var RE=/[\\\\]/,str="\\\\"||"[\\\\]"||"/*";require("a");require(\'b"\');require("c\\"");';
var res = udeps(s);
it('path', function (){
expect(res.map(function (o){
return o.path;
})).to.eql(['a', 'b"', 'c"']);
});
it('use replace', function (){
var s = 'require("a");require("b");var num=0||.7e+7||7.7e+7||0xff;/*';
var res = udeps(s, function (path){
return 'woot/' + path;
});
expect(res).to.eql('require("woot/a");require("woot/b");var num=0||.7e+7||7.7e+7||0xff;/*');
});
it('reg & comment', function (){
var s = '(1)/*\n*/ / require("a");return/*\nreturn*/;return/\\/;';
var res = udeps(s, true).map(function (o){
return o.path;
});
expect(res).to.eql(["a"]);
});
it('include async', function (){
var s = 'require.async("a");';
var res = udeps(s, function (){
return '1';
}, true);
expect(res).to.eql('require.async("1");');
s = 'require["async"]("a");';
res = udeps(s, function (){
return '1';
}, true);
expect(res).to.eql('require["async"]("1");');
s = 'require.async(["a", "b"]);';
res = udeps(s, function (){
return '1';
}, true);
expect(res).to.eql('require.async(["1", "1"]);');
s = 'require["async"](["a", "b"]);';
res = udeps(s, function (){
return '1';
}, true);
expect(res).to.eql('require["async"](["1", "1"]);');
});
it('async flag', function (){
var s = 'require.async("a");';
var res = udeps(s, function (path, flag){
return flag;
}, true);
expect(res).to.eql('require.async("async");');
});
it('custom flag', function (){
var s = 'require.custom("a");';
var res = udeps(s, function (path, flag){
return flag;
}, true);
expect(res).to.eql('require.custom("custom");');
});
it('return', function (){
var s = "return require('highlight.js').highlightAuto(code).value;";
var res = udeps(s);
expect(res.length).to.eql(1);
});
it('callback', function (){
var s = 'require.async("slider", function(){\nalert("loaded");\n});';
var res = udeps(s, true);
expect(res.length).to.eql(1);
});
it('block & reg 1', function (){
var s = '({}/require("a"))';
var res = udeps(s);
expect(res.length).to.eql(1);
});
it('block & reg 2', function (){
var s = 'return {}/require("a");';
var res = udeps(s);
expect(res.length).to.eql(1);
});
it('block & reg 3', function (){
var s = 'v={}/require("a");';
var res = udeps(s);
expect(res.length).to.eql(1);
});
});
describe('ignores', function (){
it('in quote', function (){
var s = '"require(\'a\')"';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('in comment', function (){
var s = '//require("a")';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('in multi comment', function (){
var s = '/*\nrequire("a")*/';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('in reg', function (){
var s = '/require("a")/';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('in ifstmt with no {}', function (){
var s = 'if(true)/require("a")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('in dostmt with no {}', function (){
var s = 'do /require("a")/.test(s); while(false);';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('reg / reg', function (){
var s = '/require("a")/ / /require("b")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('ignore variable', function (){
var s = 'require("a" + b);';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('unend string', function (){
var s = 'require("a';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('unend comment', function (){
var s = '/*';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('unend reg', function (){
var s = '/abc';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('ignore async', function (){
var s = 'require.async("a");';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('block & reg 1', function (){
var s = '{}/require("a")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('block & reg 2', function (){
var s = 'return\n{}/require("a")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('block & reg 3', function (){
var s = '()=>{}/require("a")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
it('block & reg 4', function (){
var s = '(1)\n{}/require("a")/;';
var res = udeps(s);
expect(res.length).to.eql(0);
});
});
describe('callback', function (){
it('none', function (){
var s = 'test("a");';
var res = udeps(s, function (){
return '1';
});
expect(res).to.eql(s);
});
it('one', function (){
var s = 'require("a");';
var res = udeps(s, function (){
return '1';
});
expect(res).to.eql('require("1");');
});
it('two', function (){
var s = 'require("a");require("b");';
var res = udeps(s, function (path){
return 'root/' + path;
});
expect(res).to.eql('require("root/a");require("root/b");');
});
it('same length as item', function (){
var s = 'require("a");require("b");';
var res = udeps(s, function (){
return '123456789012';
});
expect(res).to.eql('require("123456789012");require("123456789012");');
});
}); | JavaScript | 0 | @@ -205,16 +205,31 @@
%22c%5C%5C%22%22);
+require(%5B%22d%22%5D);
';%0A var
|
4c0dfb36c9814228c633a430041f516018114a9c | Revert "Prepare branch for section 2.4 tutorial" | routes/recipes/index.js | routes/recipes/index.js | var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Escape a string for regexp use
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
| JavaScript | 0 | @@ -128,133 +128,8 @@
);%0A%0A
-// Escape a string for regexp use%0Afunction escapeRegExp(string) %7B%0A return string.replace(/%5B.*+?%5E$%7B%7D()%7C%5B%5C%5D%5C%5C%5D/g, %22%5C%5C$&%22);%0A%7D%0A%0A
// R
|
b94196faae17a013d8c32e8eb2b67f69c2a5a7f7 | Allow calls to Promise.reject() with no arguments | rules/best-practices.js | rules/best-practices.js | 'use strict';
module.exports = {
rules: {
// enforce getter and setter pairs in objects
'accessor-pairs': 'error',
// enforce return statements in callbacks of array methods
'array-callback-return': 'error',
// enforce the use of variables within the scope they are defined
'block-scoped-var': 'error',
// enforce that class methods utilize this
'class-methods-use-this': 'error',
// enforce a maximum cyclomatic complexity allowed in a program
'complexity': ['error', 11],
// require return statements to either always or never specify values
'consistent-return': 'error',
// enforce consistent brace style for all control statements
'curly': 'error',
// require default cases in switch statements
'default-case': 'error',
// enforce consistent newlines before and after dots
'dot-location': 'error',
// enforce dot notation whenever possible
'dot-notation': 'error',
// require the use of === and !==
'eqeqeq': ['error', 'smart'],
// require for-in loops to include an if statement
'guard-for-in': 'error',
// disallow the use of alert, confirm, and prompt
'no-alert': 'warn',
// disallow the use of arguments.caller or arguments.callee
'no-caller': 'error',
// disallow lexical declarations in case clauses
'no-case-declarations': 'error',
// disallow division operators explicitly at the beginning of regular expressions
'no-div-regex': 'error',
// disallow else blocks after return statements in if statements
'no-else-return': 'error',
// disallow empty functions
'no-empty-function': ['error', {allow: ['arrowFunctions', 'functions', 'methods']}],
// disallow empty destructuring patterns
'no-empty-pattern': 'error',
// disallow null comparisons without type-checking operators
'no-eq-null': 'off',
// disallow the use of eval()
'no-eval': 'error',
// disallow extending native types
'no-extend-native': 'error',
// disallow unnecessary calls to .bind()
'no-extra-bind': 'error',
// disallow unnecessary labels
'no-extra-label': 'error',
// disallow fallthrough of case statements
'no-fallthrough': 'error',
// disallow leading or trailing decimal points in numeric literals
'no-floating-decimal': 'error',
// disallow assignments to native objects or read-only global variables
'no-global-assign': 'error',
// disallow shorthand type conversions
'no-implicit-coercion': 'error',
// disallow variable and function declarations in the global scope
'no-implicit-globals': 'error',
// disallow the use of eval()-like methods
'no-implied-eval': 'error',
// disallow this keywords outside of classes or class-like objects
'no-invalid-this': 'off',
// disallow the use of the __iterator__ property
'no-iterator': 'error',
// disallow labeled statements
'no-labels': 'error',
// disallow unnecessary nested blocks
'no-lone-blocks': 'error',
// disallow function declarations and expressions inside loop statements
'no-loop-func': 'error',
// disallow magic numbers
'no-magic-numbers': 'off',
// disallow multiple spaces
'no-multi-spaces': 'error',
// disallow multiline strings
'no-multi-str': 'error',
// disallow new operators outside of assignments or comparisons
'no-new': 'error',
// disallow new operators with the Function object
'no-new-func': 'error',
// disallow new operators with the String, Number, and Boolean objects
'no-new-wrappers': 'error',
// disallow octal literals
'no-octal': 'error',
// disallow octal escape sequences in string literals
'no-octal-escape': 'error',
// disallow reassigning function parameters
'no-param-reassign': 'error',
// disallow the use of the __proto__ property
'no-proto': 'error',
// disallow variable redeclaration
'no-redeclare': 'error',
// disallow certain properties on certain objects
'no-restricted-properties': ['error', {
message: 'arguments.callee is deprecated',
object: 'arguments',
property: 'callee',
}, {
message: 'Please use Object.defineProperty instead.',
property: '__defineGetter__',
}, {
message: 'Please use Object.defineProperty instead.',
property: '__defineSetter__',
}, {
message: 'Please use the object spread operator (...) instead.',
object: 'Object',
property: 'assign',
}],
// disallow assignment operators in return statements
'no-return-assign': ['error', 'always'],
// disallow assignment operators in return statements
'no-return-await': 'error',
// disallow javascript: urls
'no-script-url': 'error',
// disallow assignments where both sides are exactly the same
'no-self-assign': 'error',
// disallow comparisons where both sides are exactly the same
'no-self-compare': 'error',
// disallow comma operators
'no-sequences': 'error',
// disallow throwing literals as exceptions
'no-throw-literal': 'error',
// disallow unmodified loop conditions
'no-unmodified-loop-condition': 'error',
// disallow unused expressions
'no-unused-expressions': 'error',
// disallow unused labels
'no-unused-labels': 'error',
// disallow unnecessary calls to .call() and .apply()
'no-useless-call': 'error',
// disallow unnecessary concatenation of literals or template literals
'no-useless-concat': 'error',
// disallow unnecessary escape characters
'no-useless-escape': 'error',
// disallow redundant return statements
'no-useless-return': 'error',
// disallow void operators
'no-void': 'error',
// disallow specified warning terms in comments
'no-warning-comments': 'warn',
// disallow with statements
'no-with': 'error',
// require using Error objects as Promise rejection reasons
'prefer-promise-reject-errors': 'error',
// enforce the consistent use of the radix argument when using parseInt()
'radix': 'error',
// disallow async functions which have no await expression
'require-await': 'off',
// require var declarations be placed at the top of their containing scope
'vars-on-top': 'error',
// require parentheses around immediate function invocations
'wrap-iife': ['error', 'inside'],
// require or disallow “Yoda” conditions
'yoda': 'error',
},
};
| JavaScript | 0 | @@ -6036,32 +6036,33 @@
ct-errors':
+%5B
'error',
%0A%0A // enf
@@ -6041,32 +6041,59 @@
rors': %5B'error',
+ %7BallowEmptyReject: true%7D%5D,
%0A%0A // enforce
|
563bf56f53db51ad2ecd1c4393c6b697649411bd | Update issue8test | neukinnis/spec/integration/issue8test.js | neukinnis/spec/integration/issue8test.js | /*
* By: Frances Go
* Date: Jan 2015
* Title: Casper Test Integration
*/
// casper.test.begin(testTitle, numberOfTests, callback)
casper.test.begin('Testing About the Courses page', 13, function(test){
casper.start('http://localhost:3000/courses.html', function(){
this.test.assertUrlMatch('/courses.html', 'currently in the courses page');
test.assertTitle('About the Courses', 'about the courses title is good');
});
casper.then(function(){
this.click('a[href="/"]');
});
casper.then(function() {
this.test.assertUrlMatch('/', 'currently in the homepage');
this.echo('Page title is: ' + this.getTitle());
test.assertTitle(this.getTitle(), 'homepage title is good');
});
casper.then(function(){
this.click('a[href="/courses.html"]');
});
casper.then(function(){
this.test.assertUrlMatch('/courses.html', 'currenty in the courses page');
this.echo('Page title is: ' + this.getTitle());
test.assertTitle(this.getTitle(), 'about the courses title is good');
});
casper.then(function(){
this.test.assertExists('.breadcrumb li a', 'breadcrumbs found');
this.test.assertEval(function() {
return __utils__.findAll('.row .thumbnail').length >= 6;
}, 'there are at least 6 course images on the page');
});
casper.then(function(){
this.click('a[href="/instructors.html"]');
});
casper.then(function(){
this.test.assertUrlMatch('/instructors.html', 'currenty in the instructors page');
this.echo('Page title is: ' + this.getTitle());
test.assertTitle(this.getTitle(), 'instructor title is good');
});
casper.then(function(){
this.click('a[href="/courses.html"]');
});
casper.then(function(){
this.test.assertUrlMatch('/courses.html', 'currenty in the courses page');
this.test.assertExists('footer div', 'footer information found');
});
casper.then(function(){
this.test.assertEval(function() {
return __utils__.findAll('.row h3 a').length >= 6;
}, 'there are at least 6 course title links on the page');
});
casper.run(function(){
test.done();
});
}); | JavaScript | 0 | @@ -892,32 +892,33 @@
.html', 'current
+l
y in the courses
@@ -1519,32 +1519,33 @@
.html', 'current
+l
y in the instruc
@@ -1861,16 +1861,17 @@
'current
+l
y in the
@@ -1879,32 +1879,88 @@
courses page');%0A
+ this.echo('Page title is: ' + this.getTitle());%0A
this.tes
|
9747646ded68799f930c1a21345402a293b1c357 | Tweak ajaxChosen | media/js/libs/chosen.ajax.jquery.js | media/js/libs/chosen.ajax.jquery.js | (function() {
(function($) {
return $.fn.ajaxChosen = function(options, callback) {
var select;
select = this;
this.chosen().change(function() {
$select = $(this);
// New message
if ($('body').hasClass('new-message')) {
$option = $('option:selected', $select);
if ($select.attr('id') === 'id_user') {
if ($option.val() !== '') {
$('div.team, div.or').addClass('disabled');
$('select#id_team').attr('disabled', 'disabled').trigger('liszt:updated');
} else {
$('div.team, div.or').removeClass('disabled');
$('select#id_team').removeAttr('disabled').trigger('liszt:updated');
}
}
}
});
return this.next('.chzn-container').find(".chzn-search > input").bind('keyup', function() {
var field, val;
val = $.trim($(this).attr('value'));
if (val === $(this).data('prevVal')) {
return false;
}
if (val.length < 1) {
$sel = $('ul.chzn-results', select.next('.chzn-container'));
$lis = $sel.children('li');
if ($lis.length === 1) {
$lis.remove();
}
if ($('li.no-results', $sel).length === 0) {
$sel.prepend($('<li class="no-results">Begin typing to search.</li>'));
}
$lis.removeClass('highlighted');
return false;
}
$(this).data('prevVal', val);
field = $(this);
options.data = {
term: val,
// New tasks.
task_type: $('select#id_type option:selected').val(),
team_video: $('input[name="id_team_video"]').val(),
task_lang: $('input[name="language"]').val()
};
if (!options.data['task_type']) {
// Existing tasks.
options.data = {
term: val,
task_type: field.parents('form.assign-form').children('input[name="task_type"]').val(),
team_video: field.parents('form.assign-form').children('input[name="task_video"]').val(),
task: field.parents('form.assign-form').children('input[name="task"]').val(),
task_lang: field.parents('form.assign-form').children('input[name="task_lang"]').val()
}
}
if (typeof success !== "undefined" && success !== null) {
success;
} else {
success = options.success;
}
options.success = function(data) {
var items;
if (!(data != null)) {
return;
}
select.find('option').each(function() {
if (!$(this).is(":selected")) {
return $(this).remove();
}
});
items = callback(data);
$.each(items, function(value, text) {
return $("<option />", {'value': value, 'html': text}).appendTo(select);
});
var rem = field.attr('value');
select.trigger("liszt:updated");
field.attr('value', rem);
field.keyup();
if (typeof success !== "undefined" && success !== null) {
return success();
}
};
if (window.chosenAjaxInProgress) {
window.chosenAjaxInProgress.abort();
}
window.chosenAjaxInProgress = $.ajax(options);
return window.chosenAjaxInProgress;
});
};
})(jQuery);
}).call(this);
| JavaScript | 0.000001 | @@ -3719,24 +3719,25 @@
r('value');%0A
+%0A
@@ -3823,17 +3823,16 @@
, rem);%0A
-%0A
@@ -3855,24 +3855,24 @@
d.keyup();%0A%0A
-
@@ -3929,32 +3929,71 @@
ess !== null) %7B%0A
+ field.keyup();%0A
|
f93e38cda01f731f4847a507799550f4c4bd947f | Update comment for Navigation Component | src/main/webapp/components/Navigation.js | src/main/webapp/components/Navigation.js | import * as React from "react";
/**
*/
const NavigationItem = props => <li><a href={props.href}>{props.innerText}</a></li>
/**
* Main Navigation List.
* Instance will be embedded in ./Header component.
*/
export const Navigation = (props) => {
return (
<ul>
{props.options.map(option => <NavigationItem href={option.link} innerText={option.text}/>)}
</ul>
);
}
| JavaScript | 0 | @@ -200,16 +200,152 @@
ponent.%0A
+ * @param %7Boptions: %5Boption%5D%7D props arbituary object containing an array of%0A * options, where each option = %7Bhref:String, text: String%7D%0A
*/%0Aexpo
|
004610af9d698d59780520312896096ce465647e | Remove obsolete comments | test/trie.js | test/trie.js | var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should return itself when adding', function() {
expect(trie.add('test')).to.equal(trie);
});
it('should return true when found', function() {
expect(trie.add('test').find('test')).to.be.true;
});
it('should return false when not found', function() {
expect(trie.find('test')).to.be.false;
});
it('should consider case when finding', function() {
trie.add('TeSt');
expect(trie.find('test')).to.be.false;
expect(trie.find('TEST')).to.be.false;
expect(trie.find('TeSt')).to.be.true;
});
it('should trim leading/trailing spaces when adding', function() {
expect(trie.add(' test ').find('test')).to.be.true;
});
it('should return an array when searching', function() {
expect(trie.search('test')).to.be.an.instanceof(Array);
});
it('should return an empty array when searching with no match', function() {
expect(trie.search('test')).to.be.empty;
});
it('should return a single element array when searching with one match', function() {
expect(trie.add('test').search('test')).to.have.length(1);
});
it('should return all matching strings when searching', function() {
trie.add('test');
trie.add('tester');
trie.add('nottest');
var result = trie.search('test');
expect(result).to.contain('test');
expect(result).to.contain('tester');
expect(result).to.not.contain('nottest');
});
it('should ignore case when searching', function() {
trie.add('test lower');
trie.add('TEST UPPER');
trie.add('TeSt MiXeD');
var result = trie.search('test');
expect(result).to.contain('test lower');
expect(result).to.contain('TEST UPPER');
expect(result).to.contain('TeSt MiXeD');
});
// search not match return empty array
// search one match return one element array
// add should ignore case on character -> TrieNode
// add should save case on word -> TrieNode
});
| JavaScript | 0 | @@ -2326,96 +2326,8 @@
);%0A%0A
- // search not match return empty array%0A // search one match return one element array%0A
//
|
ee132e914021647b5eb549aca3940dbd1732c0ee | Write test for built-in and custom event binding. | test/unit.js | test/unit.js | import 'skatejs-named-slots';
import { emit } from '../src/index';
import { number } from '../src/properties';
import * as IncrementalDOM from 'incremental-dom';
import kickflip from '../src/kickflip';
import state from '../src/state';
import vdom, { IncrementalDOM as VdomIncrementalDOM } from '../src/vdom';
import version from '../src/version';
let componentCount = 0;
function component (opts) {
return kickflip(`my-el-${++componentCount}`, opts);
}
function element (opts) {
return component(opts)();
}
describe('kickflip', function () {
it('kickflip', function () {
expect(kickflip).to.be.a('function');
});
it('state', function () {
expect(state).to.be.a('function');
});
it('vdom', function () {
expect(vdom).to.be.a('function');
});
it('version', function () {
expect(version).to.be.a('string');
});
});
describe('events (on*)', function () {
it('should not duplicate listeners', function (done) {
const myel = component({
properties: {
test: number({ default: 0 })
},
created (elem) {
elem._test = 0;
},
render (elem) {
vdom('div', {
onevent () {
elem._test++;
}
}, elem.test);
}
});
const el = myel();
const shadowDiv = el.shadowRoot.children[0];
// Ensures that it rendered.
expect(shadowDiv.textContent).to.equal('0');
expect(el._test).to.equal(0);
// Trigger the handler.
emit(shadowDiv, 'event');
// Ensure the event fired.
expect(el._test).to.equal(1);
// Re-render.
el.test++;
setTimeout(function () {
expect(shadowDiv.textContent).to.equal('1');
emit(shadowDiv, 'event');
expect(el._test).to.equal(2);
el.test++;
setTimeout(function () {
expect(shadowDiv.textContent).to.equal('2');
emit(shadowDiv, 'event');
expect(el._test).to.equal(3);
done();
}, 100);
}, 100);
});
it('should not trigger events bubbled from descendants', function () {
let called = false;
const test = () => called = true;
const myel = component({
render () {
vdom('div', { ontest: test }, vdom.bind(null, 'span'));
}
})();
emit(myel.querySelector('span'), 'test');
expect(called).to.equal(false);
});
it('should not fail for listeners that are not functions', function () {
const myel = component({
render () {
vdom('div', { ontest: null });
}
})();
emit(myel.shadowRoot.firstChild, 'test');
});
});
describe('IncrementalDOM', function () {
it('should export all the same members as the incremental-dom we consume', function () {
expect(VdomIncrementalDOM).to.contain(IncrementalDOM);
});
});
describe('properties', function () {
it('class -> className', function () {
const elem = element({
render () {
vdom('div', { class: 'test' });
}
});
expect(elem.shadowRoot.firstChild.className).to.equal('test');
});
it('false should remove the attribute', function () {
const elem = element({
render () {
vdom('div', { test: false });
}
});
expect(elem.shadowRoot.firstChild.hasAttribute('test')).to.equal(false);
});
});
| JavaScript | 0 | @@ -881,32 +881,719 @@
, function () %7B%0A
+ it('built-in events', function () %7B%0A let count = 0;%0A const el = element(%7B%0A render () %7B%0A vdom('div', %7B onclick: () =%3E ++count %7D);%0A %7D%0A %7D).shadowRoot.firstChild;%0A expect(count).to.equal(0);%0A expect(el.onclick).to.be.a('function');%0A el.onclick();%0A expect(count).to.equal(1);%0A emit(el, 'click');%0A expect(count).to.equal(2);%0A %7D);%0A%0A it('custom events', function () %7B%0A let count = 0;%0A const el = element(%7B%0A render () %7B%0A vdom('div', %7B ontest: () =%3E ++count %7D);%0A %7D%0A %7D).shadowRoot.firstChild;%0A expect(count).to.equal(0);%0A expect(el.test).to.equal(undefined)%0A emit(el, 'test');%0A expect(count).to.equal(1);%0A %7D);%0A%0A
it('should not
|
3c9cfe145942a4f8706c2362442f0906ae9b6e70 | fix bug fix with access_token | js/components/security.js | js/components/security.js | module.exports = function(oauth, settings) {
return new Security(oauth, settings);
}
var _ = require('underscore'),
basic_auth = require('http-auth');
var request = require("request");
var Promise = require('bluebird');
/**
* AuthoriseClient
*
* @param {Object} config Instance of OAuth object
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
function Security(oauth, settings) {
this.oauth = oauth;
this.settings = settings;
this.rules = settings.rules;
return this;
}
Security.prototype.getSecurityMiddleware = function(rule) {
var self = this;
var rule = self.rules[rule];
var methods = rule['methods'];
var securityCallback = rule['callback'];
return function(req, res, next) {
if (!methods) {
return next();
}
if (typeof methods == 'string') {
methods = [methods];
}
if (_.contains(methods, 'oauth')) {
if (self.oauth == null) {
var reg = new RegExp("^bearer ");
var authorization = req.headers.authorization;
if (authorization && reg.test(authorization.toLowerCase())) {
oAuthAccessToken = authorization.toLowerCase().replace("bearer ", "");
}
if (req.query.access_token) {
oAuthAccessToken = req.query.access_token;
}
new Promise(function(resolve, reject) {
if (oAuthAccessToken != null) {
request.get(self.settings.userd_me_url, {
auth: {
bearer: oAuthAccessToken
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
req.user = JSON.parse(response.body);
var securityCallbackResult = true;
if (securityCallback != undefined) {
console.log(securityCallback);
securityCallbackResult = securityCallback(req.user)
if (securityCallbackResult) {
return resolve()
} else {
return reject();
}
} else {
return resolve();
}
} else {
return reject();
}
});
} else {
return reject();
}
}).then(function() {
next();
}).catch(function(e) {
res.send(401, {
error: "Authorization required"
});
});
}
else {
var reg = new RegExp("^bearer ");
var authorization = req.headers.authorization;
if (authorization && reg.test(authorization.toLowerCase())) {
return self.oauth.authorise()(req, res, next);
} else {
res.send(401, {
error: "Authorization required"
});
}
}
} else if (_.contains(methods, 'http')) {
var reg = new RegExp("^basic ");
var authorization = req.headers.authorization;
console.log(authorization);
if (authorization && reg.test(authorization.toLowerCase())) {
var auth = basic_auth.basic({
realm: self.settings.basic.realm
}, function(username, password, callback) { // Custom authentication method.
callback(username === self.settings.basic.user && password === self.settings.basic.password);
});
return basic_auth.connect(auth)(req, res, next);
} else {
res.send(401, {
error: "Authorization required"
});
}
} else {
res.send(401, {
error: "Authorization required"
});
}
}
}
| JavaScript | 0.000001 | @@ -989,24 +989,68 @@
== null) %7B%0A
+ var oAuthAccessToken = %22%22;%0A%0A
@@ -1824,17 +1824,16 @@
body) %7B
-
%0A
|
8d513c55203e6200f5f9f2d4f40e2e54e9eb7f9e | swap getting token in util function | test/util.js | test/util.js |
/**
* Module dependencies
*/
var WPCOM = require('../');
/**
* Detect client/server side
*/
var is_client_side = 'undefined' !== typeof window;
/**
* Testing data
*/
var fixture = require('./fixture');
module.exports = {
wpcom: wpcom,
wpcom_public: function() { return WPCOM(); }
};
function wpcom() {
if (is_client_side) {
var proxy = require('../node_modules/wpcom-proxy-request');
var _wpcom = WPCOM(proxy);
_wpcom.request({
metaAPI: { accessAllUsersBlogs: true }
}, function(err) {
if (err) throw err;
console.log('proxy now running in "access all user\'s blogs" mode');
});
return _wpcom;
} else {
// get token from environment var
var token = require('./token').value || process.env.TOKEN;
return WPCOM(token);
}
}
| JavaScript | 0.000053 | @@ -715,16 +715,37 @@
token =
+ process.env.TOKEN %7C%7C
require
@@ -765,29 +765,8 @@
alue
- %7C%7C process.env.TOKEN
;%0A
|
ed7322ff7b2de46786a2f81885b5142cf1b4442c | _.find is the preferred name for _.detect | js/saiku/views/Toolbar.js | js/saiku/views/Toolbar.js | /*
* Copyright 2012 OSBI Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The global toolbar
*/
var Toolbar = Backbone.View.extend({
tagName: "div",
events: {
'click a' : 'call'
},
template: function() {
return _.template( $("#template-toolbar").html() )(this);
},
initialize: function() {
this.render();
},
render: function() {
$(this.el).attr('id', 'toolbar')
.html(this.template());
// Trigger render event on toolbar so plugins can register buttons
Saiku.events.trigger('toolbar:render', { toolbar: this });
return this;
},
call: function(e) {
var target = $(e.target);
var callback = target.attr('href').replace('#', '');
if(this[callback]) {
this[callback](e);
}
e.preventDefault();
},
/**
* Add a new tab to the interface
*/
new_query: function() {
Saiku.tabs.add(new Workspace());
return false;
},
/**
* Open a query from the repository into a new tab
*/
open_query: function() {
var dialog = _.detect(Saiku.tabs._tabs, function(tab) {
return tab.content instanceof OpenQuery;
});
if (dialog) {
dialog.select();
} else {
Saiku.tabs.add(new OpenQuery());
}
return false;
},
/**
* Clear the current session and show the login window
*/
logout: function() {
Saiku.session.logout();
},
/**
* Show the credits dialog
*/
about: function() {
(new AboutModal).render().open();
return false;
},
/**
* Go to the issue tracker
*/
issue_tracker: function() {
window.open('http://jira.meteorite.bi/');
return false;
}
});
| JavaScript | 0.999999 | @@ -1715,25 +1715,20 @@
var
-dialog = _.detect
+tab = _.find
(Sai
@@ -1844,22 +1844,19 @@
if (
-dialog
+tab
) %7B%0A
@@ -1863,22 +1863,19 @@
-dialog
+tab
.select(
|
d7020faa61ddd5e6ab6206278fa6f7e188a112be | Handle invite message | src/commands/handlers/channel.js | src/commands/handlers/channel.js | var _ = require('lodash');
var handlers = {
RPL_CHANNELMODEIS: function(command) {
var channel = command.params[1];
var modes = this.parseModeList.call(this, command.params[2], command.params.slice(3));
this.emit('channel info', {
channel: channel,
modes: modes
});
},
RPL_CREATIONTIME: function(command) {
var channel = command.params[1];
this.emit('channel info', {
channel: channel,
created_at: parseInt(command.params[2], 10)
});
},
RPL_CHANNEL_URL: function(command) {
var channel = command.params[1];
this.emit('channel info', {
channel: channel,
url: command.params[command.params.length - 1]
});
},
RPL_NAMEREPLY: function(command) {
var that = this;
var members = command.params[command.params.length - 1].split(' ');
var cache = this.cache('names.' + command.params[2]);
if (!cache.members) {
cache.members = [];
}
_.each(members, function(member) {
var j = 0;
var modes = [];
// If we have prefixes, strip them from the nick and keep them separate
if (that.network.options.PREFIX) {
for (j = 0; j < that.network.options.PREFIX.length; j++) {
if (member[0] === that.network.options.PREFIX[j].symbol) {
modes.push(that.network.options.PREFIX[j].mode);
member = member.substring(1);
}
}
}
cache.members.push({nick: member, modes: modes});
});
},
RPL_ENDOFNAMES: function(command) {
var cache = this.cache('names.' + command.params[1]);
this.emit('userlist', {
channel: command.params[1],
users: cache.members
});
cache.destroy();
},
RPL_BANLIST: function(command) {
var cache = this.cache('banlist.' + command.params[1]);
if (!cache.bans) {
cache.bans = [];
}
cache.bans.push({
channel: command.params[1],
banned: command.params[2],
banned_by: command.params[3],
banned_at: command.params[4]
});
},
RPL_ENDOFBANLIST: function(command) {
var cache = this.cache('banlist.' + command.params[1]);
this.emit('banlist', {
channel: command.params[1],
bans: cache.bans
});
cache.destroy();
},
RPL_TOPIC: function(command) {
this.emit('topic', {
channel: command.params[1],
topic: command.params[command.params.length - 1]
});
},
RPL_NOTOPIC: function(command) {
this.emit('topic', {
channel: command.params[1],
topic: ''
});
},
RPL_TOPICWHOTIME: function(command) {
this.emit('topicsetby', {
nick: command.params[2],
channel: command.params[1],
when: command.params[3]
});
},
JOIN: function(command) {
var channel;
var gecos_idx = 1;
var data = {};
if (typeof command.params[0] === 'string' && command.params[0] !== '') {
channel = command.params[0];
}
if (this.network.cap.isEnabled('extended-join')) {
data.account = command.params[1] === '*' ? false : command.params[1];
gecos_idx = 2;
}
data.nick = command.nick;
data.ident = command.ident;
data.hostname = command.hostname;
data.gecos = command.params[gecos_idx] || '';
data.channel = channel;
data.time = command.getServerTime();
this.emit('join', data);
},
PART: function(command) {
var time = command.getServerTime();
var channel = command.params[0];
var message;
if (command.params.length > 1) {
message = command.params[command.params.length - 1];
}
this.emit('part', {
nick: command.nick,
ident: command.ident,
hostname: command.hostname,
channel: channel,
message: message,
time: time
});
},
KICK: function(command) {
var time = command.getServerTime();
this.emit('kick', {
kicked: command.params[1],
nick: command.nick,
ident: command.ident,
hostname: command.hostname,
channel: command.params[0],
message: command.params[command.params.length - 1],
time: time
});
},
QUIT: function(command) {
var time = command.getServerTime();
this.emit('quit', {
nick: command.nick,
ident: command.ident,
hostname: command.hostname,
message: command.params[command.params.length - 1],
time: time
});
},
TOPIC: function(command) {
// If we don't have an associated channel, no need to continue
if (!command.params[0]) {
return;
}
// Check if we have a server-time
var time = command.getServerTime();
var channel = command.params[0];
var topic = command.params[command.params.length - 1] || '';
this.emit('topic', {
nick: command.nick,
channel: channel,
topic: topic,
time: time
});
},
RPL_INVITING: function(command) {
this.emit('invited', {
nick: command.params[0],
channel: command.params[1]
});
}
};
module.exports = function AddCommandHandlers(command_controller) {
_.each(handlers, function(handler, handler_command) {
command_controller.addHandler(handler_command, handler);
});
};
| JavaScript | 0 | @@ -5558,32 +5558,369 @@
%7D);%0A %7D,%0A%0A%0A
+ INVITE: function(command) %7B%0A var time = command.getServerTime();%0A%0A this.emit('invite', %7B%0A nick: command.nick,%0A ident: command.ident,%0A hostname: command.hostname,%0A invited: command.params%5B0%5D,%0A channel: command.params%5B1%5D,%0A time: time%0A %7D);%0A %7D,%0A%0A%0A
RPL_INVITING
|
330ce166d7a701c7a47a3dfc9354835685bd9371 | Check If Pagination Is Supported | js/tasks/LayerInfoTask.js | js/tasks/LayerInfoTask.js | /*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */
/*
| Copyright 2015 ESRI (UK) Limited
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
/**
* Execute the Query Task to a Layer
*/
define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"],
function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) {
var taskOutput = function LayerInfoTask(props) {
this.properties = props;
this.getLayerInfo = function () {
var _this = this, result = new Deferred(), featureLayer;
// Need to also get the symbology for each layer
featureLayer = new FeatureLayer(_this.properties.serviceUrl);
featureLayer.on("error", function (err) {
result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId });
});
featureLayer.on("load", function (data) {
var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity };
if (props.layerRenderer !== undefined && props.layerRenderer !== null) {
layerInf.renderer = jsonUtils.fromJson(props.layerRenderer);
}
else {
layerInf.renderer = data.layer.renderer;
}
_this.queryLayer(data.layer.maxRecordCount).then(function (res) {
result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl });
});
});
return result.promise;
};
this.getUnits = function (distanceUnits) {
switch (distanceUnits) {
case "m":
return Units.MILES;
case "km":
return Units.KILOMETERS;
case "me":
return Units.METERS;
default:
return Units.MILES;
}
};
this.queryLayer = function (maxRecords) {
var _this = this, result = new Deferred(), query, queryTask, geom, searchradius;
searchradius = parseFloat(_this.properties.searchRadius);
if (searchradius > 0) {
geom = new Circle({
center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y],
geodesic: true,
radius: searchradius,
radiusUnit: _this.getUnits(_this.properties.distanceUnits)
});
}
else {
geom = _this.properties.currentPoint;
}
// Use the current location and buffer the point to create a search radius
query = new Query();
queryTask = new QueryTask(_this.properties.serviceUrl);
query.where = "1=1"; // Get everything
query.geometry = geom;
query.outFields = ["*"];
query.returnGeometry = true;
query.outSpatialReference = _this.properties.currentPoint.spatialReference;
query.num = maxRecords || 1000;
queryTask.execute(query, function (features) {
result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId});
},
function (error) {
result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId });
});
return result.promise;
};
this.execute = function () {
return this.getLayerInfo();
};
};
return taskOutput;
}); | JavaScript | 0 | @@ -1773,18 +1773,54 @@
pacity %7D
+,%0A maxRecordCount
;%0A
-
%0A
@@ -2095,32 +2095,315 @@
%7D%0A%0A
+ // Check if layer supports pagination%0A if (_this._supportsPagination(data.layer)) %7B%0A maxRecordCount = data.layer.maxRecordCount;%0A %7D%0A else %7B%0A maxRecordCount = %22foo%22;%0A %7D%0A%0A
@@ -2690,32 +2690,32 @@
%7D);%0A%0A
-
retu
@@ -2737,32 +2737,516 @@
se;%0A %7D;%0A%0A
+ this. _supportsPagination = function (source) %7B %0A // check if featurelayer supports pagination remove at 3.14 %0A var supported = false; %0A if (source.featureLayer) %7B %0A // supports pagination %0A if (source.advancedQueryCapabilities && source.advancedQueryCapabilities.supportsPagination) %7B %0A supported = true; %0A %7D %0A %7D %0A return supported; %0A %7D;%0A%0A
this.get
|
d6ca7cb6c5103bf8a8c9fafb932adf6ef3cd48d3 | replace unused code with comment | js/views/ReadReactView.js | js/views/ReadReactView.js | // Copyright (C) 2012-present, Polis Technology Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
var eb = require("../eventBus");
var Handlebones = require("handlebones");
var template = require("../tmpl/readReactView");
var CommentModel = require("../models/comment");
var VoteView = require('../views/vote-view');
var PolisFacebookUtils = require('../util/facebookButton');
// var serverClient = require("../stores/polis");
// var Utils = require("../util/utils");
// var iOS = Utils.isIos();
var SHOULD_PROMPT_FOR_FB = false;
var cardNames = ["w","x","y","z"];
module.exports = Handlebones.ModelView.extend({
name: "readReactView",
template: template,
events: {
"click #fbNotNowBtn": "fbNotNowBtn",
"click #fbNoUseBtn": "fbNoUseBtn",
"click #fbConnectBtn": "fbConnectBtn",
// "click #passButton": "participantPassed",
},
fbNotNowBtn: function() {
// this.model.set("response", "fbnotnow");
},
fbNoUseBtn: function() {
// this.model.set("response", "fbnouse");
},
fbConnectBtn: function() {
PolisFacebookUtils.connect().then(function() {
// that.model.set("response", "fbdone");
location.reload();
}, function(err) {
// alert("facebook error");
});
},
context: function() {
var ctx = Handlebones.ModelView.prototype.context.apply(this, arguments);
// ctx.iOS = iOS;
var hasFacebookAttached = window.userObject.hasFacebook;
var voteCountForFacebookPrompt = 3;
ctx.promptFacebook = SHOULD_PROMPT_FOR_FB && !hasFacebookAttached && !this.model.get("response") && this.model.get("voteCount") > voteCountForFacebookPrompt;
return ctx;
},
onVoteViewClick: function() {
var that = this;
var v = this.voteViews.shift();
this.voteViews.push(v);
var $cards = this.$el.find(".animVoteCard");
// var $c = $cards.shift();
// $cards.push($c);
// var $el;
var $c = $cards[0];
$c.remove();
$("#cardStack").append($c);
// $($cards[0]).find('.comment_shower').css('visibility', 'hidden'); // css("background-color", "green");
this.animateCardToPosition($($cards[0]), 'A');
// setTimeout(function() {
// }, 500);
$($cards[0]).hide();
// $($cards[0]).fadeOut();
this.animateCardToPosition($($cards[1]), 0);
this.animateCardToPosition($($cards[2]), 1);
this.animateCardToPosition($($cards[3]), 2);
setTimeout(function() {
that.animateCardToPosition($($cards[0]), 3);
$($cards[3]).fadeIn();
// $($cards[0]).find('.comment_shower').css('visibility', 'visible'); // css("background-color", "white");
}, 1000);
this.commentModel.set({
showHereIsNextStatement: true,
});
// v.animateOut(function() {
// $el = $(v.el).remove();
// // $el = v.$el;
// $("#cardStack").append($el);
// // return v.gotoBackOfStack();
// for (var i = 0; i < that.voteViews.length; i++) {
// var vi = that.voteViews[i];
// that.animateCardToPosition(vi, i);
// }
// });
this.voteViews.forEach(function(vv, i) {
if (i === 0) {
vv.enableButtons();
} else {
vv.disableButtons();
}
});
},
animateCardToPosition: function($card, position) {
// var $card = $("#card_" + cardNames[cardIndex]);
// this.position = i;
if (position === 0) {
$card.attr("aria-hidden", false);
} else {
$card.attr("aria-hidden", true);
}
var classes = [
"voteViewCardPos_0",
"voteViewCardPos_1",
"voteViewCardPos_2",
"voteViewCardPos_3",
"voteViewCardPos_A",
"voteViewCardPos_D",
"voteViewCardPos_P",
];
var newClass = "voteViewCardPos_" + position;
var classesToRemove = classes.filter(function(c) {
return c !== newClass;
});
$card.removeClass(classesToRemove.join(" ")).addClass(newClass);
// setTimeout(function() {
// this.model.set({ // trigger a render
// foo: i,
// });
// }, 1000);
$card.fadeIn();
},
initialize: function(options) {
Handlebones.ModelView.prototype.initialize.apply(this, arguments);
var that = this;
this.model = options.model;
this.voteViews = [];
var commentModel = this.commentModel = new CommentModel();
[0,1,2,3].forEach(function(i) {
that.voteViews.push(that.addChild(new VoteView({
firstCommentPromise: options.firstCommentPromise,
serverClient: options.serverClient,
model: commentModel,
position: i,
orig_position: ['a','b','c'][i],
css_position: "absolute",
conversationModel: options.conversationModel,
votesByMe: options.votesByMe,
is_public: options.is_public,
isSubscribed: options.isSubscribed,
onVote: that.onVoteViewClick.bind(that),
conversation_id: options.conversation_id,
shouldPoll: false, // let the dummy view poll since there's only one.
})));
});
this.voteView_w = this.voteViews[0];
this.voteView_x = this.voteViews[1];
this.voteView_y = this.voteViews[2];
this.voteView_z = this.voteViews[3];
// hidden dummy view used to affect flow since animated views are position:absolute
// (make sure screen readers cant see this)
this.voteView_dummy = that.addChild(new VoteView({
firstCommentPromise: options.firstCommentPromise,
serverClient: options.serverClient,
model: commentModel,
position: 0,
orig_position: 'y',
hidden: true,
css_position: "relative",
conversationModel: options.conversationModel,
votesByMe: options.votesByMe,
is_public: options.is_public,
isSubscribed: options.isSubscribed,
onVote: that.onVoteViewClick.bind(that),
conversation_id: options.conversation_id,
shouldPoll: true,
}));
eb.on("vote", function() {
// that.model.set("voteCount", (that.model.get("voteCount") + 1) || 1);
});
}
});
| JavaScript | 0.000002 | @@ -1057,25 +1057,26 @@
se;%0A
-var cardN
+// Card n
ames
-= %5B
+are
%22w%22,
@@ -1086,18 +1086,16 @@
,%22y%22,%22z%22
-%5D;
%0A%0Amodule
|
8e44d33c1e97ad5caa118f5cfeb6886bbe2a2e91 | Remove buttonMarkup AMD-dependency. | js/widgets/collapsible.js | js/widgets/collapsible.js | //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Creates collapsible content blocks.
//>>label: Collapsible
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css
define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.buttonMarkup", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
collapsedIcon: "plus",
expandedIcon: "minus",
iconpos: "left",
theme: null,
contentTheme: null,
inset: true,
corners: true,
mini: false
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ),
collapsibleClasses = "";
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "a" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon;
// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon;
// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos;
// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
if ( collapsibleSet.jqmData( "inset" ) !== undefined ) {
o.inset = collapsibleSet.jqmData( "inset" );
} else {
o.inset = true;
}
// Set corners for individual collapsibles to false when in a collapsible-set
o.corners = false;
// Gets the preference for mini in the set
if ( !o.mini ) {
o.mini = collapsibleSet.jqmData( "mini" );
}
} else {
// get inherited theme if not a set and no theme has been set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "a" );
}
}
if ( !!o.inset ) {
collapsibleClasses += " ui-collapsible-inset";
if ( !!o.corners ) {
collapsibleClasses += " ui-corner-all" ;
}
}
if ( o.contentTheme ) {
collapsibleClasses += " ui-collapsible-themed-content";
collapsibleContent.addClass( "ui-body-" + o.contentTheme );
}
if ( collapsibleClasses !== "" ) {
collapsible.addClass( collapsibleClasses );
}
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.addClass( "ui-btn ui-btn-" + o.theme +
" ui-icon ui-icon-" + o.collapsedIcon + " ui-btn-icon-" + o.iconpos +
( o.mini ? " ui-mini" : "" ) );
$.extend( this, {
_collapsibleHeading: collapsibleHeading,
_collapsibleContent: collapsibleContent
});
//events
this._on({
"expand": "_handleExpandCollapse",
"collapse": "_handleExpandCollapse"
});
this._on( collapsibleHeading, {
"tap": function(/* event */) {
collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
},
"click": function( event ) {
var type = collapsibleHeading.hasClass( "ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
event.stopPropagation();
}
});
this._setOptions( this.options );
},
_handleExpandCollapse: function( event ) {
var isCollapse,
o = this.options;
if ( !event.isDefaultPrevented() ) {
isCollapse = ( event.type === "collapse" );
event.preventDefault();
this._collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
.end()
.find( "a" ).first().removeClass( $.mobile.activeBtnClass );
this.element.toggleClass( "ui-collapsible-collapsed", isCollapse );
this._collapsibleContent
.toggleClass( "ui-collapsible-content-collapsed", isCollapse )
.attr( "aria-hidden", isCollapse )
.trigger( "updatelayout" );
}
},
_setOptions: function( o ) {
var $el = this.element;
if ( o.collapsed !== undefined ) {
$el.trigger( o.collapsed ? "collapse" : "expand" );
}
return this._super( o );
}
});
$.mobile.collapsible.initSelector = ":jqmData(role='collapsible')";
//auto self-init widgets
$.mobile._enhancer.add( "mobile.collapsible" );
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
| JavaScript | 0 | @@ -328,41 +328,8 @@
et%22,
- %22../jquery.mobile.buttonMarkup%22,
%22..
|
39525ee2b1b610b0cc472dde306e0caf390fb150 | fix section titles in experimental tab | src/clincoded/static/components/variant_central/interpretation/functional.js | src/clincoded/static/components/variant_central/interpretation/functional.js | 'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var globals = require('../../globals');
var RestMixin = require('../../rest').RestMixin;
var vciFormHelper = require('./shared/form');
var CurationInterpretationForm = vciFormHelper.CurationInterpretationForm;
var CompleteSection = require('./shared/complete_section').CompleteSection;
var panel = require('../../../libs/bootstrap/panel');
var form = require('../../../libs/bootstrap/form');
var PanelGroup = panel.PanelGroup;
var Panel = panel.Panel;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var InputMixin = form.InputMixin;
// Display the curator data of the curation data
var CurationInterpretationFunctional = module.exports.CurationInterpretationFunctional = React.createClass({
mixins: [RestMixin],
propTypes: {
data: React.PropTypes.object,
interpretation: React.PropTypes.object,
updateInterpretationObj: React.PropTypes.func,
href_url: React.PropTypes.object
},
getInitialState: function() {
return {
clinvar_id: null,
interpretation: this.props.interpretation
};
},
componentWillReceiveProps: function(nextProps) {
this.setState({interpretation: nextProps.interpretation});
},
render: function() {
return (
<div className="variant-interpretation functional">
{this.state.interpretation ?
<CompleteSection interpretation={this.state.interpretation} tabName="experimental" updateInterpretationObj={this.props.updateInterpretationObj} />
: null}
<PanelGroup accordion><Panel title="Does variant result in LOF?" panelBodyClassName="panel-wide-content" open>
{(this.props.data && this.state.interpretation) ?
<div className="row">
<div className="col-sm-12">
<CurationInterpretationForm renderedFormContent={criteriaGroup1} criteria={['PM1']}
evidenceData={null} evidenceDataUpdated={true}
formDataUpdater={criteriaGroup1Update} variantUuid={this.props.data['@id']}
interpretation={this.state.interpretation} updateInterpretationObj={this.props.updateInterpretationObj} />
</div>
</div>
: null}
</Panel></PanelGroup>
<PanelGroup accordion><Panel title="Is LOF known mechanism for disease of interest?" panelBodyClassName="panel-wide-content" open>
{(this.props.data && this.state.interpretation) ?
<div className="row">
<div className="col-sm-12">
<CurationInterpretationForm renderedFormContent={criteriaGroup2} criteria={['BS3', 'PS3']}
evidenceData={null} evidenceDataUpdated={true} criteriaCrossCheck={[['BS3', 'PS3']]}
formDataUpdater={criteriaGroup2Update} variantUuid={this.props.data['@id']} formChangeHandler={criteriaGroup2Change}
interpretation={this.state.interpretation} updateInterpretationObj={this.props.updateInterpretationObj} />
</div>
</div>
: null}
</Panel></PanelGroup>
</div>
);
}
});
// code for rendering of this group of interpretation forms
var criteriaGroup1 = function() {
let criteriaList1 = ['PM1'], // array of criteria code handled subgroup of this section
hiddenList1 = [false]; // array indicating hidden status of explanation boxes for above list of criteria codes
return (
<div>
{vciFormHelper.evalFormSectionWrapper.call(this,
vciFormHelper.evalFormNoteSectionWrapper.call(this, criteriaList1),
vciFormHelper.evalFormDropdownSectionWrapper.call(this, criteriaList1),
vciFormHelper.evalFormExplanationSectionWrapper.call(this, criteriaList1, hiddenList1, null, null),
false
)}
</div>
);
};
// code for updating the form values of interpretation forms upon receiving
// existing interpretations and evaluations
var criteriaGroup1Update = function(nextProps) {
vciFormHelper.updateEvalForm.call(this, nextProps, ['PM1'], null);
};
// code for rendering of this group of interpretation forms
var criteriaGroup2 = function() {
let criteriaList1 = ['BS3', 'PS3'], // array of criteria code handled subgroup of this section
hiddenList1 = [false, true]; // array indicating hidden status of explanation boxes for above list of criteria codes
return (
<div>
{vciFormHelper.evalFormSectionWrapper.call(this,
vciFormHelper.evalFormNoteSectionWrapper.call(this, criteriaList1),
vciFormHelper.evalFormDropdownSectionWrapper.call(this, criteriaList1),
vciFormHelper.evalFormExplanationSectionWrapper.call(this, criteriaList1, hiddenList1, null, null),
false
)}
</div>
);
};
// code for updating the form values of interpretation forms upon receiving
// existing interpretations and evaluations
var criteriaGroup2Update = function(nextProps) {
vciFormHelper.updateEvalForm.call(this, nextProps, ['BS3', 'PS3'], null);
};
// code for handling logic within the form
var criteriaGroup2Change = function(ref, e) {
// Both explanation boxes for both criteria of each group must be the same
vciFormHelper.shareExplanation.call(this, ref, ['BS3', 'PS3']);
};
| JavaScript | 0 | @@ -1738,35 +1738,36 @@
le=%22
-Does variant result in LOF?
+Hotspot or functional domain
%22 pa
@@ -2624,55 +2624,28 @@
le=%22
-Is LOF known mechanism for disease of interest?
+Experimental Studies
%22 pa
|
c4df78aa19c2aae208fd1f668c9a3535a27b4ecc | Disable PSI reporting for now | extension/src/browser_action/popup.js | extension/src/browser_action/popup.js | /*
Copyright 2020 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const API_URL = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?';
const FE_URL = 'https://developers.google.com/speed/pagespeed/insights/';
let encodedUrl = '';
let psiURL = '';
let resultsFetched = false;
let localMetrics = {};
// Hash the URL and return a numeric hash as a String to be used as the key
function hashCode(str) {
let hash = 0;
if (str.length == 0) {
return "";
}
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32bit integer
}
return hash.toString();
}
async function fetchAPIResults(url) {
if (resultsFetched) { return; }
const query = [
'url=url%3A' + url
// 'key=' + API_KEY,
].join('&');
const queryURL = API_URL + query;
try {
const response = await fetch(queryURL);
const json = await response.json();
createPSITemplate(json);
} catch (err) {
const el = document.getElementById('report');
el.innerHTML = `We were unable to process your request.`;
}
}
function createPSITemplate(result) {
const experience = result.loadingExperience;
const metrics = experience.metrics;
const overall_category = experience.overall_category;
const fcp = metrics.FIRST_CONTENTFUL_PAINT_MS;
const fid = metrics.FIRST_INPUT_DELAY_MS;
const fcp_template = buildDistributionTemplate(fcp, 'First Contentful Paint (FCP)');
const fid_template = buildDistributionTemplate(fid, 'First Input Delay (FID)');
const link_template = buildPSILink();
const tmpl = `<h1>Origin Performance (${overall_category})</h1> ${fcp_template} ${fid_template} ${link_template}`;
const el = document.getElementById('report');
el.innerHTML = tmpl;
// TODO: Implement per-tab/URL report caching scheme
resultsFetched = true;
}
/**
*
* Construct a WebVitals.js metrics template for display at the
* top of the pop-up. Consumes a custom metrics object provided
* by vitals.js.
* @param {Object} metrics
* @returns
*/
function buildLocalMetricsTemplate(metrics) {
return `
<div class="lh-audit-group lh-audit-group--metrics">
<div class="lh-audit-group__header"><span class="lh-audit-group__title">Metrics</span></div>
<div class="lh-columns">
<div class="lh-column">
<div class="lh-metric lh-metric--${metrics.lcp.pass ? 'pass':'fail'}">
<div class="lh-metric__innerwrap">
<span class="lh-metric__title">Largest Contentful Paint <span class="lh-metric-state">${metrics.lcp.final ? '(final)' : '(not final)'}</span></span>
<div class="lh-metric__value">${(metrics.lcp.value/1000).toFixed(2)} s</div>
</div>
</div>
<div class="lh-metric lh-metric--${metrics.fid.pass ? 'pass':'fail'}">
<div class="lh-metric__innerwrap">
<span class="lh-metric__title">First Input Delay <span class="lh-metric-state">${metrics.fid.final ? '(final)' : '(not final)'}</span></span>
<div class="lh-metric__value">${metrics.fid.value.toFixed(2)} ms</div>
</div>
</div>
<div class="lh-metric lh-metric--${metrics.cls.pass ? 'pass':'fail'}">
<div class="lh-metric__innerwrap">
<span class="lh-metric__title">Cumulative Layout Shift <span class="lh-metric-state">${metrics.cls.final ? '(final)' : '(not final)'}</span></span>
<div class="lh-metric__value">${metrics.cls.value.toFixed(3)} </div>
</div>
</div>
</div>
</div>
</div>`;
}
/**
*
* Render a WebVitals.js metrics table in the pop-up window
* @param {Object} metrics
* @returns
*/
function renderLocalMetricsTemplate(metrics) {
// if (metrics === undefined || metrics.lcp === undefined) { return; }
const el = document.getElementById('local-metrics');
el.innerHTML = buildLocalMetricsTemplate(metrics);
}
function buildDistributionTemplate(metric, label) {
return `<div class="field-data">
<div class="metric-wrapper lh-column">
<div class="lh-metric">
<div class="field-metric ${metric.category.toLowerCase()} lh-metric__innerwrap">
<span class="metric-description">${label}</span>
<div class="metric-value lh-metric__value">${formatDisplayValue(label, metric.percentile)}</div></div>
<div class="metric-chart">
<div class="bar fast" style="flex-grow:
${Math.floor(metric.distributions[0].proportion * 100)};">
${Math.floor(metric.distributions[0].proportion * 100)}%</div>
<div class="bar average" style="flex-grow:
${Math.floor(metric.distributions[1].proportion * 100)};">
${Math.floor(metric.distributions[1].proportion * 100)}%</div>
<div class="bar slow" style="flex-grow:
${Math.floor(metric.distributions[2].proportion * 100)};">
${Math.floor(metric.distributions[2].proportion * 100)}%</div>
</div></div>
</div>
</div> `;
}
function buildPSILink() {
return `<br><a href='${FE_URL}?url=${encodedUrl}' target='_blank'>
View Report on PageSpeed Insights</a>`;
}
/**
*
* Format PSI API metric values
* @param {String} metricName
* @param {Number} metricValueMs
* @returns
*/
function formatDisplayValue(metricName, metricValueMs) {
if (metricValueMs === undefined) {
return '';
}
if (metricName === 'First Input Delay (FID)') {
return Number(metricValueMs.toFixed(0)) + ' ms';
} else {
return Number((metricValueMs / 1000).toFixed(1)) + ' s';
}
};
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
let thisTab = tabs[0];
console.log(`popup: PSI API will be queried for URL ${thisTab.url}`);
fetchAPIResults(thisTab.url);
// Retrieve the stored latest metrics
if (thisTab.url) {
let key = hashCode(thisTab.url);
chrome.storage.local.get(key, result => {
renderLocalMetricsTemplate(result[key]);
});
}
}); | JavaScript | 0 | @@ -6284,24 +6284,81 @@
tabs%5B0%5D;%0A
+ // TODO: Re-enable PSI support once LCP, CLS land%0A //
console.log
@@ -6419,16 +6419,19 @@
%7D%60);%0A
+ //
fetchAP
@@ -6449,24 +6449,25 @@
isTab.url);%0A
+%0A
// Retri
|
f2000d0d79c513e099f9cfc15b701d29d0fcd1fa | Fix Timeago Preact Type (#27113) | extensions/amp-timeago/0.2/timeago.js | extensions/amp-timeago/0.2/timeago.js | /**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {createElement, useEffect, useRef, useState} from '../../../src/preact';
import {timeago} from '../../../third_party/timeagojs/timeago';
import {useResourcesNotify} from '../../../src/preact/utils';
/**
* @param {!JsonObject} props
* @return {Preact.Renderable}
*/
export function Timeago(props) {
const {
'datetime': datetime,
'locale': locale,
'cutoff': cutoff,
'cutoffText': cutoffText,
} = props;
const [timestamp, setTimestamp] = useState(null);
const ref = useRef(null);
useEffect(() => {
const node = ref.current;
const observer = new IntersectionObserver(entries => {
const last = entries[entries.length - 1];
if (last.isIntersecting) {
setTimestamp(
getFuzzyTimestampValue(datetime, locale, cutoffText, cutoff)
);
}
});
if (node) {
observer.observe(node);
}
return () => observer.disconnect();
}, [datetime, locale, cutoff, cutoffText]);
useResourcesNotify();
return createElement('time', {datetime, ref}, timestamp);
}
/**
* @param {string} datetime
* @param {string} locale
* @param {string} cutoffText
* @param {number=} opt_cutoff
* @return {string}
*/
function getFuzzyTimestampValue(datetime, locale, cutoffText, opt_cutoff) {
if (!opt_cutoff) {
return timeago(datetime, locale);
}
const elDate = new Date(datetime);
const secondsAgo = Math.floor((Date.now() - elDate.getTime()) / 1000);
if (secondsAgo > opt_cutoff) {
return cutoffText;
}
return timeago(datetime, locale);
}
| JavaScript | 0 | @@ -881,16 +881,19 @@
%7BPreact
+Def
.Rendera
|
8bfe7301debc79f50edf3c5fa59e84f17a8d4dc1 | remove Meteor code that is no longer needed | plugin/index.js | plugin/index.js | import BabelInlineImportHelper from './helper';
export default function({ types: t }) {
class BabelInlineImport {
constructor() {
return {
visitor: {
ImportDeclaration: {
exit(path, state) {
const givenPath = path.node.source.value;
let reference = state && state.file && state.file.opts.filename;
const extensions = state && state.opts && state.opts.extensions;
if (BabelInlineImportHelper.shouldBeInlined(givenPath, extensions)) {
if (path.node.specifiers.length > 1) {
throw new Error(`Destructuring inlined import is not allowed. Check the import statement for '${givenPath}'`);
}
// Here we detect the use of Meteor by checking global.meteorBabelHelpers
if(global.meteorBabelHelpers && BabelInlineImportHelper.hasRoot(reference)) {
reference = BabelInlineImportHelper.transformRelativeToRootPath(reference);
}
const id = path.node.specifiers[0].local.name;
const content = BabelInlineImportHelper.getContents(givenPath, reference);
const variable = t.variableDeclarator(t.identifier(id), t.stringLiteral(content));
path.replaceWith({
type: 'VariableDeclaration',
kind: 'const',
declarations: [variable],
leadingComments: [
{
type: 'CommentBlock',
value: ` babel-plugin-inline-import '${givenPath}' `
}
]
});
}
}
}
}
};
}
}
return new BabelInlineImport();
}
| JavaScript | 0.000014 | @@ -733,305 +733,8 @@
%7D%0A%0A
- // Here we detect the use of Meteor by checking global.meteorBabelHelpers%0A if(global.meteorBabelHelpers && BabelInlineImportHelper.hasRoot(reference)) %7B%0A reference = BabelInlineImportHelper.transformRelativeToRootPath(reference);%0A %7D%0A%0A
|
ee2bb68b1f8fc4bc06f6f67a26ae8489f947cff0 | Remove hooks from echo plugin. | plugins/echo.js | plugins/echo.js | /*
* Echo plugin
* - echo: Repeats whatever is passed with the command
*/
var Echo = function() {
this.commands = ['echo'];
this.hooks = [];
};
Echo.prototype.echo = function(bot, to, from, msg, callback) {
bot.say(to, msg);
callback();
};
exports.Plugin = Echo;
| JavaScript | 0 | @@ -128,27 +128,8 @@
'%5D;%0A
- this.hooks = %5B%5D;%0A
%7D;%0A%0A
@@ -230,16 +230,17 @@
();%0A%7D;%0A%0A
+%0A
exports.
|
3dcba911435289c315d0727e969eec221bc7223e | Remove the smoketest image lookup | extras/build.gnome.org/controllers.js | extras/build.gnome.org/controllers.js | (function(exports) {
'use strict';
var bgoControllers = angular.module('bgoControllers', []);
var taskNames = ['build', 'smoketest', 'integrationtest', 'applicationstest'];
var ROOT = '/continuous/buildmaster/';
bgoControllers.controller('ContinuousStatusCtrl', function($scope, $http) {
$http.get(ROOT + 'results/tasks/build/build/meta.json').success(function(data) {
$scope.status = data.success ? 'good' : 'bad';
$scope.buildName = data.buildName;
});
});
bgoControllers.controller('ContinuousBuildViewCtrl', function($scope, $http, $routeParams) {
var buildName = $routeParams.buildName;
$scope.buildName = buildName;
var buildRoot = ROOT + 'builds/' + buildName + '/';
var tasks = [];
taskNames.forEach(function(taskName) {
$http.get(buildRoot + taskName + '/meta.json').success(function(data) {
// Mangle the data a bit so we can render it better
data['name'] = taskName;
tasks.push(data);
if (taskName == 'smoketest')
$scope.smoketestImage = getUrl(data['path'] + '/work-gnome-continuous-x86_64-runtime/screenshot-final.png');
});
});
$scope.tasks = tasks;
var apps = [];
$http.get(buildRoot + 'applicationstest/apps.json').success(function(data) {
var apps = data['apps'];
apps.forEach(function(app) {
// Mangle the data a bit
app.name = app.id; /* XXX */
app.status = (app.state == "success") ? 'good' : 'bad';
// XXX -- this should probably be in the template
if (app.icon)
app.icon = ROOT + app.icon;
else
app.icon = '/images/app-generic.png';
app.screenshot = ROOT + app.screenshot;
});
$scope.apps = apps;
});
});
bgoControllers.controller('ContinuousHomeCtrl', function($scope, $http) {
var builds = [];
// Just get the most recent build for now. We need an
// API to iterate over all the builds.
$http.get(ROOT + 'results/tasks/build/build/meta.json').success(function(data) {
builds.push(data);
});
$scope.builds = builds;
$http.get(ROOT + 'autobuilder-status.json').success(function(status) {
var text;
if (status.running.length > 0)
text = 'Running: ' + status.running.join(' ') + '; load=' + status.systemLoad[0];
else
text = 'Idle, awaiting commits';
$scope.runningState = text;
});
});
})(window);
| JavaScript | 0 | @@ -1068,183 +1068,8 @@
ta);
-%0A%0A if (taskName == 'smoketest')%0A $scope.smoketestImage = getUrl(data%5B'path'%5D + '/work-gnome-continuous-x86_64-runtime/screenshot-final.png');
%0A
|
a24f3943a13caa1d79399b84c70bceb7c22e8c22 | Update testing for CLI | tests/cli.js | tests/cli.js | var assert = require('assert'),
should = require('should'),
childProcess = require('child_process');
describe('cli', function () {
it('should return help instructions', function (done) {
var command = 'sass-lint -h';
childProcess.exec(command, function (err, stdout) {
if (err) {
return done(err);
}
assert(stdout.indexOf('Usage') > 0);
done(null);
});
});
it('should return a version', function (done) {
var command = 'sass-lint -V';
childProcess.exec(command, function (err, stdout) {
if (err) {
return done(err);
}
should(stdout).match(/^[0-9]+.[0-9]+(.[0-9]+)?/);
done(null);
});
});
// Test custom config path
it('should return JSON from a custom config', function (done) {
var command = 'sass-lint -c tests/yml/.color-keyword-errors.yml tests/sass/cli.scss --verbose';
childProcess.exec(command, function (err, stdout) {
if (err) {
return done(err);
}
else {
try {
JSON.parse(stdout);
return done();
}
catch (e) {
return done(new Error('Not JSON'));
}
}
});
});
// Test 0 errors/warnings when rules set to 0 in config
it('output should return no errors/warnings', function (done) {
var command = 'sass-lint -c tests/yml/.json-lint.yml tests/sass/cli.scss --verbose';
childProcess.exec(command, function (err, stdout) {
var result = 0;
if (err) {
return done(err);
}
console.log(stdout.length);
result = stdout.length;
if (result !== 0) {
return done(new Error('warnings/errors were returned'));
}
return done();
});
});
// Test 1 warning when rules set to 0 in config
it('should return a warning', function (done) {
var command = 'sass-lint -c tests/yml/.color-keyword-errors.yml tests/sass/cli.scss --verbose';
childProcess.exec(command, function (err, stdout) {
var result = '';
if (err) {
return done(err);
}
else {
try {
result = JSON.parse(stdout);
}
catch (e) {
return done(new Error('Not JSON'));
}
if (result[0].warningCount === 1 && result[0].errorCount === 0) {
return done();
}
else {
return done(new Error('warnings/errors were expected to be returned but weren\'t'));
}
}
});
});
});
| JavaScript | 0.000001 | @@ -1543,42 +1543,8 @@
%7D%0A
- console.log(stdout.length);%0A
|
08a09fab9cf0485818ab5824f9cb0364f136a138 | throw a new Error | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var webpack = require('webpack');
var jshint = require('gulp-jshint');
var map = require('map-stream');
var bump = require('gulp-bump');
var argv = require('yargs').argv;
//var header = require('gulp-header');
var pkg = require('./package.json');
var banner = '/*! <%= pkg.name %> - v<%= pkg.version %> - '
+ '<%= new Date().toISOString() %>\n'
+ '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>'
+ '* Copyright (c) <%= new Date().getFullYear() %> <%= pkg.author.name %>;'
+ ' Licensed <%= pkg.license %> */'
var sjclSrc = [
'src/js/sjcl/core/sjcl.js',
'src/js/sjcl/core/aes.js',
'src/js/sjcl/core/bitArray.js',
'src/js/sjcl/core/codecString.js',
'src/js/sjcl/core/codecHex.js',
'src/js/sjcl/core/codecBase64.js',
'src/js/sjcl/core/codecBytes.js',
'src/js/sjcl/core/sha256.js',
'src/js/sjcl/core/sha512.js',
'src/js/sjcl/core/sha1.js',
'src/js/sjcl/core/ccm.js',
// 'src/js/sjcl/core/cbc.js',
// 'src/js/sjcl/core/ocb2.js',
'src/js/sjcl/core/hmac.js',
'src/js/sjcl/core/pbkdf2.js',
'src/js/sjcl/core/random.js',
'src/js/sjcl/core/convenience.js',
'src/js/sjcl/core/bn.js',
'src/js/sjcl/core/ecc.js',
'src/js/sjcl/core/srp.js',
'src/js/sjcl-custom/sjcl-ecc-pointextras.js',
'src/js/sjcl-custom/sjcl-secp256k1.js',
'src/js/sjcl-custom/sjcl-ripemd160.js',
'src/js/sjcl-custom/sjcl-extramath.js',
'src/js/sjcl-custom/sjcl-montgomery.js',
'src/js/sjcl-custom/sjcl-validecc.js',
'src/js/sjcl-custom/sjcl-ecdsa-canonical.js',
'src/js/sjcl-custom/sjcl-ecdsa-der.js',
'src/js/sjcl-custom/sjcl-ecdsa-recoverablepublickey.js',
'src/js/sjcl-custom/sjcl-jacobi.js'
];
gulp.task('concat-sjcl', function() {
return gulp.src(sjclSrc)
.pipe(concat('sjcl.js'))
.pipe(gulp.dest('./build/'));
});
gulp.task('build', [ 'concat-sjcl' ], function(callback) {
webpack({
cache: true,
entry: './src/js/ripple/index.js',
output: {
library: 'ripple',
path: './build/',
filename: [ 'ripple-', '.js' ].join(pkg.version)
},
}, callback);
});
gulp.task('bower-build', [ 'build' ], function(callback) {
return gulp.src([ './build/ripple-', '.js' ].join(pkg.version))
.pipe(rename('ripple.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('bower-build-min', [ 'build-min' ], function(callback) {
return gulp.src([ './build/ripple-', '-min.js' ].join(pkg.version))
.pipe(rename('ripple-min.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('bower-build-debug', [ 'build-debug' ], function(callback) {
return gulp.src([ './build/ripple-', '-debug.js' ].join(pkg.version))
.pipe(rename('ripple-debug.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('bower-version', function() {
gulp.src('./dist/bower.json')
.pipe(bump({version: pkg.version}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('version-bump', function() {
if (!argv.type) {
throw "No type found, pass it in using the --type argument";
}
gulp.src('./package.json')
.pipe(bump({type:argv.type}))
.pipe(gulp.dest('./'));
});
gulp.task('version-beta', function() {
gulp.src('./package.json')
.pipe(bump({version: pkg.version+'-beta'}))
.pipe(gulp.dest('./'));
});
gulp.task('build-min', [ 'build' ], function(callback) {
return gulp.src([ './build/ripple-', '.js' ].join(pkg.version))
.pipe(uglify())
.pipe(rename([ 'ripple-', '-min.js' ].join(pkg.version)))
.pipe(gulp.dest('./build/'));
});
gulp.task('build-debug', [ 'concat-sjcl' ], function(callback) {
webpack({
cache: true,
entry: './src/js/ripple/index.js',
output: {
library: 'ripple',
path: './build/',
filename: [ 'ripple-', '-debug.js' ].join(pkg.version)
},
debug: true,
devtool: 'eval'
}, callback);
});
gulp.task('lint', function() {
gulp.src('src/js/ripple/*.js')
.pipe(jshint())
.pipe(map(function(file, callback) {
if (!file.jshint.success) {
console.log('\nIn', file.path);
file.jshint.results.forEach(function(err) {
if (err && err.error) {
var col1 = err.error.line + ':' + err.error.character;
var col2 = '[' + err.error.reason + ']';
var col3 = '(' + err.error.code + ')';
while (col1.length < 8) {
col1 += ' ';
}
console.log(' ' + [ col1, col2, col3 ].join(' '));
}
});
}
callback(null, file);
}));
});
gulp.task('watch', function() {
gulp.watch('src/js/ripple/*', [ 'build-debug' ]);
});
gulp.task('default', [ 'concat-sjcl', 'build', 'build-debug', 'build-min' ]);
gulp.task('bower', ['bower-build', 'bower-build-min', 'bower-build-debug', 'bower-version']);
| JavaScript | 0.000001 | @@ -2984,16 +2984,26 @@
throw
+new Error(
%22No type
@@ -3047,16 +3047,17 @@
rgument%22
+)
;%0A %7D%0A
|
6df68ac20aa0214dce10023adb81adccf6bf8e34 | Disable coverage in tests until I figure out why it's failing on Windows | Gulpfile.js | Gulpfile.js | var gulp = require("gulp");
var typescript = require("gulp-typescript");
var mocha = require("gulp-mocha");
var cover = require("gulp-coverage");
gulp.task("tsc-src", function() {
return gulp.src(["./src/*.ts"])
.pipe(typescript())
.js
.pipe(gulp.dest("./bin/src"));
});
gulp.task("tsc-test", function() {
return gulp.src(["./test/*.ts"])
.pipe(typescript())
.js
.pipe(gulp.dest("./bin/test"));
});
gulp.task("tsc", ["tsc-src", "tsc-test"]);
gulp.task("test", ["tsc"], function() {
return gulp.src("./bin/test/*.js", { read: false })
.pipe(cover.instrument({
pattern: ['bin/src/*.js', 'bin/src/**/*.js'],
debugDirectory: 'debug'
}))
.pipe(mocha({ reporter: "spec"}))
.pipe(cover.gather())
.pipe(cover.format())
.pipe(gulp.dest("./cover"));
});
gulp.task("watch-src", ["tsc-src"], function() {
return gulp.watch(["src/*", "src/**/*"], ["tsc-src"]);
});
gulp.task("watch-test", ["tsc-test"], function() {
return gulp.watch(["test/*", "test/**/*"], ["tsc-test"]);
});
gulp.task("watch", ["watch-src", "watch-test"]);
gulp.task("default", ["test"]);
| JavaScript | 0.000001 | @@ -591,32 +591,34 @@
alse %7D)%0A
+//
.pipe(cover.inst
@@ -630,24 +630,26 @@
t(%7B%0A
+//
pattern:
@@ -690,24 +690,26 @@
'%5D,%0A
+//
debugDir
@@ -732,16 +732,18 @@
+//
%7D))%0A
@@ -779,16 +779,17 @@
spec%22%7D))
+;
%0A
@@ -781,32 +781,34 @@
ec%22%7D));%0A
+/*
.pipe(cover.gath
@@ -875,24 +875,26 @@
%22./cover%22));
+*/
%0A%7D);%0A%0Agulp.t
|
dcba243b58e5e5865c3c54b1e07da41b3ef0357f | Fix build and serve commands | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var exec = require('child_process').exec;
var autoprefixer = require('autoprefixer-core');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var compression = require('compression');
var remarkable = require('gulp-remarkable'); // this doesn't seem to work with gulp-load-plugins
// var header = require('gulp-header');
var hugoServer = 'hugo server --watch --config=./app/config.yaml -s ./app';
var hugoBuild = 'hugo --config=./app/config.yaml --source ./app --verbose=true';
gulp.task('markdown', function() {
return gulp.src('content/**/*.md')
// convert to html
.pipe(remarkable({
preset: 'commonmark',
typographer: true
}))
// insert toc
.pipe($.insert.prepend('<!-- toc -->\n'))
.pipe(toc())
// wrap layout
.pipe($.wrap({ src: 'app/templates/layout.html' }))
.pipe(gulp.dest('.tmp'));
});
gulp.task('styles', function () {
return gulp.src('app/styles/*.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
outputStyle: 'expanded',
precision: 10,
includePaths: ['.'],
}).on('error', $.sass.logError))
.pipe($.postcss([
autoprefixer({ browsers: ['last 2 version', 'android 4', 'ios 7', 'ie 10']})
]))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/styles'))
.pipe($.filter('**/*.css'))
.pipe(reload({ stream: true }));
});
gulp.task('scripts', function () {
return gulp.src('app/scripts/**/*.js')
.pipe($.sourcemaps.init())
.pipe($.babel())
// .pipe($.concat('main.js'))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts/'));
});
gulp.task('clean', require('del').bind(null, ['.tmp', 'dist']));
// starts a server for development
gulp.task('serve', ['markdown', 'styles', 'scripts'], function () {
browserSync({
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
},
middleware: compression()
}
});
// watch for changes and run tasks
// gulp.watch(['app/*.html', 'app/templates/*.html'], ['html', reload]);
// gulp.watch('content/**/*.md', ['markdown', reload]);
gulp.watch('app/scripts/**/*.js', ['scripts', reload]);
gulp.watch('app/styles/**/*.scss', ['styles']); // 'styles' does reload
});
// shortcut for serve
gulp.task('s', ['serve']);
gulp.task('build', ['markdown', 'styles', 'scripts'], function() {
return gulp.src('.tmp/**/*')
.pipe(gulp.dest('dist'))
.pipe($.size({ title: 'build', gzip: true }));
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
| JavaScript | 0 | @@ -475,17 +475,23 @@
.yaml -s
-
+source=
./app';%0A
@@ -547,17 +547,17 @@
--source
-
+=
./app --
|
333f92719cd055ea82fdb491b99130a95ae94eff | fix syntax error | Gulpfile.js | Gulpfile.js | var gulp = require('gulp'),
rimraf = require('rimraf'),
uglify = require('gulp-uglify'),
minifyCss = require('gulp-minify-css'),
ngmin = require('gulp-ngmin'),
useref = require('gulp-useref'),
deploy = require('gulp-gh-pages'),
gif = require('gulp-if'),
es = require('event-stream'),
lr = require('gulp-livereload'),
autoprefixer = require('gulp-autoprefixer'),
saveLicense = require('uglify-save-license');
// Clean public
gulp.task('clean', function (cb) {
rimraf('dist', cb);
});
// Build
gulp.task('default', ['build', 'assets']);
gulp.task('dev', ['default', 'watch']);
gulp.task('watch', function(){
gulp.watch('src/**/*', ['build', 'assets']);
});
gulp.task('build', ['clean'], function () {
var nonVendor = 'scripts/**/*.js';
var assets = useref.assets();
return gulp.src('src/index.html')
.pipe(assets)
.pipe(gif(nonVendor, ngmin()))
.pipe(gif('*.js', uglify({
mangle: false,
preserveComments: saveLicense
})))
.pipe(gif('*.css', autoprefixer('last 2 versions')))
.pipe(gif('*.css', minifyCss()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist'))
.pipe(lr());
});
gulp.task('assets', ['clean'], function () {
return gulp.src([
'src/blackList.json',
'src/favicon.ico',
'src/logo.svg',
'src/opensearch.xml'
'src/README.md'
], {base: 'src'})
.pipe(gulp.dest('dist'))
.pipe(lr());
});
// Deploy
gulp.task('deploy', ['default'], function () {
return gulp.src('dist/**/*')
.pipe(deploy('[email protected]:gulpjs/plugins.git'));
});
| JavaScript | 0.000005 | @@ -1329,16 +1329,17 @@
rch.xml'
+,
%0A 'sr
|
107d22a752d371cb36bf2e39174fea47a25533ba | Refactor `script/build-support.js` | script/build-support.js | script/build-support.js | 'use strict';
/**
* Dependencies.
*/
var fs,
iso6393;
fs = require('fs');
iso6393 = require('../');
/**
* Write.
*/
fs.writeFileSync('Support.md',
'Supported Codes\n' +
'=================\n' +
'\n' +
iso6393.keys().map(function (code) {
return '- ' + code + ': ' + iso6393.get(code).name;
}).join(';\n') +
'.\n'
);
| JavaScript | 0 | @@ -215,24 +215,144 @@
'%5Cn' +%0A%0A
+ /**%0A * A nice table is too long: GitHub won't be able%0A * to render it, so we create a boring list.%0A */%0A%0A
iso6393.
|
c97323cc81c6c61d83216a477aef83bc2148b1f4 | Use === instead of ==. | src/SourceBrowser.Site/Scripts/search.js | src/SourceBrowser.Site/Scripts/search.js | $(document).ready(function () {
var path = window.location.pathname;
var splitPath = path.split('/');
splitPath = splitPath.filter(function (v) { return v !== '' });
if (splitPath.length <= 2)
{
$("#search-form").hide();
}
});
search = {
//Keeps track of whether a search is ongoing.
//We only want to send one query at a time.
isSearching: false,
//Retains the state of the most recent query.
//When we're done searching, we check the text box to see
//if the query has changed.
lastQuery: "",
beginSearch: function () {
if (search.isSearching)
return;
var query = $("#search-box").val();
//If there's no query, just clear everything
if (query == "") {
search.clearSearch();
return;
}
search.lastQuery = query;
//Split path, removing empty entries
var path = window.location.pathname;
var splitPath = path.split('/');
splitPath = splitPath.filter(function (v) { return v !== '' });
//Only search if we're in a repository
if (splitPath.length > 2) {
var username = splitPath[1];
var repository = splitPath[2];
search.searchRepository(username, repository, query);
}
return false;
},
searchRepository: function (username, repository, query) {
data = JSON.stringify({
"username": username,
"repository": repository,
"query": query
});
$.ajax({
type: "POST",
url: "/Search/Repository/",
//TODO: If anyone knows a better way to do this, please share it.
//My Javascript is not strong...
data: "username=" + username + "&repository=" + repository + "&query=" + query,
success: search.handleSuccess,
error: search.handleError
});
},
handleError: function (e) {
search.isSearching = false;
search.checkIfSearchTextChanged();
},
handleSuccess: function (results) {
$("#tree-view").hide();
//If we can't find any results, tell the user.
if (results.length == 0) {
$("#search-results").hide();
$("#no-results").show();
}
else {
$("#no-results").hide();
$("#search-results").show();
var htmlResults = search.buildResults(results);
$("#search-results").empty().append(htmlResults);
$("#search-results a").click(search.handleSearchClick);
}
search.isSearching = false;
search.checkIfSearchTextChanged();
},
buildResults: function (results) {
var htmlResults = "";
for (var i = 0; i < results.length; i++) {
var searchResult = results[i];
var lineNumber = searchResult["LineNumber"];
var link = "/Browse/" + searchResult["Path"] + "#" + lineNumber;
html = "";
html += "<a href='" + link + "'>";
html += "<span>"
html += searchResult["DisplayName"];
html += "</span>";
html += "<span>"
html += searchResult["FullyQualifiedName"];
html += "</span>";
html += "</a>";
htmlResults += html;
}
return htmlResults;
},
//After searching, we need to check to see if the user has typed
//any additional characters into search while we were waiting
//for the server
checkIfSearchTextChanged: function () {
var currentQuery = $("#search-box").val();
if (currentQuery != search.lastQuery)
search.beginSearch();
},
clearSearch: function () {
$("#search-results").hide();
$("#no-results").hide();
$("#tree-view").show();
},
handleSearchClick: function (ex) {
//If we're already on the page, allow the browser to scroll.
var currentPath= window.location.pathname;
var newPath = ex.currentTarget.pathname
if (currentPath== newPath)
return;
//Stop navigation. We'll take it from here.
ex.preventDefault();
var url = ex.currentTarget.href;
var host = ex.currentTarget.host;
var splitByHash = url.split('#');
if(splitByHash.length > 2)
throw "Too many #'s in path";
var newUrl = splitByHash[0];
var lineNumber = Number(splitByHash[1]);
window.History.pushState({ lineNumber: lineNumber }, null, newUrl);
}
}
// Bind to StateChange Event
$(document).ready(function () {
window.History.Adapter.bind(window, 'statechange', handleStateChange);
});
function handleStateChange(e) {
//TODOa
var state = History.getState();
var cleanUrl = state.url;
var data = state.data;
lineNumber = data["lineNumber"];
$.ajax({
type: "GET",
url: cleanUrl,
success: function (args) {
$("#main-content").html(args["SourceCode"]);
scrollToAnchor(lineNumber);
},
error: handlePageLoadError
});
}
function scrollToAnchor(aid) {
var aTag = $("a[name='" + aid + "']");
$('html,body').animate({ scrollTop: aTag.offset().top }, 'fast');
}
function handlePageLoadError(args) {
var errorHtml = "<h2>There was an error processing your request.</h2>";
$("#line-numbers").empty();
$(".source-code").html(errorHtml);
}
$("#search-box").keyup(function () {
search.beginSearch();
});
| JavaScript | 0.000002 | @@ -752,16 +752,17 @@
query ==
+=
%22%22) %7B%0A
@@ -2219,16 +2219,17 @@
ength ==
+=
0) %7B%0A
@@ -4105,16 +4105,18 @@
rentPath
+ =
== newPa
|
44a77c31bc3a1bea2975b860d993454152af43e9 | Update Button.js | lib/Button.js | lib/Button.js | module.exports = require('neoui-react-button');
| JavaScript | 0.000001 | @@ -23,19 +23,11 @@
re('
-neoui-react
+bee
-but
|
27c57adb2bbc18ee186d6fb52534db8a68422f44 | add a simple string diff to the analyse tool | test/analyse.js | test/analyse.js |
var fs = require('fs');
var path = require('path');
var util = require('util');
var datamap = require('./reallife/datamap.json');
var article = require('../lib/article.js');
if (process.argv.length < 3) {
return console.error('node analyse.js key');
}
var href = null;
for (var i = 0, l = datamap.length; i < l; i++) {
if (datamap[i].key === key) {
href = datamap[i].href;
break;
}
}
if (href === null) {
return console.error('Cound not find test file');
}
var key = process.argv[2];
fs.createReadStream(
path.resolve(__dirname, 'reallife', 'source', key + '.html')
).pipe(article(href, function (err, result) {
console.log();
console.log(util.inspect(result, {
colors: true,
depth: Infinity
}));
console.log();
}));
| JavaScript | 0.00001 | @@ -247,24 +247,51 @@
s key');%0A%7D%0A%0A
+var key = process.argv%5B2%5D;%0A
var href = n
@@ -295,16 +295,16 @@
= null;%0A
-
for (var
@@ -503,35 +503,1137 @@
%0A%7D%0A%0A
-var key = process.argv%5B2%5D;%0A
+function highlight(char) %7B%0A return '%5Cx1B%5B7m' + char + '%5Cx1B%5B27m';%0A%7D%0A%0Afunction spaces(n) %7B%0A var s = '';%0A for (var i = 0; i %3C n; i++) %7B%0A s += ' ';%0A %7D%0A return s;%0A%7D%0A%0Afunction alignStrings(a, b) %7B%0A if (a.length %3C b.length) %7B%0A a = spaces(b.length - a.length) + a;%0A %7D else if (b.length %3C a.length) %7B%0A b = spaces(a.length - b.length) + b;%0A %7D%0A%0A return %5Ba, b%5D;%0A%7D%0A%0Afunction stringDiff(labalA, a, labalB, b) %7B%0A var text = alignStrings(%0A labalA + ' (' + (new Buffer(a).length) + ') :',%0A labalB + ' (' + (new Buffer(b).length) + ') :'%0A );%0A var l = Math.max(a.length, b.length);%0A for (var i = 0; i %3C l; i++) %7B%0A if (i %3E= a.length) %7B%0A text%5B0%5D += highlight(' ');%0A %7D else if (i %3E= b.length) %7B%0A text%5B1%5D += highlight(' '); %0A %7D else if (a%5Bi%5D === b%5Bi%5D) %7B%0A text%5B0%5D += a%5Bi%5D;%0A text%5B1%5D += b%5Bi%5D;%0A %7D else %7B%0A text%5B0%5D += highlight(a%5Bi%5D);%0A text%5B1%5D += highlight(b%5Bi%5D);%0A %7D%0A %7D%0A %0A return text.join('%5Cn');%0A%7D%0A%0Afs.readFile(%0A path.resolve(__dirname, 'reallife', 'expected', key + '.json'),%0A function (err, expected) %7B %0A if (err) throw err;%0A expected = JSON.parse(expected);%0A%0A
fs.c
@@ -1649,16 +1649,20 @@
Stream(%0A
+
path.r
@@ -1716,16 +1716,20 @@
.html')%0A
+
).pipe(a
@@ -1768,31 +1768,106 @@
lt) %7B%0A
-console.log();%0A
+ if (err) throw err;%0A%0A console.log('analysed:');%0A console.log('------');%0A
consol
@@ -1895,16 +1895,20 @@
sult, %7B%0A
+
colo
@@ -1917,16 +1917,20 @@
: true,%0A
+
dept
@@ -1945,15 +1945,23 @@
ity%0A
+
%7D));%0A
+
co
@@ -1974,12 +1974,253 @@
log(
-);%0A%7D));%0A
+'------');%0A if (result.title !== expected.title) %7B%0A console.log(stringDiff('acutal', result.title, 'expected', expected.title));%0A %7D else %7B%0A console.log('The actual result matched the expected result');%0A %7D%0A %7D));%0A %7D%0A);
|
d49939a612ff539bad290639a7c97582c892662e | Fix Puppetier error handling | test/browser.js | test/browser.js | /* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable import/no-unresolved */
const puppeteer = require('puppeteer');
const path = require('path');
const args = process.argv.slice(2);
let browser;
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Promise rejection at', promise, 'reason:', reason);
if (browser) {
browser.close().then(() => process.exit(1));
}
process.exit(1);
});
async function onerror(err) {
console.error(err.stack);
await browser.close();
process.exit(1);
}
(async () => {
browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1024, height: 768 });
page.on('error', onerror);
page.on('pageerror', onerror);
page.on('console', msg => {
if (msg.type() !== 'clear') {
console.log('PAGE LOG:', msg.text());
}
});
const url = /https?/.test(args[0]) ? args[0] : `file://${path.resolve(args[0])}`;
await page.goto(url);
if (args[1]) {
await page.screenshot({ path: args[1] });
}
await browser.close();
})().catch(onerror);
| JavaScript | 0 | @@ -282,25 +282,14 @@
n',
-(
reason
-, promise)
=%3E
@@ -335,30 +335,8 @@
tion
- at', promise, 'reason
:',
@@ -490,16 +490,33 @@
stack);%0A
+%09if (browser) %7B%0A%09
%09await b
@@ -531,16 +531,19 @@
lose();%0A
+%09%7D%0A
%09process
|
f50e765663594d37f2e22a2c2b0ff5c69b4dbab3 | Update MediaFileProxy.js | lib/win8metro/plugin/win8metro/MediaFileProxy.js | lib/win8metro/plugin/win8metro/MediaFileProxy.js | var utils = require('cordova/utils'),
File = require('cordova/plugin/File'),
CaptureError = require('cordova/plugin/CaptureError');
module.exports = {
getFormatData:function (successCallback, errorCallback, args) {
var contentType = args[1];
Windows.Storage.StorageFile.getFileFromPathAsync(args[0]).then(function (storageFile) {
var mediaTypeFlag = String(contentType).split("/")[0].toLowerCase();
if (mediaTypeFlag === "audio") {
storageFile.properties.getMusicPropertiesAsync().then(function (audioProperties) {
successCallback(new MediaFileData(null, audioProperties.bitrate, 0, 0, audioProperties.duration / 1000));
}, function () {
errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
})
}
else if (mediaTypeFlag === "video") {
storageFile.properties.getVideoPropertiesAsync().then(function (videoProperties) {
successCallback(new MediaFileData(null, videoProperties.bitrate, videoProperties.height, videoProperties.width, videoProperties.duration / 1000));
}, function () {
errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
})
}
else if (mediaTypeFlag === "image") {
storageFile.properties.getImagePropertiesAsync().then(function (imageProperties) {
successCallback(new MediaFileData(null, 0, imageProperties.height, imageProperties.width, 0));
}, function () {
errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
})
}
else { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)) }
}, function () {
errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
}
)
}
}
| JavaScript | 0 | @@ -135,16 +135,78 @@
rror');%0D
+%0A MediaFileData = require('cordova/plugin/MediaFileData');%0D
%0A%0D%0Amodul
|
9731f408a89cf848959f7e593277cc2e67b1a437 | Add "forDOM" var when rendering for DOM | lib/attach.js | lib/attach.js | var getDefaultHistory = require('./history/getHistory');
/**
* Bootstraps the app by getting the initial state.
*/
function attach(Router, element, opts) {
if (!opts) opts = {};
var router = new Router();
var history = opts.history || getDefaultHistory();
var render = function() {
Router.engine.renderInto(router, element);
};
var onInitialReady = function() {
render();
router
.on('viewChange', render)
.on('stateChange', render);
// Now that the view has been bootstrapped (i.e. is in its inital state), it
// can be updated.
update();
history.on('change', function() {
update();
});
};
var previousURL;
var update = function(isInitial) {
var url = history.currentURL();
if (url === previousURL) return;
previousURL = url;
// TODO: How should we handle an error here? Throw it? Log it?
var res = router.dispatch(url);
if (isInitial) {
res.once('initialReady', onInitialReady);
}
};
// Start the process.
update(true);
return router;
}
module.exports = attach;
| JavaScript | 0.000001 | @@ -203,16 +203,45 @@
Router(
+%7BdefaultVars: %7BforDOM: true%7D%7D
);%0A var
|
30f6e256549de1883788b7d976c52cc632fa6db7 | Correct expiration date property typo | lib/boleto.js | lib/boleto.js | var fs = require('fs')
var ejs = require('ejs')
var formatters = require('./formatters')
var barcode = require('./barcode')
var path = require('path')
var banks = null
var hashString = function (string) {
var hash = 0
var i
var chr
var len
if (string.length == 0) return hash
for (i = 0, len = string.length; i < len; i++) {
chr = string.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0 // Convert to 32bit integer
}
return hash
}
var Boleto = function (options) {
if (!options) {
throw 'No options provided initializing Boleto.'
}
this.bank = banks[options['banco']]
if (!this.bank) {
throw 'Invalid bank.'
}
if (!options['data_emissao']) {
options['data_emissao'] = new Date()
}
if (!options['data_expiracao']) {
options['data_expiracao'] = new Date(new Date().getTime() + (5 * 24 * 3600 * 1000))
}
for (var key in options) {
this[key] = options[key]
}
this['pagador'] = formatters.htmlString(this['pagador'])
this['instrucoes'] = formatters.htmlString(this['instrucoes'])
if (!this['local_de_pagamento']) {
this['local_de_pagamento'] = 'Até o vencimento, preferencialmente no Banco ' + formatters.capitalize(this['banco'])
}
this._calculate()
}
Boleto.barcodeRenderEngine = 'img'
Boleto.prototype._calculate = function () {
this['codigo_banco'] = this.bank.options.codigo + '-' + formatters.mod11(this.bank.options.codigo)
this['nosso_numero_dv'] = formatters.mod11(this['nosso_numero'].toString())
this['barcode_data'] = this.bank.barcodeData(this)
this['linha_digitavel'] = this.bank.linhaDigitavel(this['barcode_data'])
}
Boleto.prototype.renderHTML = function (callback) {
var self = this
fs.readFile(path.join(__dirname, '/../assets/layout.ejs'), function (err, content) {
if (err) {
throw err
}
var renderOptions = self.bank.options
renderOptions.boleto = self
// Copy renderHelper's methods to renderOptions
for (var key in formatters) {
renderOptions[key] = formatters[key]
}
renderOptions['barcode_render_engine'] = Boleto.barcodeRenderEngine
renderOptions['barcode_height'] = '50'
if (Boleto.barcodeRenderEngine == 'bmp') {
renderOptions['barcode_data'] = barcode.bmpLineForBarcodeData(self['barcode_data'])
} else if (Boleto.barcodeRenderEngine == 'img') {
renderOptions['barcode_data'] = barcode.binaryRepresentationForBarcodeData(self['barcode_data'])
}
renderOptions['boleto']['linha_digitavel_hash'] = hashString(renderOptions['boleto']['linha_digitavel']).toString()
var html = ejs.render(content.toString(), renderOptions)
callback(html)
})
}
module.exports = function (_banks) {
banks = _banks
return Boleto
}
| JavaScript | 0 | @@ -765,24 +765,25 @@
s%5B'data_
-expiraca
+venciment
o'%5D) %7B%0A
@@ -803,16 +803,17 @@
ata_
-expiraca
+venciment
o'%5D
|
b1c549cac2a3dd0867200ea8d46296a3d0e06264 | Add test for Argument#toPlaceholder() | test/command.js | test/command.js | /*
* Optics test / command.js
* copyright (c) 2016 Susisu
*/
"use strict";
const chai = require("chai");
const expect = chai.expect;
const command = require("../lib/command.js");
const output = require("../lib/output.js");
describe("command", () => {
describe("Argument", () => {
describe("constructor(placeholder, reader)", () => {
it("should create a new Argument instance", () => {
let arg = new command.Argument("foobar", x => x);
expect(arg).to.be.an.instanceOf(command.Argument);
});
it("should throw an error if 'placeholder' is not a string", () => {
expect(() => { new command.Argument(null, x => x); }).to.throw(Error);
expect(() => { new command.Argument(undefined, x => x); }).to.throw(Error);
expect(() => { new command.Argument(3.14, x => x); }).to.throw(Error);
expect(() => { new command.Argument(true, x => x); }).to.throw(Error);
expect(() => { new command.Argument({}, x => x); }).to.throw(Error);
});
it("should throw an error if 'reader' is not a function", () => {
expect(() => { new command.Argument("foobar", null); }).to.throw(Error);
expect(() => { new command.Argument("foobar", undefined); }).to.throw(Error);
expect(() => { new command.Argument("foobar", 3.14); }).to.throw(Error);
expect(() => { new command.Argument("foobar", true); }).to.throw(Error);
expect(() => { new command.Argument("foobar", {}); }).to.throw(Error);
});
});
describe("#isRequired()", () => {
it("should always return true", () => {
let arg = new command.Argument("foobar", x => x);
expect(arg.isRequired()).to.be.true;
});
});
describe("#toPlaceholder()", () => {
it("should return the placeholder wrapped by angles < and >");
});
describe("#getDefaultValue()", () => {
it("should throw an error");
});
});
describe("OptionalArgument", () => {
describe("constructor(placeholder, defaultVal, reader)", () => {
it("should create a new OptionalArgument instance");
it("should throw an error if 'placeholder' is not a string");
it("should throw an error if 'reader' is not a function");
});
describe("#isRequired()", () => {
it("should always return false");
});
describe("#toPlaceholder()", () => {
it("should return the placeholder wrapped by brackets [ and ]");
});
describe("#getDefaultValue()", () => {
it("should return the default value specified at a constructor");
});
});
describe("CommandBase", () => {
describe("constructor()", () => {
it("should create a new CommandBase instance", () => {
let cmd = new command.CommandBase();
expect(cmd).to.be.an.instanceOf(command.CommandBase);
});
});
describe("#run(out, argv)", () => {
it("should throw an Error", () => {
let out = new output.Output(
_ => { throw new Error("unexpected output"); },
_ => { throw new Error("unexpected output"); }
);
let cmd = new command.CommandBase();
expect(() => { cmd.run(out, []); }).to.throw(Error);
});
});
});
describe("Command", () => {
describe("constructor(desc, args, opts, action)", () => {
it("should create a new Command instance");
it("should throw an error if 'args' is not an array of Argument");
it("should throw an error if 'opts' is not an array of Option");
it("should throw an error if 'action' is not a function");
it("should throw an error if a required argument occurs after an optional argument");
});
describe("#run(out, argv)", () => {
it("should parse 'argv' and call the action with arguments and options if arguments are correct");
it("should throw an error if 'out' is not an instance of Output");
it("should throw an error if 'argv' is not an array");
it("should write error message to 'out.err' if arguments are incorrect");
});
});
});
| JavaScript | 0.000001 | @@ -2012,16 +2012,393 @@
%3C and %3E%22
+, () =%3E %7B%0A %7B%0A let arg = new command.Argument(%22foobar%22, x =%3E x);%0A expect(arg.toPlaceholder()).to.equal(%22%3Cfoobar%3E%22);%0A %7D%0A %7B%0A let arg = new command.Argument(%22nyancat%22, x =%3E x);%0A expect(arg.toPlaceholder()).to.equal(%22%3Cnyancat%3E%22);%0A %7D%0A %7D
);%0A
|
c554932e596e3242c8b1802834cd175b080b09de | Add parsing exception for "cursor" CSS property (#551) | test/css/all.js | test/css/all.js | /**
* Test individual CSS extracts.
*
* The tests run against the curated view of the extracts.
*
* Note: the tests are not run against the `@webref/css` package view of the
* data because that view is a strict subset of the curated view.
*/
const assert = require('assert').strict;
const path = require('path');
const css = require('@webref/css');
const { definitionSyntax } = require('css-tree');
const curatedFolder = path.join(__dirname, '..', '..', 'curated', 'css');
// Expected content in CSS extracts
const cssValues = [
{ type: 'property', prop: 'properties', value: 'value' },
{ type: 'extended property', prop: 'properties', value: 'newValues' },
{ type: 'descriptor', prop: 'descriptors', value: 'value' },
{ type: 'value space', prop: 'valuespaces', value: 'value' }
];
// TEMP: constructs that are not yet supported by the parser
// See: https://github.com/w3c/reffy/issues/494#issuecomment-790713119
// (last validated on 2021-12-17)
const tempIgnore = [
{ shortname: 'css-extensions', prop: 'valuespaces', name: '<custom-selector>' },
{ shortname: 'fill-stroke', prop: 'properties', name: 'stroke-dasharray' },
{ shortname: 'svg-animations', prop: 'valuespaces', name: '<control-point>' },
{ shortname: 'svg-strokes', prop: 'valuespaces', name: '<dasharray>' }
];
describe(`The curated view of CSS extracts`, () => {
before(async () => {
const all = await css.listAll({ folder: curatedFolder });
for (const [shortname, data] of Object.entries(all)) {
describe(`The CSS extract for ${shortname} in the curated view`, () => {
it('contains a link to the underlying spec', async () => {
assert(data);
assert(data.spec);
assert(data.spec.title);
});
for (const { type, prop, value } of cssValues) {
for (const [name, desc] of Object.entries(data[prop])) {
if (!desc[value]) {
continue;
}
if (tempIgnore.some(c => c.shortname === shortname &&
c.prop === prop && c.name === name)) {
continue;
}
it(`defines a valid ${type} "${name}"`, () => {
assert.doesNotThrow(() => {
const ast = definitionSyntax.parse(desc[value]);
assert(ast.type);
}, `Invalid definition value: ${desc[value]}`);
});
}
}
});
}
});
// Dummy test needed for "before" to run and register late tests
// (test will fail if before function throws, e.g. because data is invalid)
it('contains valid JSON data', () => {});
});
| JavaScript | 0 | @@ -956,14 +956,14 @@
202
-1-12-1
+2-04-0
7)%0Ac
@@ -978,24 +978,80 @@
pIgnore = %5B%0A
+ // Stacked combinator %22+#?%22 not supported by css-tree%0A
%7B shortnam
@@ -1116,24 +1116,199 @@
elector%3E' %7D,
+%0A%0A // Stacked combinator %22#?%22 not supported by css-tree%0A %7B shortname: 'css-ui', prop: 'properties', name: 'cursor' %7D,%0A%0A // Stacked combinator %22+#%22 not supported by css-tree
%0A %7B shortna
@@ -1369,24 +1369,93 @@
asharray' %7D,
+%0A%0A // Unescaped comma with multiplier %22,*%22 not supported by css-tree
%0A %7B shortna
@@ -1519,24 +1519,80 @@
l-point%3E' %7D,
+%0A%0A // Stacked combinator %22#*%22 not supported by css-tree
%0A %7B shortna
|
59390c61bd4d74b8e36b14f743d769d2e4a66cc4 | fix nested modal closing (#685) | docs/lib/examples/ModalNested.js | docs/lib/examples/ModalNested.js | /* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
class ModalExample extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: false,
nestedModal: false,
};
this.toggle = this.toggle.bind(this);
this.toggleNested = this.toggleNested.bind(this);
}
toggle() {
this.setState({
modal: !this.state.modal
});
}
toggleNested() {
this.setState({
nestedModal: !this.state.nestedModal
});
}
render() {
return (
<div>
<Button color="danger" onClick={this.toggle}>{this.props.buttonLabel}</Button>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
<ModalBody>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
<br />
<Button color="success" onClick={this.toggleNested}>Show Nested Model</Button>
<Modal isOpen={this.state.nestedModal} toggle={this.toggleNested}>
<ModalHeader>Nested Modal title</ModalHeader>
<ModalBody>Stuff and things</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.toggleNested}>Done</Button>{' '}
<Button color="secondary" onClick={this.toggle}>All Done</Button>
</ModalFooter>
</Modal>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
<Button color="secondary" onClick={this.toggle}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
);
}
}
export default ModalExample;
| JavaScript | 0 | @@ -315,15 +315,37 @@
se,%0A
+ closeAll: false%0A
%7D;%0A
-
%0A
@@ -437,16 +437,64 @@
(this);%0A
+ this.toggleAll = this.toggleAll.bind(this);%0A
%7D%0A%0A t
@@ -602,24 +602,24 @@
.setState(%7B%0A
-
nested
@@ -644,24 +644,161 @@
.nestedModal
+,%0A closeAll: false%0A %7D);%0A %7D%0A%0A toggleAll() %7B%0A this.setState(%7B%0A nestedModal: !this.state.nestedModal,%0A closeAll: true
%0A %7D);%0A %7D
@@ -1758,16 +1758,62 @@
eNested%7D
+ onClosed=%7Bthis.state.closeAll && this.toggle%7D
%3E%0A
@@ -2097,16 +2097,19 @@
s.toggle
+All
%7D%3EAll Do
|
75ddab1d23d5931f0af7eeb2fd21d35f2d26c052 | test valid air date | test/episode.js | test/episode.js | var assert = require("assert");
var API_KEY = process.env.TVDB_KEY;
var TVDBClient = require("..");
describe("Episode endpoints", function() {
describe("Node callback API", function() {
it("should return an object of the episode with id \"4768125\"", function(done) {
var client = new TVDBClient(API_KEY);
client.getEpisodeById("4768125", function(error, response) {
assert.ifError(error);
assert.equal("object", typeof response);
assert.equal("4768125", response.id);
done();
});
});
it("should return an error for a episode search with an invalid id", function(done) {
var client = new TVDBClient(API_KEY);
client.getEpisodeById("0", function(error, response) {
assert.notEqual(null, error);
assert.equal(null, response);
done();
});
});
});
describe("Promise API", function() {
it("should return an object of the episode with id \"4768125\"", function(done) {
var client = new TVDBClient(API_KEY);
client.getEpisodeById("4768125")
.then(function(response) {
assert.equal("object", typeof response);
assert.equal("4768125", response.id);
})
.catch(function(error) {
assert.ifError(error);
})
.done(done);
});
it("should return an error for a episode search with an invalid id", function(done) {
var client = new TVDBClient(API_KEY);
client.getEpisodeById("0")
.then(function(response) {
assert.equal(null, response);
})
.catch(function(error) {
assert.notEqual(null, error);
})
.done(done);
});
});
});
| JavaScript | 0.000079 | @@ -541,32 +541,97 @@
, response.id);%0A
+ assert.equal(%222014-03-30%22, response.FirstAired);%0A
@@ -1412,32 +1412,101 @@
, response.id);%0A
+ assert.equal(%222014-03-30%22, response.FirstAired);%0A
|
60e8a2cf2bc2e2eb96418981f4f2e871c0c555a8 | Fix typo in example | test/example.js | test/example.js | require('longjohn')
var DeeToo = require('..')
, util = require('../lib/util.js')
, _ = require('underscore')
, d2 = DeeToo.init()
, JOB_TIME = 5000
function _generateJobs() {
function mkjob(i) {
var id = 'demo'+j
return {jobType:'demonstrate', jobData:{title: id}}
}
function showUpdates(err, job) {
if (err)
throw err;
job.on('progress', function(prog) {
console.log(['Job', job.id, '@', prog, '%'].join(' '))
})
}
for (var j=0; j<20; j++) {
d2.jobs.push(mkjob(j), showUpdates)
}
}
// An example task that takes 5 seconds to run
// and updates its progress every second.
function processDemonstration(job, $done) {
function nextStep(){ job.progress(++step, 5) }
function stop() {
clearTimeout(ticker)
console.log(['Job', job.id, 'finished!'].join(' '))
$done()
}
var step = 0
, ticker = setInterval(nextStep, JOB_TIME/5)
setTimeout(stop, JOB_TIME)
}
// Launch the worker
d2
.can('demonstrate', 4, processDemonstration)
.start(function(err) {
console.log('Example worker has started!')
})
setTimeout(_generateJobs, 1)
// Demonstrate graceful shutdown
setTimeout(function() {
console.log('\n([~ shutting down ~])\n')
d2.shutdown(function() {
console.log('\n([~ SHUT DOWN ~])\n')
process.exit(0)
})
}, JOB_TIME * 2.3)
| JavaScript | 0.000381 | @@ -753,23 +753,24 @@
clear
-Timeout
+Interval
(ticker)
|
b9a9046dfba941cd19def7c1523742ca542485b7 | Modify example file | test/example.js | test/example.js | require('longjohn')
var DeeToo = require('..')
, util = require('../lib/util.js')
, _ = require('underscore')
, d2 = DeeToo.init()
, JOB_TIME = 5000
function _generateJobs() {
function mkjob(i) {
var id = 'demo'+j
return {id:id, jobType:'demonstrate', jobData:{title: id}}
}
function showUpdates(err, job) {
if (err)
throw err;
job.on('progress', function(prog) {
console.log(['Job', job.id, '@', prog, '%'].join(' '))
})
}
// TODO: check to see if job being replaced correctly if added twice
// TODO: check to see if job being replaced if delayed and added again
for (var j=0; j<1; j++) {
d2.jobs.push(mkjob(j), showUpdates)
d2.jobs.push(mkjob(j), showUpdates)
}
}
// An example process that takes 5 seconds to run
// and updates its progress every second.
function processDemonstration(job, $done) {
function nextStep(){ job.progress(++step, 5) }
function stop() {
clearTimeout(ticker)
console.log(['Job', job.id, 'finished!'].join(' '))
$done()
}
var step = 0
, ticker = setInterval(nextStep, JOB_TIME/5)
setTimeout(stop, JOB_TIME)
}
function demoCron(job, $done) {
console.log('CRON FIGHTS FOR THE USER')
$done()
}
// Launch the worker
d2
.can('demonstrate', 4, processDemonstration)
//.cron('democron', 4000, demoCron)
.start(function(err) {
console.log('Example worker has started!')
})
setTimeout(_generateJobs, 1)
// Demonstrate graceful shutdown
setTimeout(function() {
console.log('\n([~ shutting down ~])\n')
d2.shutdown(function() {
console.log('\n([~ SHUT DOWN ~])\n')
setTimeout(function(){ process.exit(0) }, 1000)
})
}, JOB_TIME * 2.3)
| JavaScript | 0.000001 | @@ -241,15 +241,8 @@
rn %7B
-id:id,
jobT
@@ -468,161 +468,8 @@
%7D%0A%0A
-%0A%0A%0A // TODO: check to see if job being replaced correctly if added twice%0A // TODO: check to see if job being replaced if delayed and added again%0A%0A%0A%0A%0A%0A%0A
fo
@@ -482,17 +482,18 @@
j=0; j%3C
-1
+20
; j++) %7B
@@ -537,48 +537,8 @@
es)%0A
- d2.jobs.push(mkjob(j), showUpdates)%0A
%7D%0A
|
5c8a96da19bb1345e878f167a011cd5d75b84134 | Fix fn.gettext's tests to actually use fn.gettext | test/fn.test.js | test/fn.test.js | var assert = require('assert');
var fn = require('../lib/fn');
describe("fn", function() {
it("should proxy to .gettext when called directly", function() {
assert.deepEqual(fn('foo'), {
method: 'gettext',
params: {message: 'foo'}
});
});
describe(".gettext", function() {
it("should throw an error if the message param is unusable",
function() {
assert.throws(
function() { fn(null); },
new RegExp([
"gettext was given a value of type 'object'",
"instead of a string or number for parameter",
"'message': null"
].join(' ')));
});
it("should return the method call's data", function() {
assert.deepEqual(fn('foo'), {
method: 'gettext',
params: {message: 'foo'}
});
});
});
});
| JavaScript | 0.000002 | @@ -467,16 +467,24 @@
n() %7B fn
+.gettext
(null);
@@ -817,32 +817,40 @@
ert.deepEqual(fn
+.gettext
('foo'), %7B%0A
|
d220b378191d4f1e44a53b10cfdf485ae0f95816 | add source files | lib/common.js | lib/common.js | /**
* Created by nuintun on 2015/4/27.
*/
'use strict';
var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var through = require('through2');
var rename = require('rename');
var udeps = require('umd-deps');
var debug = require('debug')('transport:common');
var util = require('./util');
var colors = util.colors;
/**
* Transport cmd id
* - file: file object of father
* - required options: idleading, rename
*/
function transportId(file, options){
var pkg = util.parsePackage(file);
var idleading = resolveIdleading(options.idleading, file.path, pkg);
var id = util.template(idleading, pkg);
var renameOpts = util.getRenameOpts(options.rename);
// rename id
id = rename.parse(util.addExt(id));
id = rename(id, renameOpts);
id = util.slashPath(util.hideExt(id));
// seajs has hacked css before 3.0.0
// https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
// demo https://github.com/popomore/seajs-test/tree/master/css-deps
if (extname(id) === '.css') {
id += '.js';
}
// debug
debug('transport id ( %s )', colors.dataBold(id));
// rewrite relative
file.path = join(file.base, util.addExt(id));
// set file package info
file.package = util.extend(file.package, { id: id }, pkg);
return id;
}
/**
* Transport cmd dependencies, it will get deep dependencies of the file,
* but will ignore relative module of the dependent package.
* - file: file object of father
* - required options: idleading, rename, ignore
*/
function transportDeps(file, options){
var deps = [];
var depspath = [];
var alias = options.alias;
var paths = options.paths;
var vars = options.vars;
// replace require and collect dependencies
file.contents = new Buffer(udeps(file.contents.toString(), function (id, flag){
var path;
var query;
var normalizeId;
var last = id.length - 1;
var charCode = id.charCodeAt(last);
var renameOpts = util.getRenameOpts(options.rename);
var isRelative = util.isRelative(id);
// parse id form alias, paths, vars
id = util.parseAlias(id, alias);
id = util.parsePaths(id, paths);
id = util.parseAlias(id, alias);
id = util.parseVars(id, vars);
id = util.parseAlias(id, alias);
// if the id ends with `#`, just return it without '#'
if (charCode === 35 /* "#" */) {
normalizeId = id.substring(0, last);
} else
// if the id not ends with `/' '.js' or not has '?', just return it with '.js'
if (id.substring(last - 2) !== '.js' && id.indexOf('?') === -1 /* "?" */ && charCode !== 47 /* "/" */) {
normalizeId = id + '.js';
}
// parse id form alias
if (alias && is.string(alias[normalizeId])) {
id = util.parseAlias(normalizeId, alias);
}
// debug
debug('transport%s dependencies ( %s )', flag ? ' ' + flag : '', colors.dataBold(id));
// get file path form id
path = util.normalize(id);
// get search string
query = id.substr(path.length);
// add extname
path = util.addExt(path);
// rename id
id = rename.parse(path);
id = (isRelative ? './' : '') + util.slashPath(rename(id, renameOpts));
// if id do not ends with `#` '/' or has '?', hide extname
if (!query) {
id = util.hideExt(id);
}
// seajs has hacked css before 3.0.0
// https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
// demo https://github.com/popomore/seajs-test/tree/master/css-deps
if (extname(id) === '.css') {
id += '.js';
}
id = id + query;
// cache dependencie id and path
if (flag === null) {
// cache dependencie id
deps.push(id);
// get absolute path
path = util.slashPath(join(file.base, util.resolve(path, file.package.id)));
// cache dependencie absolute path
depspath.push(path);
}
return id;
}, true));
// Cache file dependencies
file.package = util.extend(file.package, { dependencies: deps, dependenciespath: depspath });
return deps;
}
/*
Create a stream for parser in lib/parser
*/
function createStream(options, type, parser){
options = util.extendOption(options);
return through.obj(function (gfile, enc, callback){
if (gfile.isNull()) {
debug('transport ignore filepath:%s cause null', gfile.path);
return callback(null, gfile);
}
if (gfile.isStream()) {
return callback(new Error('Streaming not supported.'));
}
var ext = extname(gfile.path).substring(1);
if (type && ext !== type) {
return callback(new Error('extension "' + ext + '" not supported.'));
}
try {
debug('transport %s / filepath:%s', type, gfile.path);
gfile = parser.call(this, gfile, options);
} catch (e) {
return callback(e);
}
this.push(gfile);
return callback();
});
}
function isFunction(fun){
return Object.prototype.toString.call(fun) === '[object Function]';
}
function resolveIdleading(idleading, filepath, pkg){
return isFunction(idleading) ? idleading(filepath, pkg) : idleading;
}
/*
Exports
*/
exports.transportId = transportId;
exports.transportDeps = transportDeps;
exports.createStream = createStream;
exports.resolveIdleading = resolveIdleading; | JavaScript | 0.000001 | @@ -3252,14 +3252,20 @@
if (
-!
query
+.length
) %7B%0A
@@ -3539,24 +3539,48 @@
js';%0A %7D%0A%0A
+ // add query string%0A
id = id
|
6f91f0287f80adfbc9422fc5edf2db6aca0bc5cd | Fix placeholder image | lcp-critical-path/load.js | lcp-critical-path/load.js | export function insertImage() {
const img = 'https://placedog.net/500/500';
const image = new Image();
image.src = img;
document.getElementById('app').appendChild(image);
}
| JavaScript | 0.000015 | @@ -52,20 +52,27 @@
s://
+via.
place
-dog.net
+holder.com
/500
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.