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
|
---|---|---|---|---|---|---|---|
4245104242a2cca07d6d03c3b26a1b5b48f49f94
|
debug typeof in string.if
|
lib/output-engine/string.js
|
lib/output-engine/string.js
|
var utils = require('../utils'),
openTags = require('../parsers/open-tags'),
strictTags = /span|script|meta/,
Context = require('../context'),
Template = require('../template'),
View = require('../view');
// String Output Descriptor
function SOD() {
this.attributes = '';
this.classes = '';
this.children = '';
this.style = '';
}
function tagOutput(descriptor, innerDescriptor, name) {
var out = '<' + name + innerDescriptor.attributes;
if (innerDescriptor.style)
out += ' style="' + innerDescriptor.style + '"';
if (innerDescriptor.classes)
out += ' class="' + innerDescriptor.classes + '"';
if (innerDescriptor.children)
descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
else if (openTags.test(name))
descriptor.children += out + '>';
else if (strictTags.test(name))
descriptor.children += out + '></' + name + '>';
else
descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;
var methods = {
SOD: SOD,
//_________________________________ local context management
context: function(context, descriptor, args) {
var data = args[0],
parent = args[1] || context,
path = args[2];
descriptor.context = new Context(data, parent, path);
},
//_________________________________________ EACH
each: function(context, descriptor, args) {
var path = args[0],
values = (typeof path === 'string') ? context.get(path) : path;
if (values && values.length) {
var template = args[1];
for (var i = 0, len = values.length; i < len; ++i)
template.toHTMLString(new Context(values[i], context), descriptor);
} else if (args[2])
args[2].toHTMLString(context, descriptor);
},
// ____________________________________ WITH
with: function(context, descriptor, args) {
var path = args[0],
template = args[1];
var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
template.toHTMLString(ctx, descriptor, container);
},
//______________________________________________
if: function(context, descriptor, args) {
var ok, condition = args[0],
successTempl = args[1],
failTempl = args[2];
if (condition && condition.__interpolable__)
ok = condition.output(context);
else if (type === 'function')
ok = condition.call(this, context);
var sod = new SOD();
if (ok)
successTempl.toHTMLString(context, sod);
else if (failTempl)
failTempl.toHTMLString(context, sod);
if (sod.children)
descriptor.children += sod.children;
},
switch: function(context, descriptor, args) {
var xpr = args[0],
dico = args[1],
value = xpr.output(context),
templ = dico[value] || dico['default'];
if (templ) {
var sod = new SOD();
templ.toHTMLString(context, sod);
if (sod.children)
descriptor.children += sod.children;
}
},
//________________________________ TAGS
tag: function(context, descriptor, originalArgs) {
var name = originalArgs[0],
template = originalArgs[1];
var newDescriptor = new SOD();
template.toHTMLString(context, newDescriptor);
tagOutput(descriptor, newDescriptor, name);
},
text: function(context, descriptor, args) {
var value = args[0];
descriptor.children += value.__interpolable__ ? value.output(context) : value;
},
br: function(context, descriptor) {
descriptor.children += '<br>';
},
//______________________________________________ ATTRIBUTES
attr: function(context, descriptor, args) {
var name = args[0],
value = args[1];
descriptor.attributes += ' ' + name;
if (value)
descriptor.attributes += '="' + (value.__interpolable__ ? value.output(context) : value) + '"';
},
disabled: function(context, descriptor, args) {
var value = args[0];
if (value === undefined || context.get(value))
descriptor.attributes += ' disabled';
},
val: function(context, descriptor, args) {
var path = args[0],
value = args[1];
descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
},
setClass: function(context, descriptor, args) {
var name = args[0],
flag = args[1];
if ((flag.__interpolable__ && flag.output(context)) || flag)
descriptor.classes += ' ' + (name.__interpolable__ ? name.output(context) : name);
},
css: function(context, descriptor, args) {
var prop = args[0],
value = args[1];
descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
},
visible: function(context, descriptor, args) {
var flag = args[0],
val = flag.__interpolable__ ? flag.output(context) : flag;
if (!val)
descriptor.style += 'display:none;';
},
//_________________________________ EVENTS
on: function() {},
off: function() {},
//_________________________________ CLIENT/SERVER
client: function(context, descriptor, args) {
if (context.env.data.isServer)
return;
args[0].toHTMLString(context, descriptor);
},
server: function(context, descriptor, args) {
if (!context.env.data.isServer)
return;
args[0].toHTMLString(context, descriptor);
},
//_______________________________ SUSPEND RENDER
suspendUntil: function(context, descriptor, args) {
var xpr = args[0],
index = args[1],
templ = args[2],
val = xpr.__interpolable__ ? xpr.output(context) : xpr,
rest = new Template(templ._queue.slice(index));
if (val)
rest.toHTMLString(context, descriptor);
}
};
View.prototype.toHTMLString = function(context, descriptor) {
var sod = new SOD();
Template.prototype.toHTMLString.call(this, context, sod);
descriptor.children += sod.children;
return descriptor.children;
};
Template.prototype.toHTMLString = function(context, descriptor) {
context = context || new Context();
descriptor = descriptor || new SOD();
var handler = this._queue[0],
nextIndex = 0,
f;
while (handler) {
if (handler.engineBlock)
f = handler.engineBlock.string;
else
f = handler.func || methods[handler.name];
f(descriptor.context || context, descriptor, handler.args);
handler = this._queue[++nextIndex];
}
return descriptor.children;
};
module.exports = methods;
|
JavaScript
| 0.000053 |
@@ -2214,16 +2214,28 @@
if (type
+of condition
=== 'fu
|
06a2972cdbd019201aad84d4ce3975a637aa8cf7
|
Exit code should return 1 when there are errors
|
lib/package/bundleLinter.js
|
lib/package/bundleLinter.js
|
//bundleLinter.js
var fs = require("fs"),
path = require("path"),
Bundle = require("./Bundle.js"),
request = require("request"),
async = require("async"),
debug = require("debug")("bundlelinter:");
function contains(a, obj, f) {
if (!a || !a.length) {
return false;
}
f =
f ||
function(lh, rh) {
return lh === rh;
};
for (var i = 0; i < a.length; i++) {
if (f(a[i], obj)) {
if (!a[i]) {
return true;
}
return a[i];
}
}
return false;
}
function exportData(path, report) {
fs.writeFile(
path + "apigeeLint.json",
JSON.stringify(report, null, 4),
"utf8",
function(err) {
if (err) {
return console.log(err);
}
}
);
}
var lint = function(config, done) {
new Bundle(config, function(bundle, err) {
if (err) {
if (done) {
done(null, err);
} else {
console.log(err);
}
} else {
//for each plugin
var normalizedPath = path.join(__dirname, "plugins");
fs.readdirSync(normalizedPath).forEach(function(file) {
if (!config.plugins || contains(config.plugins, file)) {
try {
executePlugin(file, bundle);
} catch (e) {
debug("plugin error: " + file + " " + e);
}
}
});
var fmt = config.formatter || "json.js",
fmtImpl = getFormatter(fmt),
fmtReport = fmtImpl(bundle.getReport());
if (config.output) {
if (typeof config.output == "function") {
config.output(fmtReport);
}
} else {
console.log(fmtReport);
}
if (fmt !== "json.js") {
(fmt = "json.js"), (fmtImpl = getFormatter(
fmt
)), (fmtReport = JSON.parse(fmtImpl(bundle.getReport())));
} else {
fmtReport = JSON.parse(fmtReport);
}
if (config.apiUpload) {
var policySLOC = 0,
resourceSLOC = 0;
bundle.getResources().forEach(function(resource) {
resourceSLOC += resource.getLines().length;
});
bundle.getPolicies().forEach(function(policy) {
policySLOC += policy.getLines().length;
});
var htmlReport = getFormatter("html.js")(bundle.getReport());
var myReq = {
uri:
config.apiUpload.destPath ||
"https://csdata-test.apigee.net/v1/lintresults",
headers: {
"Content-Type": "application/json",
Authorization: config.apiUpload.authorization
},
json: true,
method: "POST",
body: {
authorization: config.apiUpload.authorization,
organization: config.apiUpload.organization,
name: bundle.getName(),
revision: bundle.getRevision(),
policyCount: bundle.getPolicies().length,
resourceCount: bundle.getResources().length,
policySLOC,
resourceSLOC,
lintingResults: fmtReport,
htmlReport
}
};
var cb = function(err, httpResponse, body) {
if (err) {
throw new Error("upload failed:", err);
}
console.log("Upload successful! Server responded with:", body);
};
request.post(myReq, cb);
}
if (config.writePath) {
exportData(config.writePath, fmtReport);
}
if (done) {
done(bundle, null);
}
}
});
};
var getFormatter = function(format) {
// default is stylish
var formatterPath;
format = format || "stylish.js";
if (typeof format === "string") {
format = format.replace(/\\/g, "/");
// if there's a slash, then it's a file
if (format.indexOf("/") > -1) {
const cwd = this.options ? this.options.cwd : process.cwd();
formatterPath = path.resolve(cwd, format);
} else {
formatterPath = `./formatters/${format}`;
}
try {
return require(formatterPath);
} catch (ex) {
ex.message = `There was a problem loading formatter: ${formatterPath}\nError: ${ex.message}`;
throw ex;
}
} else {
return null;
}
};
var executePlugin = function(file, bundle, callback) {
if (file.endsWith(".js")) {
var plugin = require("./plugins/" + file);
if (plugin.plugin.enabled) {
async.parallel(
[
function(acb) {
if (plugin.onBundle) {
bundle.onBundle(plugin.onBundle, acb);
} else {
acb("bundleLinter no onBundle");
}
},
function(acb) {
if (plugin.onStep) {
bundle.onSteps(plugin.onStep, acb);
} else {
acb("bundleLinter no onStep");
}
},
function(acb) {
if (plugin.onCondition) {
bundle.onConditions(plugin.onCondition, acb);
} else {
acb("bundleLinter no onCondition");
}
},
function(acb) {
if (plugin.onProxyEndpoint) {
bundle.onProxyEndpoints(plugin.onProxyEndpoint, acb);
} else {
acb("bundleLinter no onProxyEndpoint");
}
},
function(acb) {
if (plugin.onTargetEndpoint) {
bundle.onTargetEndpoints(plugin.onTargetEndpoint, acb);
} else {
acb("bundleLinter no onTargetEndpoint");
}
},
function(acb) {
if (plugin.onResource) {
bundle.onResources(plugin.onResource, acb);
} else {
acb("bundleLinter no onResource");
}
},
function(acb) {
if (plugin.onPolicy) {
bundle.onPolicies(plugin.onPolicy, acb);
} else {
acb("bundleLinter no onPolicy");
}
},
function(acb) {
if (plugin.onFaultRule) {
bundle.onFaultRules(plugin.onFaultRule, acb);
} else {
acb("bundleLinter no onFaultRule");
}
},
function(acb) {
if (plugin.onDefaultFaultRule) {
bundle.onDefaultFaultRules(plugin.onDefaultFaultRule, acb);
} else {
acb("bundleLinter no onDefaultFaultRules");
}
}
],
function(err, result) {
if (typeof callback === "function") {
if (err) {
callback(err);
} else {
callback(null, result);
}
}
}
);
}
}
};
module.exports = {
lint,
executePlugin,
getFormatter
};
|
JavaScript
| 0.000011 |
@@ -3444,32 +3444,259 @@
null);%0A %7D%0A
+ %0A // Exit code should return 1 when there are errors%0A bundle.getReport().some(function(value)%7B%0A if (value.errorCount %3E 0) %7B%0A process.exitCode = 1;%0A return;%0A %7D%0A %7D);%0A
%7D%0A %7D);%0A%7D;%0A%0A
|
f6345efce653ef6ec49dd51b66e3b95d3f99601d
|
Add honorCount to test config to prevent timeout being sent
|
test/www/jxcore/meta_tests/testPerfTestFramework.js
|
test/www/jxcore/meta_tests/testPerfTestFramework.js
|
'use strict';
var PerfTestFramework = require('../../../TestServer/PerfTestFramework.js');
var TestDevice = require('../../../TestServer/TestDevice.js');
var tape = require('../lib/thali-tape');
var test = tape({
setup: function(t) {
t.end();
},
teardown: function(t) {
t.end();
}
});
test('#should be able to add devices to the framework', function (t) {
var testConfig = JSON.parse('{"devices":{"ios":2}}');
var perfTestFramework = new PerfTestFramework(testConfig);
var testDevice = new TestDevice(null, "a device", "ios", "perftest", [], null);
perfTestFramework.addDevice(testDevice);
console.log(perfTestFramework);
t.equal(perfTestFramework.devices["ios"].length, 1);
t.end();
});
|
JavaScript
| 0 |
@@ -419,16 +419,35 @@
%22ios%22:2%7D
+, %22honorCount%22:true
%7D');%0A v
|
0aa8a8de0396212642102dfeb2dd712e7dea8505
|
Remove warning on mapInteractor test.
|
testing/test-cases/phantomjs-tests/mapInteractor.js
|
testing/test-cases/phantomjs-tests/mapInteractor.js
|
/* global describe, it, beforeEach, afterEach, expect, $, geo */
describe('mapInteractor', function () {
'use strict';
// An event object template that will work with the interactor
// handlers.
var evtObj = function (type, args) {
args = $.extend({}, {
pageX: 0,
pageY: 0,
type: type,
which: 1,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false
},
args
);
return new $.Event(type, args);
};
function mockedMap(node) {
var map = geo.object();
var base = geo.object();
var info = {
pan: 0,
zoom: 0,
panArgs: {},
zoomArgs: {}
};
map.node = function () { return $(node); };
base.displayToGcs = function (x) { return x; };
map.baseLayer = function () { return base; };
map.zoom = function (arg) {
if (arg === undefined) {
return 2;
}
info.zoom += 1;
info.zoomArgs = arg;
};
map.zoom.nCalls = 0;
map.pan = function (arg) {
info.pan += 1;
info.panArgs = arg;
};
map.center = function () {
return {x: 0, y: 0};
};
map.displayToGcs = base.displayToGcs;
map.info = info;
map._zoomCallback = function () {};
return map;
}
beforeEach(function () {
// create a new div
$('body').append('<div id="mapNode1" class="mapNode"></div>');
$('body').append('<div id="mapNode2" class="mapNode"></div>');
});
afterEach(function () {
// delete the div
$('.mapNode').remove();
});
it('Test initialization with given node.', function () {
var map = mockedMap('#mapNode1');
var interactor = geo.mapInteractor({ map: map });
expect(interactor.map()).toBe(map);
interactor.destroy();
expect(!!interactor.map()).toBe(false);
});
it('Test initialization without a map.', function () {
var map = mockedMap('#mapNode1');
var interactor = geo.mapInteractor();
expect(!!interactor.map()).toBe(false);
interactor.map(map);
expect(interactor.map()).toBe(map);
interactor.destroy();
expect(!!interactor.map()).toBe(false);
interactor.map(map);
expect(interactor.map()).toBe(map);
});
it('Test pan event propagation', function () {
var map = mockedMap('#mapNode1');
var interactor = geo.mapInteractor({
map: map,
panMoveButton: 'left',
panWheelEnabled: false,
zoomMoveButton: null,
zoomWheelEnabled: false,
});
// initiate a pan
interactor.simulateEvent(
'mousedown',
{
map: {x: 0, y: 0},
button: 'left'
}
);
// trigger a pan
interactor.simulateEvent(
'mousemove',
{
map: {x: 10, y: 10},
button: 'left'
}
);
// check the pan event was called
expect(map.info.pan).toBe(1);
expect(map.info.panArgs.x).toBe(10);
expect(map.info.panArgs.y).toBe(10);
// trigger a pan
interactor.simulateEvent(
'mousemove',
{
map: {x: 9, y: 12},
button: 'left'
}
);
// check the pan event was called
expect(map.info.pan).toBe(2);
expect(map.info.panArgs.x).toBe(-1);
expect(map.info.panArgs.y).toBe(2);
// trigger a pan on a different element
$('#mapNode2').trigger(
evtObj('mousemove', {pageX: 0, pageY: 20})
);
// check the pan event was called
expect(map.info.pan).toBe(3);
// end the pan
interactor.simulateEvent(
'mouseup',
{
map: {x: 0, y: 20},
button: 'left'
}
);
// check the pan event was NOT called
expect(map.info.pan).toBe(3);
// trigger another mousemove
$('#mapNode1').trigger(
evtObj('mousemove', {pageX: 10, pageY: 0})
);
// check the pan event was NOT called
expect(map.info.pan).toBe(3);
});
it('Test zoom wheel event propagation', function () {
var map = mockedMap('#mapNode1');
var interactor = geo.mapInteractor({
map: map,
panMoveButton: null,
panWheelEnabled: false,
zoomMoveButton: null,
zoomWheelEnabled: true,
});
// initialize the mouse position
interactor.simulateEvent(
'mousemove',
{
map: {x: 20, y: 20},
}
);
// trigger a zoom
interactor.simulateEvent(
'mousewheel',
{
wheelDelta: {x: 20, y: -10},
}
);
// check the zoom event was called
expect(map.info.zoom).toBe(1);
expect(map.info.zoomArgs).toBe(2 - 10 / 120);
});
it('Test zoom right click event propagation', function () {
var map = mockedMap('#mapNode1'), z;
var interactor = geo.mapInteractor({
map: map,
panMoveButton: null,
panWheelEnabled: false,
zoomMoveButton: 'right',
zoomWheelEnabled: false,
});
// initialize the zoom
interactor.simulateEvent(
'mousedown',
{
map: {x: 20, y: 20},
button: 'right'
}
);
// create a zoom event
interactor.simulateEvent(
'mousemove',
{
map: {x: 20, y: 10},
button: 'right'
}
);
// check the zoom event was called
expect(map.info.zoom).toBe(1);
expect(map.info.zoomArgs).toBe(2 + 10 / 120);
z = map.zoom();
// create a zoom event
interactor.simulateEvent(
'mousemove',
{
map: {x: 30, y: 25},
button: 'right'
}
);
// check the zoom event was called
expect(map.info.zoom).toBe(2);
expect(map.info.zoomArgs).toBe(z - 15 / 120);
});
});
|
JavaScript
| 0 |
@@ -2330,32 +2330,66 @@
map: map,%0A
+ momentum: %7Benabled: false%7D,%0A
panMoveBut
@@ -4009,32 +4009,66 @@
map: map,%0A
+ momentum: %7Benabled: false%7D,%0A
panMoveBut
|
fa0bbd7bd7e54522b27565145c3d64f6f20bfdc8
|
Fix bug trying to sign up with Google or Facebook
|
api/controllers/UserController.js
|
api/controllers/UserController.js
|
module.exports = {
create: function (req, res) {
const { name, email, password } = req.allParams()
return User.create({name, email: email.toLowerCase(), account: {type: 'password', password}})
.tap(user => Analytics.trackSignup(user.id, req))
.tap(user => req.param('login') && UserSession.login(req, user, 'password'))
.then(user => {
if (req.param('resp') === 'user') {
return res.ok({
name: user.get('name'),
email: user.get('email')
})
} else {
return res.ok({})
}
})
.catch(function (err) {
res.status(422).send(req.__(err.message ? err.message : err))
})
},
status: function (req, res) {
res.ok({signedIn: UserSession.isLoggedIn(req)})
},
sendPasswordReset: function (req, res) {
var email = req.param('email')
return User.query(q => q.whereRaw('lower(email) = ?', email.toLowerCase())).fetch().then(function (user) {
if (!user) {
return res.ok({})
} else {
const nextUrl = req.param('evo')
? Frontend.Route.evo.passwordSetting()
: null
user.generateToken().then(function (token) {
Queue.classMethod('Email', 'sendPasswordReset', {
email: user.get('email'),
templateData: {
login_url: Frontend.Route.tokenLogin(user, token, nextUrl)
}
})
return res.ok({})
})
}
})
.catch(res.serverError.bind(res))
}
}
|
JavaScript
| 0 |
@@ -135,16 +135,24 @@
, email:
+ email ?
email.t
@@ -163,16 +163,23 @@
erCase()
+ : null
, accoun
|
726338d333aaa6cdb0010a6abf42ab434d48d9b2
|
Update Browser.js license to WTFPL
|
browser-extensions/Browser.js
|
browser-extensions/Browser.js
|
/*============================================================================
Simple Browser Detection Script
Author: Michael J. Ryan (http://tracker1.info)
Public Domain
This library 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.
------------------------------------------------------------------------------
Browser matching for various browser.
browser.ie
browser.gecko
browser.firefox
browser.khtml
browser.webkit
browser.chrome
browser.safari
browser.opera
Browser feature detection.
browser.phone
browser.doublePixel
recommended:
use browser.gecko over browser.firefox
use browser.webkit over browser.chrome or browser.safari
============================================================================*/
//console.debug("begin browser.js");
(function (b) {
b.any = !!(navigator && navigator.userAgent);
if (!b.any) return;
//browsermatch method...
function bm(re) {
var m = navigator.userAgent.match(re);
return (m && m[1]);
}
//setup browser detection
b.gecko = parseFloat(bm(/Gecko\/(\d+)/)) || null;
b.ff = parseFloat(bm(/Firefox\/(\d+\.\d+)/)) || null;
b.khtml = parseFloat(bm(/\((KHTML)/) && 1) || null;
b.webkit = parseFloat(bm(/AppleWebKit\/(\d+\.\d+)/));
b.chrome = parseFloat(b.webkit && bm(/Chrome\/(\d+\.\d+)/)) || null;
b.safari = parseFloat(b.webkit && bm(/Safari\/(\d+\.\d+)/) && bm(/Version\/(\d+\.\d+)/)) || null;
b.opera = parseFloat(bm(/Opera\/(\d+\.\d+)/) && bm(/Version\/(\d+\.\d+)/)) || bm(/Opera\/(\d+\.\d+)/) || null;
b.ie = (function () { //http://ajaxian.com/archives/attack-of-the-ie-conditional-comment
var v = 4, div = document.createElement('div');
while (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', div.getElementsByTagName('i')[0]);
return v > 5 ? v : null;
} ());
b.phone = !!navigator.userAgent.match(/phone|mobile/ig) || null;
b.doublePixel = (window.devicePixelRatio || 1) >= 2 || null;
//delete empty values
for (var x in b) {
if (b[x] === null)
delete b[x];
}
//disable IE matching for older Opera versions.
if (b.opera && b.ie) delete b.ie;
} (this.browser = this.browser || {}));
//console.debug("end browser.js");
|
JavaScript
| 0 |
@@ -158,210 +158,459 @@
o)%0D%0A
-%0D%0APublic Domain%0D%0A%0D%0AThis library is distributed in the hope that it will be useful,%0D%0Abut WITHOUT ANY WARRANTY; without even the implied warranty of%0D%0AMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+------------------------------------------------------------------------------%0D%0A%0D%0ALicense: WTFPL version 2.1%0D%0A%0D%0ACopyright (C) 2012 Michael J. Ryan (http://tracker1.info/)%0D%0A%0D%0AEveryone is permitted to copy and distribute verbatim or modified%0D%0Acopies of this licensed document, and changing it is allowed as long%0D%0Aas the name is changed.%0D%0A%0D%0A TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION%0D%0A%0D%0A 0. You just DO WHAT THE F*CK YOU WANT TO.%0D%0A
%0D%0A--
|
6411e5206bc55f1044031115f3c06f627bf9a8a8
|
Improve get method to get user with all events
|
api/controllers/UserController.js
|
api/controllers/UserController.js
|
/**
* UserController
*
* @description :: Server-side logic for managing users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
var Q = require('q');
module.exports = {
/**
* Basic CRUD
*/
create: function(req, res) {
sails.controllers['user'].add(req.params.all()).then(function(data) {
res.ok(data);
}).catch(function(err) {
res.badRequest(err);
});
},
read: function(req, res) {
sails.controllers['user'].get(req.params.all()).then(function(data) {
res.ok(data);
}).catch(function(err) {
res.badRequest(err);
});
},
update: function(req, res) {
sails.controllers['user'].edit(req.params.all()).then(function(data) {
res.ok(data);
}).catch(function(err) {
res.badRequest(err);
});
},
delete: function(req, res) {
User.destroy(scope).exec(function(err, cb) {
if (err) res.badRequest(err);
res.ok(cb);
});
},
// Function for views
add: function(scope) {
var deferred = Q.defer();
if (!scope) {
deferred.resolve("You can't add undefined record");
}
User.create(scope).exec(function(err, created) {
if (err) return deferred.reject(err);
deferred.resolve(created);
console.log('Created - User');
});
return deferred.promise;
},
get: function(scope) {
var deferred = Q.defer();
if (!scope) {
scope = null;
}
User.find(scope).exec(function(err, readed) {
if (err) return deferred.reject(err);
deferred.resolve(readed);
console.log('Readed - User');
});
return deferred.promise;
},
edit: function(scope) {
var deferred = Q.defer();
if (!scope) {
deferred.resolve("You can't update undefined record");
}
User.update(scope.id, scope).exec(function(err, updated) {
if (err) return deferred.reject(err);
deferred.resolve(updated);
console.log('Updated - User');
});
return deferred.promise;
}
};
|
JavaScript
| 0 |
@@ -1437,32 +1437,57 @@
ser.find(scope).
+populate('participated').
exec(function(er
|
ee7d0b7b3110b89b87d344d6f742b7c01d38ef5a
|
fix path resolving when basisjs-tools and app located on different drives (fixes #12)
|
lib/server/modules/utils.js
|
lib/server/modules/utils.js
|
var path = require('path');
var chalk = require('chalk');
var toolsPath = path.resolve(__dirname + '/../../..');
function ralign(str, len){
while (str.length < len)
str = ' ' + str;
return str;
}
function logMsg(topic, message, verbose){
if (!verbose || module.exports.verbose)
console.log(chalk.cyan(ralign(topic.toLowerCase(), 8)) + ' ' + chalk.white(message));
}
function logWarn(topic, message){
console.log(chalk.red(ralign(topic.toLowerCase(), 8)) + ' ' + chalk.white(message));
}
function relPathBuilder(base){
var cache = {};
return function(filename){
if (cache[filename])
return cache[filename];
filename = path.resolve(base, filename);
if (path.relative(toolsPath, filename)[0] != '.')
return cache[filename] = 'basisjs-tools:/' + path.relative(toolsPath, filename).replace(/\\/g, '/');
return cache[filename] = path.relative(base, filename)
.replace(/\\/g, '/')
.replace(/^([^\.])/, '/$1');
};
}
module.exports = {
verbose: true,
logMsg: logMsg,
logWarn: logWarn,
relPathBuilder: relPathBuilder
};
|
JavaScript
| 0 |
@@ -640,17 +640,29 @@
%5D;%0A%0A
-f
+var resolvedF
ilename
@@ -693,25 +693,44 @@
ename);%0A
-%0A
-if (
+var toolsRelativePath =
path.rel
@@ -750,27 +750,110 @@
th,
-filename)%5B0%5D != '.'
+resolvedFilename);%0A%0A if (toolsRelativePath.charAt(0) != '.' && toolsRelativePath.indexOf(':') == -1
)%0A
@@ -905,42 +905,25 @@
' +
-path.r
+toolsR
elative
-(toolsPath, filename)
+Path
.rep
|
a6e47a89cfae7a6326c446527b5b476c94c22094
|
Fix typo
|
tests/destructuring-string/destructuring-string.es6
|
tests/destructuring-string/destructuring-string.es6
|
var data = 'hello';
function fn() {
var [a] = data;
return a;
}
assertEqual(fn(), 'h');
test(fn);
//
// function fn(a) {
// var [b] = a;
// }
//
// fn('a');
// fn('a');
// %OptimizeFunctionOnNextCall(fn)
// fn('a');
// --trace-escape
|
JavaScript
| 0.999999 |
@@ -101,144 +101,4 @@
n);%0A
-%0A%0A//%0A// function fn(a) %7B%0A// var %5Bb%5D = a;%0A// %7D%0A//%0A// fn('a');%0A// fn('a');%0A// %25OptimizeFunctionOnNextCall(fn)%0A// fn('a');%0A%0A// --trace-escape
|
433e4b2b907f4521a679e455ca961517042c9553
|
Remove the dubagger from the file
|
app/assets/javascripts/company.js
|
app/assets/javascripts/company.js
|
$( document ).on('turbolinks:load', function() {
$('.modal-trigger').on('click',function(){
debugger
$('#modal1').modal();
})
})
|
JavaScript
| 0.000001 |
@@ -91,21 +91,8 @@
()%7B%0A
- debugger%0A
|
fe60f9d5006e9b9f0412337a2400a6593bd416d1
|
use regex for test in babel overrides
|
build/webpack/_development.js
|
build/webpack/_development.js
|
/* eslint key-spacing:0 */
import webpack from 'webpack'
import config from '../../config'
import _debug from 'debug'
const debug = _debug('app:webpack:development')
export default (webpackConfig) => {
debug('Create configuration.')
debug('Override devtool with cheap-module-eval-source-map.')
webpackConfig.devtool = 'cheap-module-eval-source-map'
// ------------------------------------
// Enable HMR if Configured
// ------------------------------------
if (config.compiler_enable_hmr) {
debug('Enable Hot Module Replacement (HMR).')
webpackConfig.entry.app.push(
'webpack-hot-middleware/client?path=/__webpack_hmr'
)
webpackConfig.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
)
webpackConfig.eslint.emitWarning = true
// We need to apply the react-transform HMR plugin to the Babel configuration,
// but _only_ when HMR is enabled. Putting this in the default development
// configuration will break other tasks such as test:unit because Webpack
// HMR is not enabled there, and these transforms require it.
webpackConfig.module.loaders = webpackConfig.module.loaders.map(loader => {
if (loader.loader === 'babel') {
debug('Apply react-transform-hmr to babel development transforms')
if (loader.query.env.development.plugins[0][0] !== 'react-transform') {
debug('ERROR: react-transform must be the first plugin')
return loader
}
const reactTransformHmr = {
transform : 'react-transform-hmr',
imports : ['react'],
locals : ['module']
}
loader.query.env.development.plugins[0][1].transforms
.push(reactTransformHmr)
}
return loader
})
}
return webpackConfig
}
|
JavaScript
| 0.000001 |
@@ -1206,32 +1206,45 @@
r =%3E %7B%0A if
+(/babel/.test
(loader.loader =
@@ -1245,20 +1245,9 @@
ader
- === 'babel'
+)
) %7B%0A
|
1b5aa6b1e338d7472ea41e591a03652f3b549025
|
Fix animation frame
|
svenv/blog/static/blog/js/blog.js
|
svenv/blog/static/blog/js/blog.js
|
/**
* Blog javascript file
* Provides dynamic interaction on frontend
*/
/**
* Logic common for all views
*/
function View() {
'use strict';
/**
* Finds the current view
* @returns {string} The current view
*/
this.getView = function () {
if ($('body').hasClass('categoryview')) {
return new CategoryView();
}
if ($('body').hasClass('postview') || $('body').hasClass('pageview')) {
return new PostView();
}
};
}
/**
* Provides methods for categoryview
*/
function CategoryView() {
'use strict';
this.api_url = '/api/';
this.content_section = $('section#content');
this.fetch_button = $('.fetchposts');
this.articles = this.content_section.children('article');
this.articleLinkSelector = 'header a';
this.transitionInterval = 100;
/**
* Runs the logic for this view
* @returns {Object} fluent interface
*/
this.construct = function () {
this.setUpFetchPosts()
.fadeInArticles()
.setUpRedirectToArticle();
return this;
};
/**
* Binds the fetch button to fetchPosts()
* @returns {Object} fluent interface
*/
this.setUpFetchPosts = function () {
var self = this;
this.fetch_button.click(function (e) {
e.preventDefault();
self.fetchPosts();
});
return this;
};
/**
* Fetches additional posts
* @returns {Object} fluent interface
*/
this.fetchPosts = function () {
var self = this;
$.ajax({
url: self.api_url + 'posts/?format=html&ordering=-date&page=' + self.nextPage(),
success: $.proxy(self._fetchPostsSuccess, self),
error: $.proxy(self._fetchPostsError, self)
});
return this;
};
/**
* Success callback for fetchPosts
* adds the received data to the dom and update the current page value
*/
this._fetchPostsSuccess = function (data) {
$(data).insertBefore(this.fetch_button);
var nodes = $('article').filter(function() {
return $(this).css('opacity') !== '1';
});
this._fadeIn(nodes);
this.setPage(this.nextPage());
};
/**
* Error callback for fetchPosts
* notifies the user that fetching posts has failed
*/
this._fetchPostsError = function () {
this.fetch_button.text('No more posts.');
};
/**
* Calculates the next page
* @returns {number} The next page
*/
this.nextPage = function () {
return this.getPage() + 1;
};
/**
* Gets the current page
* @returns {number} the current page
*/
this.getPage = function () {
return parseInt($('body').attr('data-page'), 10);
};
/**
* Sets the current page
* @param {number} page The new page value
* @returns {Object} fluent interface
*/
this.setPage = function (page) {
$('body').attr('data-page', page);
return this;
};
/**
* Animates articles fading in using CSS3 transitions
* @returns {Object} fluent interface
*/
this.fadeInArticles = function () {
return this._fadeIn(this.articles);
};
/**
* Animates jQuery selected nodes fading in using CSS3 transitions
* @param {Object} set of jQuery nodes
* @returns {Object} fluent interface
*/
this._fadeIn = function (nodes) {
var self = this;
$.each(nodes, function (index) {
var delay = index * self.transitionInterval;
$(this).transition({
'opacity': 1,
'delay': delay
});
});
return this;
};
/**
* Binds articles to redirectToArticle()
* @returns {Object} fluent interface
*/
this.setUpRedirectToArticle = function () {
var self = this;
this.articles.click(function () {
self.redirectToArticle($(this));
});
return this;
};
/**
* Redirect to the permalink of the article
* @param {Object} jQuery node
*/
this.redirectToArticle = function (article) {
var a = article.find(this.articleLinkSelector);
window.location = a.attr('href');
};
}
/**
* Provides methods for postview
*/
function PostView () {
'use strict';
this.disqus_shortname = 'svenv';
this.article_header_image = $('article header img');
this.parallax_ratio = 0.3;
/**
* Runs the logic for this view
* @returns {Object} fluent interface
*/
this.construct = function () {
this.disqus();
this.parallaxHeader();
// Universal requestAnimationFrame
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback){
window.setTimeout(callback, 1000 / 60);
};
})();
return this;
};
/**
* Add Disqus to the current page
* @returns {Object} fluent interface
*/
this.disqus = function () {
if ($('body').hasClass('postview')) {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + this.disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
}
return this;
};
/**
* Create a parallax effect on the header by utilizing requestAnimationFrame
* @returns {Object} fluent interface
*/
this.parallaxHeader = function () {
var self = this;
$(window).scroll(function(){
requestAnimFrame(self._parallaxHeader());
});
return this;
};
/**
* Sets the parallax position of the header
* @returns {Object} fluent interface
*/
this._parallaxHeader = function () {
this.article_header_image.css({
'top': this.parallax_ratio * $(window).scrollTop()
});
return this;
};
}
/**
* Provides main routine, called on ready
*/
function blog() {
'use strict';
// Get base view
var baseView = new View(),
view = baseView.getView();
view.construct();
}
/**
* Calls main routine
*/
$(document).ready(function () {
'use strict';
blog();
});
|
JavaScript
| 0.000001 |
@@ -4694,39 +4694,8 @@
s();
-%0A this.parallaxHeader();
%0A%0A
@@ -5095,24 +5095,55 @@
%7D)();%0A%0A
+ this.parallaxHeader();%0A
retu
@@ -5961,17 +5961,26 @@
axHeader
-(
+.bind(self
));%0A
|
40378e3b8ad8249d475a139f57f97e95f763c196
|
Fix cloud signout path
|
app/assets/javascripts/signOut.js
|
app/assets/javascripts/signOut.js
|
var Fiware = Fiware || {};
Fiware.signOut = (function($, undefined) {
var portals = {
cloud: {
name: 'Cloud',
verb: 'GET',
protocol: 'http',
subdomain: 'cloud',
path: '/#auth/logout'
},
account: {
name: 'Account',
verb: 'GET',
protocol: 'https',
subdomain: 'account',
path: '/users/sign_out'
}
};
var match = window.location.hostname.match(/\.(.*)/);
var domain = match && match[1];
// If domain exists, we are in production environment,
// such as account.testbed.fi-ware.eu
var productionCall = function(currentPortal) {
portalCalls = $.map(portals, function(portal) {
url = portal.protocol + '://' + portal.subdomain + '.' + domain + portal.path;
return $.ajax(url, {
type: portal.verb,
error: function() { console.error("Error signing out " + portal.name); }
});
});
deferredCall(portalCalls);
};
var deferredCall = function(calls) {
$.when.apply($, calls).then(
// success
finish,
// fail
function() {
if (calls.length === 1) {
finish();
} else {
var unfinished = $.grep(calls, function(call) {
return call.state() === "pending";
});
deferredCall(unfinished);
}
});
};
var finish = function() {
window.location.replace('http://' + domain);
};
// Development environment
var developmentCall = function(currentPortal) {
var url = 'http://' + window.location.host + portals[currentPortal].path;
$.ajax(url, {
type: portals[currentPortal].verb,
success: function() {
window.location.replace('http://' + window.location.host);
}
});
};
var call = function(currentPortal) {
if (domain) {
productionCall(currentPortal);
} else {
developmentCall(currentPortal);
}
};
return call;
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -219,14 +219,8 @@
'/
-#auth/
logo
|
26cde6be23223126120519b24e0e10ba49660f23
|
remove extraneous require
|
lib/utils/read-installed.js
|
lib/utils/read-installed.js
|
// Walk through the file-system "database" of installed
// packages, and create a data object related to the
// installed/active versions of each package.
var npm = require("../../npm")
, fs = require("./graceful-fs")
, path = require("path")
, mkdir = require("./mkdir-p")
, asyncMap = require("./async-map")
, semver = require("./semver")
module.exports = readInstalled
function readInstalled (args, cb) {
var showAll = args.length === 0
, data = {}
fs.readdir(npm.dir, function (er, packages) {
// if an error, just assume nothing is installed.
if (er) return cb(null, {})
packages = packages.filter(function (dir) {
return (showAll || args.indexOf(dir) !== -1) && dir.charAt(0) !== "."
})
var pkgDirs = {}
packages.forEach(function (p) {
pkgDirs[p] = path.join(npm.dir, p)
data[p] = {}
})
asyncMap(packages, function (package, cb) {
var active = path.join(pkgDirs[package], "active")
fs.lstat(active, function (er, s) {
if (er || !s.isSymbolicLink()) return cb()
fs.readlink(active, function (er, p) {
if (er) return cb(er)
var activeVersion = path.basename(p)
data[package][activeVersion] = data[package][activeVersion] || {}
data[package][activeVersion].active = true
return cb()
})
})
}, function (package, cb) {
fs.readdir(pkgDirs[package], function (er, versions) {
if (er) {
delete data[package]
return cb() // skip over non-dirs or missing things.
}
asyncMap(versions, function (version, cb) {
if (semver.valid(version)) {
data[package][version] = data[package][version] || {}
}
cb()
}, cb)
})
}, function (er) {
// just return the data object we've created.
cb(er, data)
})
})
}
|
JavaScript
| 0.02835 |
@@ -246,41 +246,8 @@
h%22)%0A
- , mkdir = require(%22./mkdir-p%22)%0A
,
|
8e3d46de4d6d99c685c2debb4855c8dae29c8f1c
|
update setitmeout
|
models/bookmark.js
|
models/bookmark.js
|
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ValidationError = require('mongoose/lib/error/validation'),
utils = require('../utils/function'),
http = require('http'),
url = require('url'),
phantom = require('phantom'),
fs = require('fs'),
request = require('request'),
path = require('path'),
FormData = require('form-data'),
config = require('../config');
var UPLOADFOLDER = 'public/uploads/';
var bookmarkSchema = mongoose.Schema({
url : String,
title : String,
cover : String,
note : String,
categories : { type: Array, index: true, default: ['other'] },
tags : { type: Array, index: true },
created_at : {type : Date, default : Date.now},
updated_at : Date
});
/*
VIRTUAL PATH
*/
bookmarkSchema.virtual('coverpath')
.get(function() {
var cp;
if (config.upload) {
cp = config.upload.remote + 'uploads/'
} else {
cp = '/uploads/'
}
return cp;
});
/*
STATICS METHOD
*/
bookmarkSchema.statics.getCategories = function getCategories(callback) {
// this.mapReduce({
// map : function map(){
// if (!this.categories) {
// return;
// }
// for (index in this.categories) {
// emit(this.categories[index], 1);
// }
// },
// reduce : function reduce(previous, current){
// var count = 0;
// for (index in current) {
// count += current[index];
// }
// return count;
// }
// }, callback);
this.distinct("categories", function(err, categories){
callback(categories.sort());
});
};
bookmarkSchema.statics.getTags = function getTags(callback) {
this.distinct("tags", function(err, tags){
callback(tags.sort());
});
};
bookmarkSchema.statics.prepareData = function prepareData(req){
var data = {};
if(utils.validatePresenceOf(req.body.categories)){
data.categories = req.body.categories;
}
if(utils.validatePresenceOf(req.body.newcategory)){
data.categories = data.categories || [];
data.categories.push(req.body.newcategory);
}
if(utils.validatePresenceOf(req.body.tags)){
data.tags = req.body.tags.split(',');
}
if(utils.validatePresenceOf(req.body.url)){
data.url = req.body.url;
}
if(utils.validatePresenceOf(req.body.note)){
data.note = req.body.note;
}
if(utils.validatePresenceOf(req.body.title)){
data.title = req.body.title;
}
return data;
};
bookmarkSchema.statics.getHomeList = function getHomeList(categories, callback){
var count = 0,
total = categories.length,
data = [];
categories.forEach(function(category, index){
this.find({categories:category})
.sort({
'created_at': -1
})
.limit(5)
.exec(function(err, bookmarks){
count ++;
//ensure order
data[index] = {
category: category,
bookmarks: bookmarks
}
if(count == total){
callback(data);
}
});
}.bind(this));
}
/*
HOOKS
*/
bookmarkSchema.pre('save', function(next){
var self = this,
errors;
if (!utils.validatePresenceOf(this.url)) {
errors = errors || new ValidationError(this);
errors.errors.url = {
path : 'url',
type: 'You must enter an url',
value : this.url
}
}
if(errors){
next(errors)
} else {
//remove whitespace
if(this.tags.length){
this.tags.forEach(function(tag, index){
var t = utils.trim(tag);
if (utils.validatePresenceOf(t)) {
self.tags[index] = t;
} else {
//remove tag of the list
self.tags.splice(index, 1);
}
});
}
var book_url = url.parse(this.url),
options = {
host: book_url.host,
path: book_url.path
};
var httpRequest = http.request(options, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
var titleReg = /<title>(.*)<\/title>/,
title = data.match(titleReg);
self.title = (title && title.length) ? title[1] : self.url;
//@todo
//create screenshot
phantom.create(function(ph){
ph.createPage(function(page){
page.set('viewportSize', {width: 1280, height: 800});
page.set('clipRect', {top: 0, left: 0, width: 1280, height: 800});
page.open(self.url, function(){
var filename = self._id+'.png';
page.render( UPLOADFOLDER + filename);
ph.exit();
self.cover = filename;
setTimeout(function(){
//timeout for draw the preview
if (config.upload) {
//transfert file on a remote server
var img = path.join(__dirname + '/../' + UPLOADFOLDER, filename),
remote = config.upload.remote + config.upload.script,
key = config.upload.key,
form;
form = new FormData();
form.append('origin', key);
form.append('file', fs.createReadStream(img));
form.getLength(function(err,length){
var r = request.post(remote, { headers: { 'content-length': length } }, function(err, res, body){
if (err) {
return console.error('upload failed:', err);
}
next();
});
r._form = form;
});
} else {
next();
}
}, 200);
})
});
});
});
});
httpRequest.on('error', function (e) {
errors = errors || new ValidationError(this);
errors.errors = 'error';
next(errors);
});
httpRequest.end();
}
});
bookmarkSchema.post('remove', function(bookmark) {
fs.unlink('public/uploads/' + bookmark.cover, function (err) {
if (err) {
console.log(err);
}
});
});
var Bookmark = mongoose.model('Bookmark', bookmarkSchema);
module.exports = Bookmark;
|
JavaScript
| 0.000001 |
@@ -7250,17 +7250,17 @@
%7D,
-2
+9
00);%0A
|
7c71b461548eb49c8bf32db67896ad60c0541ba4
|
add body.invalid_request to error checking during auth
|
wunderline-auth.js
|
wunderline-auth.js
|
var app = require('commander')
var inquirer = require('inquirer')
var request = require('request')
var Configstore = require('configstore')
var conf = new Configstore('wunderline')
var wrap = require('wordwrap')(80)
app
.description('Authenticate Wunderline')
.parse(process.argv)
var questions = [
{
name: 'client_id',
message: 'CLIENT ID',
validate: function (input) {
return input.length > 0
}
},
{
name: 'access_token',
message: 'ACCESS TOKEN',
validate: function (input) {
return input.length > 0
}
}
]
console.log(wrap('Please create a Wunderlist Application before you proceed, you can do so over here: https://developer.wunderlist.com/apps/new, once that is done please enter your access token and client id below.'))
inquirer.prompt(questions, function (answers) {
request.get({
json: true,
url: 'https://a.wunderlist.com/api/v1/user',
headers: {
'X-Access-Token': answers.access_token,
'X-Client-ID': answers.client_id
}
}, function (err, res, body) {
if (err || body.error) {
console.error(JSON.stringify(err || body.error, null, 2))
process.exit(1)
}
conf.set('authenticated_at', new Date())
conf.set('client_id', answers.client_id)
conf.set('access_token', answers.access_token)
console.log('Thanks ' + body.name.split(' ')[0] + ', Wunderline has been authenticated.')
})
})
|
JavaScript
| 0.000001 |
@@ -1072,16 +1072,40 @@
dy.error
+ %7C%7C body.invalid_request
) %7B%0A
|
bdb77700d452c479bdbcfdbac4a1f8cdfdaa2ccc
|
handle empty db.
|
models/employee.js
|
models/employee.js
|
'use strict';
const keyMirror = require('keymirror');
const _ = require('lodash');
const db = require('./db');
const Base = require('./base');
var internals = {};
const TYPE = 'Employee';
//uppercase to match usage on client and email sender.
const statuses = keyMirror({
InOffice: null,
OutOfOffice: null,
Sick: null,
Holiday: null
});
module.exports = internals.Employee = function(options) {
options = options || {};
this.name = options.name;
this.email = options.email;
this.status = options.status; //use keymirror
Base.call(this, options);
};
_.extend(internals.Employee, Base);
_.extend(internals.Employee.prototype, Base.prototype);
internals.Employee.prototype.toJSON = function() {
return {
name: this.name,
email: this.email,
status: this.status,
type: TYPE
};
};
internals.Employee.getAll = function() {
return Base.view(`${TYPE}/all`)
.then((employees) => {
return employees.map((employee) => {
return employee;
});
});
};
internals.Employee.getByEmail = function(email) {
return Base.view(`${TYPE}/byEmail`, email);
};
internals.Employee.isValidStatus = function(status) {
return !!statuses[status];
};
internals.Employee.updateStatus = function(email, status) {
return internals.Employee.getByEmail(email)
.then((employee) => {
if (employee && Array.isArray(employee)) {
employee = _.first(employee);
return internals.Employee.update(employee, {
status: status,
dateModified: new Date()
});
}
return null;
});
};
db.save('_design/' + TYPE, {
all: {
map: function(doc) {
if (doc.type === 'Employee') {
emit(doc.id, doc);
}
}
},
byEmail: {
map: function(doc) {
if (doc.type === 'Employee') {
emit(doc.email, doc);
}
}
},
byStatus: {
map: function(doc) {
if (doc.type === 'Employee') {
emit(doc.status, doc);
}
}
},
byName: {
map: function(doc) {
if (doc.type === 'Employee') {
emit(doc.name, doc);
}
}
}
});
|
JavaScript
| 0.000001 |
@@ -914,24 +914,76 @@
oyees) =%3E %7B%0A
+ if (!employees) %7B%0A return %5B%5D;%0A %7D%0A%0A
return
|
d5ef4ea487536f5e73378b8bd8efa0dc4b4b8ea8
|
append user with feedback
|
models/feedback.js
|
models/feedback.js
|
var syBookshelf = require('./base'),
tbFeedback = 'feedback',
Feedback, Feedbacks;
Feedback = module.exports = syBookshelf.Model.extend({
tableName: tbFeedback,
fields: [
'id', 'userid', 'type', 'title', 'body', 'versioncode', 'device', 'posttime'
],
defaults: function () {
return {
posttime: new Date()
};
}
});
Feedbacks = Feedback.Set = syBookshelf.Collection.extend({
model: Feedback,
lister: function (req, qb) {
this.qbWhere(qb, req, req.query, ['id', 'userid', 'type', 'versioncode', 'device'], tbFeedback);
}
});
|
JavaScript
| 0.00001 |
@@ -252,16 +252,63 @@
me'%0A%09%5D,%0A
+%09omitInJSON: %5B'userid'%5D,%0A%09appended: %5B'user'%5D,%0A%0A
%09default
@@ -364,16 +364,95 @@
()%0A%09%09%7D;%0A
+%09%7D,%0A%09user: function () %7B%0A%09%09return this.belongsTo(require('./user'), 'userid');%0A
%09%7D%0A%7D);%0A%0A
|
4213028dbc286f43ae5fd28d9dbfa4786680d52f
|
Add Spinner
|
app/components/audit_log/Index.js
|
app/components/audit_log/Index.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import DocumentTitle from 'react-document-title';
import Dropdown from '../shared/Dropdown';
import Icon from '../shared/Icon';
import Panel from '../shared/Panel';
import PageHeader from '../shared/PageHeader';
import ShowMoreFooter from '../shared/ShowMoreFooter';
import AuditLogRow from './row';
const PAGE_SIZE = 30;
const EVENT_SUBJECTS = [
{ name: 'Any Subject', id: null },
{ name: 'Pipeline events', id: 'PIPELINE' },
{ name: 'Organization events', id: 'ORGANIZATION' }
];
class AuditLogIndex extends React.PureComponent {
static propTypes = {
organization: PropTypes.shape({
name: PropTypes.string.isRequired,
auditEvents: PropTypes.shape({
edges: PropTypes.array
}).isRequired
}).isRequired,
relay: PropTypes.object.isRequired
};
state = {
loading: false
};
render() {
return (
<DocumentTitle title={`Audit Log · ${this.props.organization.name}`}>
<div>
<PageHeader>
<PageHeader.Icon>
<Icon
icon="eye"
className="align-middle mr2"
style={{ width: 40, height: 40 }}
/>
</PageHeader.Icon>
<PageHeader.Title>
Audit Log
</PageHeader.Title>
<PageHeader.Description>
Event log of all organization activity
</PageHeader.Description>
</PageHeader>
{this.renderLogPanel()}
</div>
</DocumentTitle>
);
}
renderLogPanel() {
return (
<Panel>
<Panel.Section>
<Dropdown width={180} ref={(_eventSubjectDropdown) => this._eventSubjectDropdown = _eventSubjectDropdown}>
<div className="underline-dotted cursor-pointer inline-block regular dark-gray">
{EVENT_SUBJECTS.find((subject) => subject.id === this.props.relay.variables.subjectType).name}
</div>
{this.renderEventSubjects()}
</Dropdown>
</Panel.Section>
{this.renderEvents()}
<ShowMoreFooter
connection={this.props.organization.auditEvents}
loading={this.state.loading}
onShowMore={this.handleShowMoreAuditEvents}
/>
</Panel>
);
}
renderEvents() {
const auditEvents = this.props.organization.auditEvents;
if (!auditEvents) {
return (
<Panel.Section className="center">
<Spinner />
</Panel.Section>
);
}
if (auditEvents.edges.length > 0) {
return auditEvents.edges.map(({ node: auditEvent }) => (
<AuditLogRow
key={auditEvent.id}
auditEvent={auditEvent}
/>
));
}
let message = 'There are no audit events';
if (this.props.relay.variables.subjectType) {
message = 'There are no matching audit events';
}
return (
<Panel.Section>
<div className="dark-gray">
{message}
</div>
</Panel.Section>
);
}
handleShowMoreAuditEvents = () => {
this.setState({ loading: true });
this.props.relay.setVariables(
{
pageSize: this.props.relay.variables.pageSize + PAGE_SIZE
},
(readyState) => {
if (readyState.done) {
this.setState({ loading: false });
}
}
);
};
renderEventSubjects() {
return EVENT_SUBJECTS.map((subject) => {
return (
<div
key={`subject-${subject.id}`}
className="btn block hover-bg-silver"
onClick={() => {
this._eventSubjectDropdown.setShowing(false);
this.handleEventSubjectSelect(subject.id);
}}
>
<span className="block">{subject.name}</span>
</div>
);
});
}
handleEventSubjectSelect = (subjectType) => {
this.setState({ loading: true });
this.props.relay.setVariables(
{
pageSize: PAGE_SIZE,
subjectType
},
(readyState) => {
if (readyState.done) {
this.setState({ loading: false });
}
}
);
};
}
export default Relay.createContainer(AuditLogIndex, {
initialVariables: {
pageSize: PAGE_SIZE,
subjectType: null
},
fragments: {
organization: () => Relay.QL`
fragment on Organization {
name
auditEvents(first: $pageSize, subject_type: $subjectType) {
edges {
node {
id
${AuditLogRow.getFragment('auditEvent')}
}
}
${ShowMoreFooter.getFragment('connection')}
}
}
`
}
});
|
JavaScript
| 0.000003 |
@@ -364,16 +364,57 @@
Footer';
+%0Aimport Spinner from '../shared/Spinner';
%0A%0Aimport
|
31cf3ee0d74a0eba53fe0daeb88a914bdbccde89
|
Fix process name
|
src/tasks.js
|
src/tasks.js
|
import nodemailer from 'nodemailer'
import { exec } from 'child_process'
function notifyViaEmail(
subject = 'Message',
text = 'This is a mail.',
to,
from
) {
let sender = from || process.env.NOTIFICATION_FROM || '[email protected]'
let receiver = to || process.env.NOTIFICATION_TO || '[email protected]'
let transporter = nodemailer.createTransport({
sendmail: true,
newline: 'unix',
path: '/usr/sbin/sendmail'
})
transporter.sendMail(
{
from: sender,
to: receiver,
subject: subject,
text: text
},
(error, info) => {
log(`Whoops.Something Wrong, error: ${error},info: ${info}`)
}
)
}
function notifyFailedDeploy(err, stdout, stderr) {
notifyViaEmail(
'部署 xiayang.me 失败',
`
错误: ${err}
输出错误: ${stderr}
详细输出: ${stdout}
时间: ${new Date().getTime()}
`
)
}
function notifySucceededDeploy() {
notifyViaEmail(
'部署 xiayang.me 成功',
`
时间: ${new Date().getTime()}
`
)
}
function log(...parameter) {
console.log(...parameter)
}
function changeDirectory() {
let directory = process.env.SITE_PATH || '~/code/site'
return `cd ${directory} && `
}
function redeploySite() {
const command =
changeDirectory() +
'git pull origin master && yarn build && yarn start && pm2 restart npm'
exec(command, function(error, stdout, stderr) {
if (error) {
notifyFailedDeploy(error, stdout, stderr)
throw error
} else {
notifySucceededDeploy()
}
})
}
export { log, redeploySite }
|
JavaScript
| 0.00152 |
@@ -1345,11 +1345,18 @@
art
-npm
+xiayang.me
'%0D%0A%0D
|
a283345cfd54ad7ce77734814c57019d1b653880
|
Fix for silly default in Station name field
|
models/stations.js
|
models/stations.js
|
var keystone = require('keystone'),
Types = keystone.Field.Types;
var Station = new keystone.List('Station', {
autokey: { from: 'name', path: 'key' }
});
Station.add({
name: { type: String, default: Date.now },
location: { type: Types.Location }
});
Station.register();
|
JavaScript
| 0 |
@@ -190,27 +190,8 @@
ring
-, default: Date.now
%7D,%0A
|
e60575baf846e7e3013a36b2b46d837ae0da831f
|
Keep the default state of loading as false
|
app/components/audit_log/Index.js
|
app/components/audit_log/Index.js
|
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import Panel from '../shared/Panel';
import ShowMoreFooter from '../shared/ShowMoreFooter';
import Spinner from '../shared/Spinner';
import AuditLogRow from './row';
const PAGE_SIZE = 30;
type Props = {
organization: {
name: string,
auditEvents?: {
edges: Array<Object>
}
},
relay: Object
};
type State = {
loading: boolean
};
class AuditLogList extends React.PureComponent<Props, State> {
static propTypes = {
organization: PropTypes.shape({
name: PropTypes.string.isRequired,
auditEvents: PropTypes.shape({
edges: PropTypes.array.isRequired
})
}).isRequired,
relay: PropTypes.object.isRequired
};
state = {
loading: true
};
componentDidMount() {
// Always fetch new audit data when you switch to this component
this.setState({ loading: true });
this.props.relay.forceFetch({ isMounted: true });
}
render() {
return (
<Panel>
{this.renderEvents()}
<ShowMoreFooter
connection={this.props.organization.auditEvents}
loading={this.state.loading}
onShowMore={this.handleShowMoreAuditEvents}
/>
</Panel>
);
}
renderEvents() {
const auditEvents = this.props.organization.auditEvents;
if (!auditEvents) {
return (
<Panel.Section className="center">
<Spinner />
</Panel.Section>
);
}
if (auditEvents.edges.length > 0) {
return auditEvents.edges.map(({ node: auditEvent }) => (
<AuditLogRow
key={auditEvent.id}
auditEvent={auditEvent}
/>
));
}
return (
<Panel.Section>
<div className="dark-gray">
There are no audit events
</div>
</Panel.Section>
);
}
handleShowMoreAuditEvents = () => {
this.setState({ loading: true });
this.props.relay.setVariables(
{
pageSize: this.props.relay.variables.pageSize + PAGE_SIZE
},
(readyState) => {
if (readyState.done) {
this.setState({ loading: false });
}
}
);
};
}
export default Relay.createContainer(AuditLogList, {
initialVariables: {
isMounted: false,
pageSize: PAGE_SIZE
},
fragments: {
organization: () => Relay.QL`
fragment on Organization {
name
auditEvents(first: $pageSize) @include (if: $isMounted) {
edges {
node {
id
${AuditLogRow.getFragment('auditEvent')}
}
}
${ShowMoreFooter.getFragment('connection')}
}
}
`
}
});
|
JavaScript
| 0.999691 |
@@ -806,19 +806,20 @@
oading:
-tru
+fals
e%0A %7D;%0A%0A
|
a24cf796ce43fdc50caa4944d4f6da6479ba8120
|
Fix token upload
|
src/token.js
|
src/token.js
|
import uuid from "uuid/v4";
import log from "./log";
import database from './databases';
const shouldRunCleanup = () => Math.floor(Math.random() * 10) === 0;
export default {
createToken: async (id) => {
try {
const newToken = await database.createToken(id, uuid());
if (newToken) {
log('info', 'Created token successfully');
}
if (shouldRunCleanup()) {
log('info', 'Running token database cleanup');
await database.cleanupTokens();
}
return newToken;
} catch (e) {
log('error', e.stack);
return null;
}
},
consumeToken: async (token, id) => await database.consumeToken(token, id)
};
|
JavaScript
| 0.000018 |
@@ -218,20 +218,18 @@
%7B%0A
-cons
+le
t newTok
@@ -232,16 +232,45 @@
wToken =
+ uuid();%0A const result =
await d
@@ -293,22 +293,24 @@
ken(id,
-uuid()
+newToken
);%0A
@@ -314,24 +314,37 @@
if (
-newToken
+result.rowCount === 1
) %7B%0A
@@ -386,24 +386,69 @@
essfully');%0A
+ %7D else %7B%0A newToken = undefined;%0A
%7D%0A
|
a668f76dfa13fa20e33eaa6773896366926479ed
|
Allow retrieval of non saved values
|
www/js/services.js
|
www/js/services.js
|
angular.module('app.services', [])
.factory("settings", [function () {
// Central settings object containing the settings. Its initialized by querying the settings
// if settings found in local storage have a version smaller
// minCompatibleSettingsVersion they will be cleared.
// REMEMBER: increase minCompatibleSettingsversion and settings-version in the
// settings-Object if you change the settings object!
var minCompatibleSettingsVersion = 2;
var settings = {
"settings-version": 2,
"reconnect": false,
"duration": 5,
"volume": 50,
"volumeProfiles": [
{ name: "Home", volume: 40 },
{ name: "Office", volume: 70 },
{ name: "Outdoor", volume: 90 }
],
"currentVolumeProfile": false,
"mute": false,
"volBeforeMute": 50
};
var storedSettingsVersion = JSON.parse(localStorage.getItem("settings-version"))
if (storedSettingsVersion == null || storedSettingsVersion < minCompatibleSettingsVersion) {
localStorage.clear();
console.log("Settings stored are incompatible with the current app version and",
"were therefore deleted.");
}
// Function to set settings into Localstorage
function setSetting(name, value) {
// Save to local storage as stringified objects. so parsing of e.g. boolean is
// much easier
localStorage.setItem(name, JSON.stringify(value));
}
// Function to query settings by name
// TODO: Use settings setter to persist directly on set from view!?!
// see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/set
function getSetting(name) {
var ret = localStorage.getItem(name);
// Set Default-Value
try {
if (ret == null) {
throw("wrong setting");
} else {
ret = JSON.parse(ret);
}
} catch (err) {
// Catches wrong settings and parse Errors.
console.log("could not get setting " + name + " from local storage!");
ret = settings[name];
setSetting(name, ret);
}
return ret;
}
// Initialize settings!
//settings.getOwnPropertyNames().forEach((item) => {
for (item in settings) {
settings[item] = getSetting(item);
}
// Persist all settings
function persistSettings() {
//settings.getOwnPropertyNames().forEach((item) => {
for (item in settings) {
setSetting(item, settings[item]);
}
}
// Return this services interface
return {
getSetting: getSetting,
setSetting: setSetting,
persistSettings: persistSettings,
settings: settings
};
}])
.factory("dataStorage", [function() {
//TODO Use LokiDB with LokiCordovaFSAdapter
var dataStorage = {};
// This function stores data in the database.
// The current implementation is just a stub
function storeData(type, data)
{
if(dataStorage[type] === undefined)
{
dataStorage[type] = [];
}
dataStorage[type].push(data);
}
function retrieveData(type)
{
return dataStorage[type];
}
return {
storeData: storeData,
retrieveData: retrieveData
}
}]);
|
JavaScript
| 0.000001 |
@@ -3408,24 +3408,105 @@
a(type)%0A %7B%0A
+ if(dataStorage%5Btype%5D == undefined)%0A %7B%0A dataStorage%5Btype%5D = %5B%5D;%0A %7D%0A
return d
|
ceef99d0ba426866f6a9e6ad2e3e3887148840fb
|
Swap add / remove order for program year stewards
|
app/components/detail-stewards.js
|
app/components/detail-stewards.js
|
import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
const { Component, RSVP, computed, inject, isEmpty, isPresent } = Ember;
const { map, all } = RSVP;
const { service } = inject;
export default Component.extend({
store: service(),
programYear: null,
isManaging: false,
bufferStewards: [],
classNameBindings: [':detail-stewards', ':stewards-manager', 'showCollapsible:collapsible'],
editable: true,
showCollapsible: computed('isManaging', 'programYear.stewards.[]', function () {
const isManaging = this.get('isManaging');
const programYear = this.get('programYear');
const stewardIds = programYear.hasMany('stewards').ids();
return !isManaging && stewardIds.get('length');
}),
stewardsBySchool: computed('programYear.stewards.[]', async function(){
const programYear = this.get('programYear');
if (isEmpty(programYear)) {
return [];
}
const stewards = await programYear.get('stewards');
const stewardObjects = await map(stewards.toArray(), async steward => {
const school = await steward.get('school');
const schoolId = isPresent(school)?school.get('id'):0;
const schoolTitle = isPresent(school)?school.get('title'):null;
const department = await steward.get('department');
const departmentId = isPresent(department)?department.get('id'):0;
const departmentTitle = isPresent(department)?department.get('title'):null;
return {
schoolId,
schoolTitle,
departmentId,
departmentTitle,
};
});
const schools = stewardObjects.uniqBy('schoolId');
const schoolData = schools.map(obj => {
const departments = stewardObjects.filterBy('schoolId', obj.schoolId);
const rhett = {
schoolId: obj.schoolId,
schoolTitle: obj.schoolTitle,
departments
};
return rhett;
});
return schoolData;
}),
save: task( function * (){
yield timeout(10);
const programYear = this.get('programYear');
const bufferStewards = this.get('bufferStewards');
let stewards = yield programYear.get('stewards');
let stewardsToRemove = stewards.filter(steward => !bufferStewards.includes(steward));
let stewardsToAdd = bufferStewards.filter(steward => !stewards.includes(steward));
stewardsToAdd.setEach('programYear', programYear);
yield all(stewardsToRemove.invoke('destroyRecord'));
yield all(stewardsToAdd.invoke('save'));
this.set('isManaging', false);
this.set('bufferStewards', []);
}),
manage: task( function * (){
yield timeout(10);
this.get('expand')();
const stewards = yield this.get('programYear.stewards');
this.set('bufferStewards', stewards.toArray());
this.set('isManaging', true);
}),
actions: {
collapse(){
const programYear = this.get('programYear');
const stewardIds = programYear.hasMany('stewards').ids();
if (stewardIds.get('length')) {
this.get('collapse')();
}
},
cancel: function(){
this.set('isManaging', false);
this.set('bufferStewards', []);
},
addStewardToBuffer: function(steward){
//copy the array to didReceiveAttrs gets called on detail-steward-manager
let bufferStewards = this.get('bufferStewards').toArray();
bufferStewards.pushObject(steward);
this.set('bufferStewards', bufferStewards);
},
removeStewardFromBuffer: function(steward){
//copy the array to didReceiveAttrs gets called on detail-steward-manager
let bufferStewards = this.get('bufferStewards').toArray();
bufferStewards.removeObject(steward);
this.set('bufferStewards', bufferStewards);
},
}
});
|
JavaScript
| 0 |
@@ -2379,22 +2379,19 @@
ewardsTo
-Remove
+Add
.invoke(
@@ -2395,21 +2395,12 @@
ke('
-destroyRecord
+save
'));
@@ -2416,35 +2416,38 @@
d all(stewardsTo
-Add
+Remove
.invoke('save'))
@@ -2431,36 +2431,45 @@
oRemove.invoke('
-save
+destroyRecord
'));%0A this.se
|
32941ad0dc28bc31e392ecba152c252954120a7b
|
Update moves.js
|
mods/nuv2/moves.js
|
mods/nuv2/moves.js
|
exports.BattleMovedex = {
"waterpulse": {
inherit: true,
basePower: 80
},
"submission": {
inherit: true,
accuracy: 100,
basePower: 120,
category: "Physical",
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
},
lunardance: {
num: 461,
accuracy: true,
basePower: 0,
category: "Status",
desc: "The user faints and the Pokemon brought out to replace it has its HP and PP fully restored along with having any major status condition cured. Fails if the user is the last unfainted Pokemon in its party.",
shortDesc: "User faints. Replacement is fully healed, with PP.",
id: "lunardance",
isViable: true,
name: "Lunar Dance",
pp: 20,
priority: 0,
isSnatchable: true,
boosts: {
spa: 1,
spe: 1
},
secondary: false,
target: "self",
type: "Psychic"
},
"airslash": {
inherit: true,
basePower: 90,
},
};
|
JavaScript
| 0.000001 |
@@ -1091,15 +1091,436 @@
%0A %7D,%0A
+ %22psyshock%22: %7B%0A%09%09num: 473,%0A%09%09accuracy: 100,%0A%09%09basePower: 90,%0A%09%09category: %22Special%22,%0A%09%09defensiveCategory: %22Physical%22,%0A%09%09desc: %22Deals damage to one adjacent target based on its Defense instead of Special Defense.%22,%0A%09%09shortDesc: %22Damages target based on Defense, not Sp. Def.%22,%0A%09%09id: %22psyshock%22,%0A%09%09isViable: true,%0A%09%09name: %22Psyshock%22,%0A%09%09pp: 10,%0A%09%09priority: 0,%0A%09%09secondary: false,%0A%09%09target: %22normal%22,%0A%09%09type: %22Psychic%22%0A%09%7D,%0A
%7D; %0A %0A
|
5f31902f99ecb9729ddea428734ebaae703c8a62
|
Remove extra new line from log
|
util.js
|
util.js
|
"use strict";
const fs = require("fs");
const prettyDate = function(date) {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return months[date.getUTCMonth()] + " " + date.getUTCDate() + ", " + date.getUTCFullYear();
};
const log = function(text) {
const message = prettyDate(new Date(Date.now())) + ": " + text + "\n";
console.log(message); // eslint-disable-line no-console
fs.appendFile("log.txt", message, function(err) {
if (err) {
return console.log(err); // eslint-disable-line no-console
}
});
};
const ip2Hex = function(address) {
return address.split(".").map(function(octet) {
let hex = parseInt(octet, 10).toString(16);
if (hex.length === 1) {
hex = "0" + hex;
}
return hex;
}).join("");
};
module.exports = {
log,
prettyDate,
ip2Hex,
};
|
JavaScript
| 0.000001 |
@@ -368,15 +368,8 @@
text
- + %22%5Cn%22
;%0A%0A%09
|
9f1c9793c04f2163fcb0fb00b7c6d250ef26e185
|
Update utils.js
|
src/utils.js
|
src/utils.js
|
/*
MagJS v0.27.1
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
(function(mag) {
'use strict';
var utils = {};
utils.isObject = function(obj) {
//For Safari
return Object.prototype.toString.call(obj).substr(-7) == 'Object]';
}
utils.isHTMLEle = function(item) {
return item && item.nodeType && item.nodeType == 1;
}
utils.callHook = function(hookins, key, name, i, data, before) {
if (hookins[name][i].key == key) {
before = {
v: data.value,
k: data.key
}
data.change = false;
hookins[name][i].handler.call(hookins[name][i].context, data);
//if any change
if (before !== {
v: data.value,
k: data.key
}) {
data.change = true
}
}
}
var queue = [],
scheduled = 0;
utils.scheduleFlush = function(fun) {
return new Promise(function(resolve) {
queue.push(fun)
if (!scheduled) {
scheduled = requestAnimationFrame(function(now) {
var task;
while (task = queue.shift()) {
task();
// calculate how many millisends we have
if ((performance.now() - now) >= 16.6) {
break;
}
}
scheduled = 0;
resolve();
//WHY? If the batch errored we may still have tasks queued
// if (queue.length) {
// utils.scheduleFlush();
// }
})
}
})
}
var handlers = []
utils.onLCEvent = function(eventName, index, handler) {
var eventer = eventName + '-' + index;
handlers[eventer] = handlers[eventer] || []
var size = handlers[eventer].push(handler);
//Remove self:
return function() {
return handlers[eventer].splice(size - 1, 1)
}
}
utils.callLCEvent = function(eventName, controller, node, index, once, extra) {
var isPrevented;
utils.runningEventInstance = index;
if (controller && controller[eventName]) {
isPrevented = controller[eventName].call(controller, node, mag.mod.getProps(index), index, extra)
if (once) controller[eventName] = 0
}
// on Handlers
var eventer = eventName + '-' + index;
if (handlers[eventer]) {
for (var handle of handlers[eventer]) {
handle(mag.mod.getState(index), mag.mod.getProps(index));
}
if (once) handlers[eventName] = 0
}
utils.runningEventInstance = -1;
if (isPrevented === false) return true;
}
//UTILITY
utils.copy = function(o) {
return Object.assign({}, o);
}
utils.merge = function() {
return Object.assign.apply({}, arguments);
}
var a = {
i: [],
isItem: function(id) {
return ~a.i.indexOf(id)
},
setItem: function(id) {
a.i[a.i.length] = id
},
getItem: function(id) {
return a.i.indexOf(id)
},
getItemVal: function(index) {
return a.i[index]
},
removeItem: function(id) {
a.i.splice(a.i.indexOf(id), 1)
}
}
utils.items = a
utils.getItemInstanceIdAll = function() {
return a.i
}
utils.getItemInstanceId = function(id) {
if (a.isItem(id)) {
return a.getItem(id)
} else {
a.setItem(id)
return a.getItem(id)
}
}
mag.utils = utils
}(mag));
|
JavaScript
| 0.000001 |
@@ -10,11 +10,11 @@
v0.2
-7.1
+6.9
%0Ahtt
@@ -800,20 +800,16 @@
ue = %5B%5D,
-%0A
schedul
@@ -814,15 +814,11 @@
uled
- = 0;%0A%0A
+=0;
%0A%0A
@@ -995,19 +995,16 @@
unction(
-now
) %7B%0A
@@ -1062,182 +1062,15 @@
())
-%7B%0A task();%0A // calculate how many millisends we have%0A if ((performance.now() - now) %3E= 16.6) %7B%0A break;%0A %7D%0A %7D
+task();
%0A
@@ -1216,31 +1216,8 @@
th)
-%7B%0A // utils.
sche
@@ -1241,14 +1241,25 @@
- // %7D
+%7D)%0A %7D else %7B
%0A
@@ -1255,33 +1255,40 @@
else %7B%0A
-%7D
+resolve(
)%0A %7D%0A %7D)
|
14dd74ae27b03eaedc518e53663472938d6f6861
|
fix json path
|
www/js/services.js
|
www/js/services.js
|
angular.module('jsconfuy.services', [])
.service('Speakers', function ($http, $q){
this.get = function() {
var dfd = $q.defer();
$http.get('https://jsconfuy2015.herokuapp.com/speakers.json')
.success(function(data) {
dfd.resolve(data);
})
.error(function(data) {
dfd.reject(data);
});
return dfd.promise;
};
})
.service('Agenda', function ($http, $q){
this.get = function() {
var dfd = $q.defer();
$http.get('https://jsconfuy2015.herokuapp.com/agenda.json')
.success(function(data) {
var day1 = _.filter(data, function(event){ return event.date =="day1" }),
day2 = _.filter(data, function(event){ return event.date =="day2" });
dfd.resolve({
"day1": day1,
"day2": day2
});
})
.error(function(data) {
dfd.reject(data);
});
return dfd.promise;
};
this.getEvent = function(eventId){
var dfd = $q.defer();
$http.get('https://jsconfuy2015.herokuapp.com/agenda.json')
.success(function(data) {
var event = _.find(data, {id: eventId});
dfd.resolve(event);
})
.error(function(data) {
dfd.reject(data);
});
return dfd.promise;
};
})
;
|
JavaScript
| 0.000252 |
@@ -150,43 +150,8 @@
et('
-https://jsconfuy2015.herokuapp.com/
spea
@@ -432,43 +432,8 @@
et('
-https://jsconfuy2015.herokuapp.com/
agen
@@ -888,43 +888,8 @@
et('
-https://jsconfuy2015.herokuapp.com/
agen
|
7e8d5bb7c5d596278ad44a68d2983919b92ae047
|
fix markdown image uploading.
|
app/components/markdown-editor.js
|
app/components/markdown-editor.js
|
export default Ember.Component.extend({
classNames: ['wh-markdown-editor'],
classNameBindings: ['whMarkdownEditorFullscreen'],
wyMarkdownEditorFullscreen: false,
selectionStart: 0,
didInsertElement: function () {
this.$('.fullscreen-toggle').on('click', this.toggleFullscreen.bind(this));
this.$('textarea').on('keyup', this.updateSelectionStart.bind(this));
this.$('textarea').on('mouseup', this.updateSelectionStart.bind(this));
},
updateSelectionStart: function () {
this.set('selectionStart', this.$('textarea').get(0).selectionStart);
},
toggleFullscreen: function () {
this.toggleProperty('whMarkdownEditorFullscreen');
this.$('.fullscreen-toggle').toggleClass('icon-fullscreen icon-resize-small');
Ember.$('body').toggleClass('body-no-scroll');
if (this.get('whMarkdownEditorFullscreen')) {
this.syncPreview();
this.$('textarea').on('keyup', this.syncPreview.bind(this));
} else {
this.$('textarea').off('keyup', this.syncPreview.bind(this));
}
},
syncPreview: function () {
this.$('.wh-markdown-preview').html(marked(this.$('textarea').val()));
},
actions: {
toggleImageModal: function () {
// fake a control
this.set('fakeImageControl', Ember.Object.create());
// show image upload widget
this.set('showImageModal', true);
},
handleUpload: function (url) {
if (!url) {
return;
}
// hide image upload widget
this.set('showImageModal', false);
if (url.indexOf('http://') === -1) {
url = 'http://' + window.ENV.siteDNS + url;
}
var value = this.$('textarea').val();
var image = '';
var position = this.get('selectionStart');
this.$('textarea').val([value.slice(0, position), image, value.slice(position)].join(''));
}
}
});
|
JavaScript
| 0 |
@@ -1388,19 +1388,24 @@
nction (
-url
+response
) %7B%0A%0A
@@ -1412,16 +1412,38 @@
if (!
+response %7C%7C !response.
url) %7B%0A
@@ -1462,24 +1462,55 @@
n;%0A %7D%0A%0A
+ var url = response.url;%0A%0A
// hid
|
5e31f74de3be06ae64b1673d4e2c92aea7a7a492
|
add support for lucene-style search queries
|
app/containers/SearchPage/saga.js
|
app/containers/SearchPage/saga.js
|
/**
* Gets the repositories of the user from Github
*/
import _ from 'lodash';
import { call, put, takeEvery, select } from 'redux-saga/effects';
import client from 'utils/client';
import makeSelectAuthHeader from '../AuthHeader/selectors';
import {
SEARCH_CHANGED,
AGG_VIEWED,
DATA_FETCHED,
AGG_SELECTED,
AGG_REMOVED,
} from './constants';
import {
searchLoaded,
searchLoadedError,
clearSearchData,
aggLoaded,
aggLoadedError,
searchLoading,
} from './actions';
import searchSelector from './selectors';
export function* loadAgg(data) {
const searchPage = yield select(searchSelector());
if (searchPage.aggs[data.agg].loaded) {
return;
}
try {
const params = yield call(getParams, searchPage, data);
const results = yield call(
client.post,
'/studies/agg_buckets',
Object.assign({}, params, { agg: data.agg })
);
yield put(aggLoaded(data.agg, results.data));
} catch (err) {
yield put(aggLoadedError(data.agg, err));
}
}
export function* getParams(searchPage, data) {
const authHeader = yield select(makeSelectAuthHeader());
const allParams = Object.assign({}, searchPage.params, data.state);
return {
q: searchPage.searchQuery,
pageSize: allParams.pageSize,
sorted: allParams.sorted,
page: allParams.page,
aggFilters: searchPage.aggFilters,
selectedColumns: Object.keys(_.get(authHeader, 'user.search_result_columns') || {}),
};
}
export function* doSearch(data) {
let url = '/studies';
const { type } = data;
let { searchQuery } = data;
const searchPage = yield select(searchSelector());
if (searchQuery !== undefined) {
if (searchPage.searchQuery !== searchQuery && type === SEARCH_CHANGED) {
yield put(clearSearchData());
}
} else if (searchPage.searchQuery && type !== SEARCH_CHANGED) {
searchQuery = searchPage.searchQuery;
}
if (searchQuery !== undefined) {
url = `/studies/search/${searchQuery}`;
} else {
url = '/studies';
}
try {
const params = yield call(getParams, searchPage, data);
const results = yield call(client.post, `${url}/json`, params);
const resultActionData = Object.assign({}, { searchQuery }, { state: data.state || searchPage.params }, results.data);
yield put(searchLoaded(resultActionData));
} catch (err) {
yield put(searchLoadedError(err));
}
}
export function* dataFetched(data) {
const searchPage = yield select(searchSelector());
if (searchPage.params !== data.state) {
yield put(searchLoading());
yield call(doSearch, Object.assign({}, { searchQuery: searchPage.searchQuery, params: searchPage.state }, data));
}
}
export function* handleAgg(action) {
yield put(searchLoading());
yield call(doSearch, action);
}
/**
* Root saga manages watcher lifecycle
*/
export default function* loadSearch() {
yield takeEvery(SEARCH_CHANGED, doSearch);
yield takeEvery(AGG_VIEWED, loadAgg);
yield takeEvery(DATA_FETCHED, dataFetched);
yield takeEvery(AGG_SELECTED, handleAgg);
yield takeEvery(AGG_REMOVED, handleAgg);
}
|
JavaScript
| 0 |
@@ -1916,17 +1916,17 @@
url =
-%60
+'
/studies
@@ -1936,24 +1936,9 @@
arch
-/$%7BsearchQuery%7D%60
+'
;%0A
|
8024f47ca6c5221d459365185d44b7027fd2b086
|
clear ha timeout before adding a new one
|
mw/awareness/ha.js
|
mw/awareness/ha.js
|
'use strict';
var async = require('async');
var drivers = require('soajs.core.drivers');
var coreModules = require("soajs.core.modules");
var core = coreModules.core;
var param = null;
var regEnvironment = (process.env.SOAJS_ENV || "dev");
regEnvironment = regEnvironment.toLowerCase();
var awarenessCache = {};
var lib = {
"constructDriverParam": function (serviceName) {
var info = core.registry.get().deployer.selected.split('.');
var deployerConfig = core.registry.get().deployer.container[info[1]][info[2]];
let strategy = process.env.SOAJS_DEPLOY_HA;
if (strategy === 'swarm') {
strategy = 'docker';
}
var options = {
"strategy": strategy,
"driver": info[1] + "." + info[2],
"deployerConfig": deployerConfig,
"soajs": {
"registry": core.registry.get()
},
"model": {},
"params": {
"env": regEnvironment
}
};
if (serviceName) {
options.params.serviceName = serviceName;
}
return options;
},
"getLatestVersion": function (serviceName, cb) {
var options = lib.constructDriverParam(serviceName);
drivers.execute({"type": "container", "driver": options.strategy}, 'getLatestVersion', options, cb);
},
"getHostFromCache": function (serviceName, version) {
if (awarenessCache[serviceName] &&
awarenessCache[serviceName][version] &&
awarenessCache[serviceName][version].host) {
param.log.debug('Got ' + awarenessCache[serviceName][version].host + ' from awareness cache');
return awarenessCache[serviceName][version].host;
}
return null;
},
"setHostInCache": function (serviceName, version, hostname) {
if (!awarenessCache[serviceName]) awarenessCache[serviceName] = {};
if (!awarenessCache[serviceName][version]) awarenessCache[serviceName][version] = {};
awarenessCache[serviceName][version].host = hostname;
},
"getHostFromAPI": function (serviceName, version, cb) {
var options = lib.constructDriverParam(serviceName);
if (!version) {
//if no version was supplied, find the latest version of the service
lib.getLatestVersion(serviceName, function (err, obtainedVersion) {
if (err) {
//todo: need to find a better way to do this log
param.log.error(err);
return cb(null);
}
getHost(obtainedVersion);
});
}
else {
getHost(version);
}
function getHost(version) {
options.params.version = version;
drivers.execute({
"type": "container",
"driver": options.strategy
}, 'getServiceHost', options, (error, response) => {
if (error) {
param.log.error(error);
return cb(null);
}
lib.setHostInCache(serviceName, version, response);
param.log.debug('Got ' + response + ' from cluster API');
return cb(response);
});
}
},
"rebuildAwarenessCache": function () {
var myCache = {};
var options = lib.constructDriverParam();
drivers.execute({
"type": "container",
"driver": options.strategy
}, 'listServices', options, (error, services) => {
if (error) {
param.log.error(error);
return;
}
async.each(services, function (oneService, callback) {
var version, serviceName;
if (oneService.labels && oneService.labels['soajs.service.version']) {
version = oneService.labels['soajs.service.version'];
}
if (oneService.labels && oneService.labels['soajs.service.name']) {
serviceName = oneService.labels['soajs.service.name'];
}
//if no version is found, lib.getHostFromAPI() will get it from cluster api
lib.getHostFromAPI(serviceName, version, function (hostname) {
myCache[serviceName] = {};
myCache[serviceName][version] = {host: hostname};
return callback();
});
}, function () {
awarenessCache = myCache;
param.log.debug("Awareness cache rebuilt successfully");
// param.log.debug(awarenessCache);
var cacheTTL = core.registry.get().serviceConfig.awareness.cacheTTL;
if (cacheTTL) {
param.log.debug("rebuilding cache in: " + cacheTTL);
setTimeout(lib.rebuildAwarenessCache, cacheTTL);
}
});
});
}
};
var ha = {
"init": function (_param) {
param = _param;
lib.rebuildAwarenessCache();
},
"getServiceHost": function () {
var serviceName, version, env, cb;
cb = arguments[arguments.length - 1];
switch (arguments.length) {
//controller, cb
case 2:
serviceName = arguments[0];
break;
//controller, 1, cb
case 3:
serviceName = arguments[0];
version = arguments[1];
break;
//controller, 1, dash, cb [dash is ignored]
case 4:
serviceName = arguments[0];
version = arguments[1];
break;
}
env = regEnvironment;
if (serviceName === 'controller') {
if (process.env.SOAJS_DEPLOY_HA === 'kubernetes') {
serviceName += "-v1-service";
}
var info = core.registry.get().deployer.selected.split('.');
var deployerConfig = core.registry.get().deployer.container[info[1]][info[2]];
var namespace = '';
if (deployerConfig && deployerConfig.namespace && deployerConfig.namespace.default) {
namespace = '.' + deployerConfig.namespace.default;
if (deployerConfig.namespace.perService) {
namespace += '-' + env + '-controller-v1';
}
}
return cb(env + "-" + serviceName + namespace);
}
else {
var hostname = lib.getHostFromCache(serviceName, version);
if (hostname) {
return cb(hostname);
}
else {
lib.getHostFromAPI(serviceName, version, cb);
}
}
},
"getLatestVersionFromCache": function (serviceName) {
if (!awarenessCache[serviceName]) return null;
var serviceVersions = Object.keys(awarenessCache[serviceName]), latestVersion = 0;
if (serviceVersions.length === 0) return null;
for (var i = 0; i < serviceVersions.length; i++) {
if (serviceVersions[i] > latestVersion) {
latestVersion = serviceVersions[i];
}
}
if (latestVersion === 0) return null;
return latestVersion;
}
};
module.exports = ha;
|
JavaScript
| 0 |
@@ -305,24 +305,45 @@
ache = %7B%7D;%0A%0A
+let timeout = null;%0A%0A
var lib = %7B%0A
@@ -3951,24 +3951,80 @@
cacheTTL) %7B%0A
+%09%09%09%09%09if (timeout) %7B%0A%09%09%09%09%09%09clearTimeout(timeout);%0A%09%09%09%09%09%7D%0A
%09%09%09%09%09param.l
@@ -4074,16 +4074,26 @@
);%0A%09%09%09%09%09
+timeout =
setTimeo
|
cf69aa55786ac5368e1d526a05668a34754f1bec
|
Add linkOpacity to conf
|
d3/test/helpers/defaultConf.js
|
d3/test/helpers/defaultConf.js
|
var defaultConf = {
linear: {
startLineColor: "#49006a",
endLineColor: "#1d91c0",
hideHalfVisibleLinks: false
},
circular: {
tickSize: 5
},
graphicalParameters: {
canvasWidth: 1000,
canvasHeight: 1000,
karyoHeight: 30,
karyoDistance: 10,
linkKaryoDistance: 20,
tickLabelFrequency: 10,
tickDistance: 100,
treeWidth: 300,
genomeLabelWidth: 150,
fade: 0.1,
buttonWidth: 90
},
minLinkIdentity: 40,
maxLinkIdentity: 100,
midLinkIdentity: 60,
minLinkIdentityColor: "#D21414",
maxLinkIdentityColor: "#1DAD0A",
midLinkIdentityColor: "#FFEE05",
minLinkLength: 100,
maxLinkLength: 5000,
layout: "linear",
tree: {
drawTree: false,
orientation: "left"
},
features: {
showAllFeatures: false,
supportedFeatures: {
gene: {
form: "rect",
color: "#E2EDFF",
height: 30,
visible: false
},
invertedRepeat: {
form: "arrow",
color: "#e7d3e2",
height: 30,
visible: false,
pattern: "woven"
},
nStretch: {
form: "rect",
color: "#000000",
height: 30,
visible: false,
pattern: "lines"
},
repeat: {
form: "rect",
color: "#56cd0f",
height: 30,
visible: false,
pattern: "woven"
}
},
fallbackStyle: {
form: "rect",
color: "#787878",
height: 30,
visible: false
}
},
labels: {
ticks: {
showTicks: true,
showTickLabels: true,
color: "#000000",
size: 10
},
genome: {
showGenomeLabels: true,
color: "#000000",
size: 25
}
},
offset: {
isSet: false,
distance: 1000
}
};
|
JavaScript
| 0 |
@@ -400,16 +400,37 @@
e: 0.1,%0A
+%09%09%09linkOpacity: 0.9,%0A
%09%09%09butto
|
eaeda45d9c2249903c10e9bcdf39df6317a54801
|
remove `.gitignore` placeholder file.
|
tools/lib/tools/create_app.js
|
tools/lib/tools/create_app.js
|
var fs = require('fs');
var path = require('path');
var globals = require("../core/globals");
var param = require("../core/params_analyze.js");
var file = require('../core/file.js');
var CREATE_APP = "create_app.json";
var PREFERENCES = "egretProperties.json";
function run(dir, args, opts) {
var app_name = args[0];
var template_path = opts["-t"];
var h5_path = opts["-f"];
if (!app_name || !h5_path || !template_path) {
globals.exit(1601);
}
globals.log("> compile html project to android/ios ...");
// egert build h5_project -e --runtime native
var cmd = "egret build " + path.resolve(h5_path[0]) + " --runtime native -e";
var cp_exec = require('child_process').exec;
var build = cp_exec(cmd);
build.stderr.on("data", function(data) {
console.log(data);
});
build.on("exit", function(result) {
if (result == 0) {
create_app_from(path.resolve(app_name), path.resolve(h5_path[0]), path.resolve(template_path[0]));
} else {
globals.exit(1604);
}
});
}
function create_app_from(app_name, h5_path, template_path) {
var preferences = read_json_from(path.join(h5_path, PREFERENCES));
if (!preferences || !preferences["native"] || !preferences["native"]["path_ignore"]) {
globals.exit(1602);
}
var app_data = read_json_from(path.join(template_path, CREATE_APP));
if (!app_data) {
globals.exit(1603);
}
// copy from project template
globals.log("> copy from project template ...");
app_data.template.source.forEach(function(source) {
file.copy(path.join(template_path, source), path.join(app_name, source));
});
// replace keyword in content
globals.log("> replace all configure elements ...");
app_data.rename_tree.content.forEach(function(content) {
var target_path = path.join(app_name, content);
var c = file.read(target_path);
c = c.replace(new RegExp(app_data.template_name, "g"), path.basename(app_name));
file.save(target_path, c);
});
// rename keyword in project name
globals.log("> rename project name ...");
app_data.rename_tree.file_name.forEach(function(f) {
var str = path.join(app_name, f);
fs.renameSync(str, str.replace(app_data.template_name, path.basename(app_name)));
});
// copy h5 res into here
globals.log("> copy h5 resources into " + app_name + " ...");
if (preferences["native"]["support_path"] === undefined) {
preferences["native"]["support_path"] = [];
}
var target_list = [];
app_data.game.target.forEach(function(target) {
target_list.push(path.join(app_name, target));
});
preferences["native"]["support_path"] = preferences["native"]["support_path"].concat(target_list);
file.save(path.join(h5_path, PREFERENCES), JSON.stringify(preferences, null, '\t'));
build_copy(h5_path, preferences["native"]["path_ignore"], target_list);
target_list.forEach(function(target) {
file.remove(path.join(target, "egret-game/.gitignore"));
});
}
function read_json_from(json_file) {
if (!fs.existsSync(json_file)) {
return null;
} else {
return JSON.parse(file.read(json_file));
}
}
function build_copy(h5_path, ignore_list, target_path_list) {
target_path_list.forEach(function(target) {
var copy_tree = file.getDirectoryListing(h5_path);
copy_tree.forEach(function(branch) {
branch = path.basename(branch);
if (ignore_list.indexOf(branch) == -1) {
file.copy(path.join(h5_path, branch), path.join(target, branch));
}
});
});
}
function build_copy_from(h5_path) {
var preferences = read_json_from(path.join(h5_path, PREFERENCES));
if (!preferences ||
preferences["native"] === undefined ||
preferences["native"]["path_ignore"] === undefined ||
preferences["native"]["support_path"] === undefined) {
return;
}
build_copy(h5_path, preferences["native"]["path_ignore"], preferences["native"]["support_path"]);
}
function help_title() {
return "从h5游戏生成app\n";
}
function help_example() {
return "egret create_app [app_name] -f [h5_game_path] -t [template_path]";
}
exports.run = run;
exports.help_title = help_title;
exports.help_example = help_example;
exports.build_copy_from = build_copy_from;
|
JavaScript
| 0 |
@@ -3048,19 +3048,8 @@
t, %22
-egret-game/
.git
|
b62b1f8c4b16c3ea99cf114d8b1a8a1b44223f28
|
Change to jade helpers. fixes #14
|
modules/helpers.js
|
modules/helpers.js
|
/**
* Various helpers to be made available
*/
exports = module.exports = function(grunt){
// Modules
var path = require('path'),
_ = require('lodash'),
imageSize = require('image-size');
_.str = require('underscore.string');
_.mixin(_.str.exports());
// Variables
var projectData = grunt.config('project'),
projectDirs = grunt.config('paths');
grunt.config.requires('project');
if (!projectData.copyright) {
projectData.copyright = grunt.template.today('yyyy');
}
// Methods
/**
* Returns the relative path between from and to
* @param {String} from - The from pathway
* @param {String} to - The to pathway
* @returns {String}
*/
var relPath = function(from, to){
// No point with a remote link
if (to.indexOf('://') !== -1) {return to;}
return path.relative(from, to);
};
/**
* Returns the page based on the url parameter or undefined
* @param {String} url - The url to search for
* @returns {Object|Undefined}
*/
var getPageByUrl = function(url){
return _.find(projectData.nav, function(page){
return isCurrentPage(url, page.url);
});
};
/**
* Checks whether path and url match
* @param {String} path - The path or the current page
* @param {String} url - URL of page to check against
* @returns {Boolean}
*/
var isCurrentPage = function(path, url){
return path === url;
};
/**
* Returns an object with various navigation details
* for the current page.
* @param {Object} page - The page to create the navigation object for
* @param {Object} dest - The destination of the page
*
* @returns {Object} nav - The navigation object
* @returns {Array} nav.pages - All available pages
* @returns {Function(url)} nav.isCurrentPage - Checks if the url is this page
* @returns {Object|Undefined} nav.nextPage - The next page available
* @returns {Object|Undefined} nav.prevPage - The previous page available
*/
var navigationDetails = function(page, dest){
var pageIndex = _.indexOf(page);
return {
pages: projectData.nav,
isCurrentPage: _.partial(isCurrentPage, page ? page.url : dest),
nextPage: projectData.nav[pageIndex + 1],
prevPage: projectData.nav[pageIndex - 1]
};
};
/**
* Converts val and name into a HTML attribute
* @param {*} val - The value of the attribute. Can be empty for boolean attributes
* @param {String} name - The name of the attribute
* @return {String}
*/
var toHTMLAttribute = function(val, name){
// Check for boolean attributes
var attr = _.isUndefined(val) ? [' ', name] : [' ', name, '="', val.toString(), '"'];
return attr.join('');
};
/**
* Returns a HTML tag
* @param {String} name - The name of the tag
* @param {String} attributes - The attributes as a string
* @param {Boolean} open - Whether it's an open tag
* @return {String}
*/
var tag = function(name, attributes, open) {
open = _.isBoolean(open) ? open : false;
return ['<', name, attributes, open ? '>' : '/>'].join('');
}
/**
* Creates an image tag taking care of the src and image width and height
* unless overwritten in the attributes property. Will look in the image directory
* property from the gruntfile
* @param {String} dest - The directory linking to the image
* @param {String} src - The name of the image to link to.
* @param {Object} attributes - Object containing all the attributes
* @returns {String}
*/
var imageTag = function(dest, src, attributes){
var remoteImg = src.indexOf('://') !== -1,
dimensions;
attributes = _.extend({alt: ' '}, attributes || {});
// Only getting dimensions for local images
if (!remoteImg) {
src = [projectDirs.img, src].join('/');
dimensions = imageSize(['source', src].join('/'));
// Default to attributes width or height over actual width and height
attributes.width = attributes.width || dimensions.width;
attributes.height = attributes.height || dimensions.height;
src = relPath(dest, src);
}
attributes = _.map(attributes, toHTMLAttribute);
attributes.unshift(toHTMLAttribute(src, 'src')); // Putting src first
return tag('img', attributes.join(''));
};
/**
* Helper functions specific to the Jade language (http://jade-lang.com/)
* @param {String} dest - The destination of the file being exported
* @param {String} src - The src files used to create the jade file
*
* @returns {Object} jade - Jade helper object
* @returns {Underscore} jade._ - Underscore.JS and Underscore.string
* @returns {Function(url)} jade.relPath - Returns the relative path to this page
* @returns {Object} jade.project - The data from the project json file
* @returns {String} jade.pageTitle - The title for this page
* @returns {String} jade.imageTag - Creates an image tag with width and height set automatically
*/
exports.jade = function(dest, src){
var cwd = grunt.task.current.target === 'build' ? projectDirs.build : projectDirs.tmp,
srcDest = dest;
dest = dest.replace(cwd + '/', '');
var destDir = path.dirname(dest),
page = getPageByUrl(dest);
return {
_: _,
relPath: _.partial(relPath, destDir),
navigation: navigationDetails(page),
project: projectData,
pageTitle: page && page.title || undefined,
imageTag: _.partial(imageTag, destDir)
};
}
};
|
JavaScript
| 0 |
@@ -1977,16 +1977,33 @@
indexOf(
+projectData.nav,
page);%0A%0A
|
1799b5b804101414330bc3881acd0d835657a4e9
|
make vary macro output more verbose - absolutely zero help with debugging
|
vary.js
|
vary.js
|
//
// In C, it's difficult to have code that is variadic based on run time
// parameters. For instance you can't make C easily create a long as variable
// "a" in some cases and a byte as variable "a" in other cases based on some
// runtime variable's contents. You have to switch based on the type, often
// allocate memory and do a lot of extra work, and that makes everything
// complicated and time consuming to write.
//
// This code creates some macros that make it easier to write C code that
// varies by type.
//
// TODO VARY_*() macros need to handle general list more robustly
// TODO VARY_*() should be able to cast to best sizes in some circumstances
// TODO consider switching to ribosome of these kinds of scripts
//
var lib = require('./common.js');
function skip(t) {
t=t[1];
return (lib.dontcast.indexOf(t)!=-1)?true:false;
}
console.log(lib.prelude +
"// vary on a single element. unpacks x[i] into a C variable \n"+
"// called _x, of the correct c native type. then executes \n"+
"// your code (stmt). If it's a type that can't be unpacked, \n"+
"// the TAG of the type is set in failvar, you can handle it. \n\n"+
"// VARY_EL varies over one element: x[i]. \n"+
"#define VARY_EL(x,i,stmt,failvar) ({ \\");
var tmpls=[
"\tif(x->t=={{x0}}){/*cant vary {{x2}}*/ failvar={{x0}};}\\",
"\tif(x->t=={{x0}}){/*{{x2}}*/{{x3}} _x=AS_{{x1}}(x,i); stmt;}\\"
];
lib.each(lib.types,function(tx) {
if(skip(tx))tmpl=tmpls[0];
else tmpl=tmpls[1];
var a=[];
for(var i in tx)a["x"+i]=tx[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
});
console.log("})");
console.log("#define VARY_EACH(x,stmt,failvar) ({ \\\n" +
"\tint _i=0,_xn=x->n,_xt=x->t; /*PF(\"VE\");DUMP(x);*/\\");
var tmpl="\tif(_xt=={{x0}}){/*cant vary {{x2}}*/ failvar={{x0}}; }\\";
lib.each(lib.types,function(tx) {
if(skip(tx)){
var a=[];
for(var i in tx)a["x"+i]=tx[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
}
});
var tmpl="\tif(_xt=={{x0}}){/*{{x2}}*/ \\\n" +
"\t\t{{x3}} _x;\\\n" +
"\t\twhile (_i < _xn) { _x=AS_{{x1}}(x,_i); /* printf(\"%d {{5}}\\n\", _i, _x); */ stmt; _i++; }\\\n" +
"\t}\\";
lib.each(lib.types,function(tx) {
if(skip(tx))return;
var a=[];
for(var i in tx)a["x"+i]=tx[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
});
console.log("})");
console.log("#define VARY_EACHLEFT(x,y,stmt,failvar) ({ \\\n" +
"\tint _i=0,_j=0,_xn=x->n,_yn=y->n,_xt=x->t,_yt=y->t;\\");
var tmpl="\tif(xt=={{x0}}||yt=={{x0}}){/*cant vary {{x2}}*/ failvar={{x0}}; }\\";
lib.each(lib.types,function(tx) {
if(skip(tx)){
var a=[];
for(var i in tx)a["x"+i]=tx[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
}
});
var tmpl="\tif(xt=={{x0}}&&yt=={{y0}}){/*{{x2}} x {{y2}}*/ \\\n" +
"\t\t{{x3}} _x;{{y3}} _y; _y=AS_{{x1}}(y,0);\\\n" +
"\t\twhile (_i < _xn) { _x=AS_{{x1}}(x,_i); stmt; _i++; }\\\n" +
"\t}\\";
lib.each(lib.types,function(tx) {
if(skip(tx))return;
lib.each(lib.types, function(ty) {
if(skip(ty))return;
var a=[];
for(var i in tx)a["x"+i]=tx[i];
for(var i in ty)a["y"+i]=ty[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
});
});
console.log("})");
console.log("#define VARY_EACHRIGHT(x,y,stmt,failvar) ({ \\\n" +
"\tint _i=0,_j=0,_xn=x->n,_yn=y->n,_xt=x->t,_yt=y->t;\\");
var tmpl="\tif(xt=={{x0}}||yt=={{x0}}){/*cant vary {{x2}}*/ failvar={{x0}}; }\\";
lib.each(lib.types,function(tx) {
if(skip(tx)){
var a=[];
for(var i in tx)a["x"+i]=tx[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
}
});
var tmpl="\tif(xt=={{x0}}&&yt=={{y0}}){/*{{x2}} x {{y2}}*/ \\\n" +
"\t\t{{x3}} _x;{{y3}} _y; _x=AS_{{x1}}(x,0);\\\n" +
"\t\twhile (_j < _yn) { _y=AS_{{y1}}(y,_j); stmt; _j++; }\\\n" +
"\t}\\";
lib.each(lib.types,function(tx) {
if(skip(tx))return;
lib.each(lib.types, function(ty) {
if(skip(ty))return;
var a=[];
for(var i in tx)a["x"+i]=tx[i];
for(var i in ty)a["y"+i]=ty[i];
console.log(lib.exhaust(lib.projr(lib.repl,a),tmpl));
});
});
console.log("})");
|
JavaScript
| 0 |
@@ -1336,16 +1336,29 @@
%7B%7Bx2%7D%7D*/
+%5C%5C%5Cn%22+%0A%09%22%5Ct%5Ct
%7B%7Bx3%7D%7D _
@@ -1374,17 +1374,29 @@
%7D%7D(x,i);
-
+%5C%5C%5Cn%22+%0A%09%22%5Ct%5Ct
stmt;%7D%5C%5C
|
3194b8b4637e12be4d276ee82a2b3f3ec0017df4
|
Fix typo
|
tests/client/core/middleware/test_cspMiddleware.js
|
tests/client/core/middleware/test_cspMiddleware.js
|
import fs from 'fs';
import MockExpressRequest from 'mock-express-request';
import MockExpressResponse from 'mock-express-response';
import parse from 'content-security-policy-parser';
import log from 'core/logger';
import { csp, getNoScriptStyles } from 'core/middleware';
describe('CSP Middleware', () => {
const exisitingNodeEnv = process.env.NODE_ENV;
afterEach(() => {
process.env.NODE_ENV = exisitingNodeEnv;
delete process.env.NODE_APP_INSTANCE;
});
it('provides the expected csp output for amo with noScriptStyles', () => {
process.env.NODE_ENV = 'production';
process.env.NODE_APP_INSTANCE = 'amo';
jest.resetModules();
// eslint-disable-next-line global-require
const config = require('config');
const middleware = csp({
_config: config,
appName: 'amo',
noScriptStyles: getNoScriptStyles('amo'),
});
const nextSpy = sinon.stub();
const req = new MockExpressRequest();
const res = new MockExpressResponse();
middleware(req, res, nextSpy);
const cspHeader = res.get('content-security-policy');
const policy = parse(cspHeader);
const cdnHost = 'https://addons-amo.cdn.mozilla.net';
expect(policy['default-src']).toEqual(["'none'"]);
expect(policy['object-src']).toEqual(["'none'"]);
expect(policy['frame-src']).toEqual(["'none'"]);
expect(policy['media-src']).toEqual(["'none'"]);
expect(policy['form-action']).toEqual(["'self'"]);
expect(policy['base-uri']).toEqual(["'self'"]);
expect(policy['img-src']).toEqual(expect.arrayContaining([
"'self'",
'data:',
cdnHost,
'https://addons.cdn.mozilla.net',
'https://www.google-analytics.com',
]));
expect(policy['script-src']).toEqual([cdnHost, 'https://www.google-analytics.com/analytics.js']);
expect(policy['script-src']).not.toContain("'self'");
expect(policy['connect-src']).not.toContain("'self'");
expect(policy['connect-src']).toEqual(['https://addons.mozilla.org', 'https://sentry.prod.mozaws.net']);
expect(policy['style-src']).toEqual([cdnHost, "'sha256-DiZjxuHvKi7pvUQCxCVyk1kAFJEUWe+jf6HWMI5agj4='"]);
expect(nextSpy.calledOnce).toEqual(true);
});
it('provides the expected style-src directive when noScriptStyles is false', () => {
process.env.NODE_ENV = 'production';
process.env.NODE_APP_INSTANCE = 'amo';
jest.resetModules();
// eslint-disable-next-line global-require
const config = require('config');
const middleware = csp({
_config: config,
appName: 'amo',
noScriptStyles: false,
});
const nextSpy = sinon.stub();
const req = new MockExpressRequest();
const res = new MockExpressResponse();
middleware(req, res, nextSpy);
const cspHeader = res.get('content-security-policy');
const policy = parse(cspHeader);
const cdnHost = 'https://addons-amo.cdn.mozilla.net';
expect(policy['style-src']).toEqual([cdnHost]);
expect(nextSpy.calledOnce).toEqual(true);
});
it('provides the expected csp output for the disco app', () => {
process.env.NODE_ENV = 'production';
process.env.NODE_APP_INSTANCE = 'disco';
jest.resetModules();
// eslint-disable-next-line global-require
const config = require('config');
const middleware = csp({
_config: config,
appName: 'amo',
noScriptStyles: getNoScriptStyles('disco'),
});
const nextSpy = sinon.stub();
const req = new MockExpressRequest();
const res = new MockExpressResponse();
middleware(req, res, nextSpy);
const cspHeader = res.get('content-security-policy');
const policy = parse(cspHeader);
const cdnHost = 'https://addons-discovery.cdn.mozilla.net';
expect(policy['default-src']).toEqual(["'none'"]);
expect(policy['object-src']).toEqual(["'none'"]);
expect(policy['base-uri']).toEqual(["'self'"]);
expect(policy['frame-src']).toEqual(["'none'"]);
expect(policy['form-action']).toEqual(["'none'"]);
expect(policy['img-src']).toEqual(expect.arrayContaining([
"'self'",
'data:',
cdnHost,
'https://addons.cdn.mozilla.net',
'https://www.google-analytics.com',
]));
expect(policy['script-src']).toEqual([cdnHost, 'https://www.google-analytics.com/analytics.js']);
expect(policy['script-src']).not.toContain("'self'");
expect(policy['connect-src']).not.toContain("'self'");
expect(policy['connect-src']).toEqual(['https://addons.mozilla.org', 'https://sentry.prod.mozaws.net']);
expect(policy['style-src']).toEqual([cdnHost, "'sha256-DiZjxuHvKi7pvUQCxCVyk1kAFJEUWe+jf6HWMI5agj4='"]);
expect(policy['media-src']).toEqual([cdnHost]);
expect(nextSpy.calledOnce).toEqual(true);
});
it('logs if the csp config is false', () => {
const warnStub = sinon.stub();
const middleware = csp({
_config: {
get: sinon.stub().withArgs('CSP').returns(false),
},
_log: {
warn: warnStub,
},
});
const nextSpy = sinon.stub();
const req = new MockExpressRequest();
const res = new MockExpressResponse();
middleware(req, res, nextSpy);
expect(warnStub.calledWith('CSP has been disabled from the config')).toBe(true);
expect(nextSpy.calledOnce).toEqual(true);
});
it('does not blow up if optional args missing', () => {
csp();
});
});
describe('noScriptStyles', () => {
it('should log on ENOENT', () => {
const logStub = sinon.stub(log, 'debug');
sinon.stub(fs, 'readFileSync').throws({
code: 'ENOENT',
message: 'soz',
});
getNoScriptStyles('disco');
sinon.assert.calledWithMatch(logStub, /noscript styles not found at/);
});
it('should log on unknown exception', () => {
const logStub = sinon.stub(log, 'info');
sinon.stub(fs, 'readFileSync').throws({
code: 'WHATEVER',
message: 'soz',
});
getNoScriptStyles('disco');
sinon.assert.calledWithMatch(logStub, /noscript styles could not be parsed from/);
});
});
|
JavaScript
| 0.999999 |
@@ -314,25 +314,24 @@
const exis
-i
tingNodeEnv
@@ -406,17 +406,16 @@
V = exis
-i
tingNode
|
dbd365670a903807387a67e2ef57a101dc9cd8b1
|
Remove console.log
|
tools/prefix-css-requirejs.js
|
tools/prefix-css-requirejs.js
|
var packageJson = require('json!package.json');
var prefix = require('./prefix-css');
module.exports = prefix.bind({}, packageJson, prefixCss);
function prefixCss(prefix, cssText) {
var match, results = [],
cssPattern = new RegExp("([^\\s][\\s\\S]*?)(\\{[\\s\\S]*?\\})", "g"),
selectors, prefixedSelectors;
while (match = cssPattern.exec(cssText)) {
//There might be a concatenation of selectors, explode them
selectors = match[1].split(",");
prefixedSelectors = [];
// if this is something like @font-face, it can't be prefixed so continue
if (selectors.length === 1 && selectors[0].trim().indexOf('@') === 0) {
results.push(selectors.join(','), match[2]);
console.log('skipping', match);
continue;
}
for (var i = 0, l = selectors.length; i < l; i += 1) {
prefixedSelectors.push(prefix + selectors[i]);
}
results.push(prefixedSelectors.join(","), match[2]);
}
return results.join("");
};
|
JavaScript
| 0.000004 |
@@ -736,52 +736,8 @@
%5D);%0A
- console.log('skipping', match);%0A
|
d2a0b3c445fb5950d8669bb1cc4dd97edc5bb952
|
update demo
|
docs/_gulpfile.js
|
docs/_gulpfile.js
|
// balm config demo
var balm = require('balm');
balm.config = {
roots: {
source: 'app'
},
paths: {
source: {
css: 'styles',
js: 'scripts',
img: 'images',
font: 'fonts'
}
},
styles: {
ext: 'scss'
},
scripts: {
entry: {
common: ['jquery'],
main: './app/scripts/main.js'
},
vendors: ['common']
}
// sprites: {
// image: ['img-icon'], // iconPath = app/images/img-icon
// svg: ['svg-icon'] // svgPath = app/images/svg-icon
// },
// cache: true,
// assets: {
// root: '/path/to/your-project', // default: `assets`
// publicPath: 'public',
// subDir: ''
// }
};
balm.go(function(mix) {
if (balm.config.production) {
// manual delete `assets` folder
// mix.remove('./assets');
// publish assets(styles,javascripts,images,fonts) to `./assets/public`
mix.publish();
// publish `index.html` to `./assets/public`
mix.publish('index.html', 'public');
// mix.publish('index.html', 'public', {
// basename: 'yourFilename',
// suffix: '.blade',
// extname: '.php'
// });
}
});
|
JavaScript
| 0.000001 |
@@ -372,16 +372,18 @@
%7D%0A //
+ ,
sprites
@@ -578,17 +578,17 @@
/to/your
--
+_
project'
@@ -728,77 +728,8 @@
) %7B%0A
- // manual delete %60assets%60 folder%0A // mix.remove('./assets');%0A%0A
@@ -779,32 +779,45 @@
,fonts) to %60
-./assets
+/path/to/your_project
/public%60%0A
@@ -869,73 +869,41 @@
to %60
-./assets/public%60%0A mix.publish('index.html', '
+/path/to/your_project/
public
-');%0A
+%60
%0A
- //
mix
@@ -941,21 +941,18 @@
, %7B%0A
-//
-
basename
@@ -972,19 +972,16 @@
me',%0A
- //
suffi
@@ -996,19 +996,16 @@
de',%0A
- //
extna
@@ -1018,19 +1018,16 @@
php'%0A
- //
%7D);%0A %7D
|
c2fde8351e700a9594f0b542d87d6c4f51dc2e22
|
Fix for #311
|
modules/numbers.js
|
modules/numbers.js
|
var writeInt = require('write-int')
module.exports = {
commands: {
num: {
help: 'Asks the bot to greet the channel',
usage: ['lang', 'number'],
command: function (bot, msg) {
if (msg.args.lang === 'jbo') {
msg.args.lang = 'jb'
}
var attempt = writeInt(msg.args.number, { lang: msg.args.lang })
if (attempt) {
return attempt
}
return 'can\'t do that'
}
}
}
}
|
JavaScript
| 0 |
@@ -90,41 +90,44 @@
p: '
-Asks the bot to greet the channel
+Outputs a number in a given language
',%0A
|
a73f2160d0483d028300abad31b4db6946f6f727
|
Make Youtube module not freak out if no videos are found.
|
modules/youtube.js
|
modules/youtube.js
|
/*
Youtube module
@author Mikk Kiilaspää <[email protected]>
*/
var https = require("https");
class Youtube {
constructor(moo) {
this.moo = moo;
this.moo.parser.on("privMsg", this.messageHandler.bind(this));
}
messageHandler(lineVars) {
var self = this;
var regExp = /http(s?):\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)(v=|[A-Za-z0-9_=]*&v=))([\w-]{11}).*/gi;
var matches = lineVars.text.match(regExp);
if (matches !== null) {
var regExp2 = /[a-zA-Z0-9\-\_]{11}/g;
var matches2 = matches[0].match(regExp2);
if (matches2 !== null) {
var matchedID = "";
if (matches2.length > 1) {
var regExp3 = /v=[a-zA-Z0-9\-\_]{11}/g;
matchedID = matches[0].match(regExp3)[0].substring(2);
} else {
matchedID = matches2[0]
}
https.get("https://www.googleapis.com/youtube/v3/videos?part=id,snippet,contentDetails&id="
+ matchedID + "&key=" + this.moo.config.googleAuth, function (res) {
var body = "";
res.on("data", function (chunk) {
body += chunk;
});
res.on("end", function () {
var result = JSON.parse(body);
var message = "";
var to = (lineVars.to.charAt(0) === "#" ? lineVars.to : lineVars.fromNick);
if (result.error !== undefined) {
message += "YouTube error: " + result.error.message;
} else {
message += "YouTube video: \"" + result.items[0].snippet.title + "\""
+ " length: " + result.items[0].contentDetails.duration.substr(2).toLowerCase()
+ " by: " + result.items[0].snippet.channelTitle;
}
self.moo.privmsgCommand(to, message);
});
});
}
}
}
}
module.exports = Youtube;
|
JavaScript
| 0 |
@@ -1455,32 +1455,88 @@
%7D else %7B%0A
+ if (result.pageInfo.totalResults %3E 0) %7B%0A
me
@@ -1603,16 +1603,18 @@
+ %22%5C%22%22%0A
+
@@ -1713,24 +1713,26 @@
+
+ %22 by: %22 +
@@ -1769,16 +1769,109 @@
lTitle;%0A
+ %7D else %7B%0A message += %22Youtube video not found%22;%0A %7D%0A
|
3fa3482b3c02221ae6380980630b35729fc763f9
|
Add test to make sure an error is triggered when ID is missing
|
test/test.js
|
test/test.js
|
test(".once('test1-2') properly executed", function() {
// Create one once('test1-2') call.
$('#test1 span').once('test1-2').data('test1-2', 'foo');
// Create another once('test1-2') call.
$('#test1 span').once('test1-2').data('test1-2', 'bar');
// The data should result to the first once() call.
var data = $('#test1 span').data('test1-2');
ok(data === "foo");
});
test("Called only once, counted", function() {
// Count the number of times once() was called.
$('#test2 span').data('count', 0);
// Create the once() callback.
var callback = function() {
var count = $('#test2 span').data('count');
count++;
$('#test2 span').data('count', count);
};
// Call once() a bunch of times.
for (var i = 0; i < 10; i++) {
$('#test2 span').once('count').each(callback);
}
// Verify that it was only called once.
var count = $('#test2 span').data('count');
ok(count === 1, 'It was called ' + count + ' times.');
});
test("Apply the value to data correctly", function() {
// Verify that the element starts without the class.
var hasData = $('#test3 span').data('jquery-once-test3');
ok(!hasData, 'Value not applied in the beginning.');
// Create one once() call.
$('#test3 span').once('test3');
// Verify the data is applied.
hasData = $('#test3 span').data('jquery-once-test3');
ok(hasData, 'The value is properly applied after once().');
});
test("Remove the value from attribute correctly", function() {
// Create one once() call.
$('#test4 span').once('test4');
// Verify the data is applied.
var hasData = $('#test4 span').data('jquery-once-test4');
ok(hasData, 'The value is properly applied after once().');
// Remove the once property.
$('#test4 span').removeOnce('test4');
hasData = $('#test4 span').data('jquery-once-test4');
ok(!hasData, 'The value is properly removed when called removeOnce().');
});
test("Finding elements correctly through findOnce()", function() {
// Create one once() call.
$('#test5 span').once('test5');
// Find the once'd element through the callback.
var elements = $('span').findOnce('test5').each(function() {
var hasData = $(this).data('jquery-once-test5');
ok(hasData, 'Finding the correct span element after once() through callback.');
});
// Find the once'd element without the callback.
elements = $('span').findOnce('test5');
elements.each(function() {
var hasData = $(this).data('jquery-once-test5');
ok(hasData, 'Finding the correct span element after once().');
});
});
|
JavaScript
| 0 |
@@ -1,12 +1,175 @@
+test(%22ID required%22, function() %7B%0A expect(1);%0A try %7B%0A $(%22#test1 span%22).once();%0A %7D%0A catch (e) %7B%0A ok(e, %22Error is triggered when ID is missing.%22);%0A %7D%0A%7D);%0A%0A
test(%22.once(
|
41e319b1ea5a821acca67d2f6018ec685ec9bece
|
Add JWT auth token when calling the import service to upload a deck
|
services/import.js
|
services/import.js
|
import {Microservices} from '../configs/microservices';
import formdata from 'form-data';
const util = require('util');
const log = require('../configs/log').log;
export default {
name: 'import',
create: (req, resource, params, body, config, callback) => {
req.reqId = req.reqId ? req.reqId : -1;
log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'create', Method: req.method});
let form = new formdata();
//let keys = [];
//for(let k in params) keys.push(k);
// console.log('import service', params.file, params.base64.length);
//create a HTTP POST form request
form.append('file', params.base64);
form.append('filename', params.filename ? params.filename : 'unknown');
form.append('user', params.user);
form.append('jwt', params.jwt);
form.append('language', params.language);
form.append('title', params.title);
form.append('description', params.description);
form.append('theme', params.theme);
form.append('license', params.license);
form.append('tags', JSON.stringify(params.tags));
form.append('contentType', 'application/vnd.openxmlformats-officedocument.presentationml.presentation');
//knownLength: params.file.size ? params.file.size : params.base64.length
// form.submit(Microservices.import.url + '/importPPTX'
let request = form.submit({
port: Microservices.import.port ? Microservices.import.port : 3000,
host: Microservices.import.host,
path: Microservices.import.path ? Microservices.import.path : '/',
protocol: Microservices.import.protocol ? Microservices.import.protocol : 'https:',
timeout: body.timeout
}, (err, res) => {
//res.setTimeout(body.timeout);
if (err) {
console.error(err);
//only callback if no timeout
if (err.toString() !== 'Error: XMLHttpRequest timeout')
callback(err, null);
return;
}
// console.log('result of call to import-microservice', res.headers, res.statusCode);
//res does not contain any data ...
//the response data have to be send via headers
callback(null, res.headers);
});
}
};
// examples for server code
//get file in memory
/*
'use strict';
var http = require('http'),
inspect = require('util').inspect;
var Busboy = require('busboy');
http.createServer(function(req, res) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST" enctype="multipart/form-data">\
<input type="text" name="textfield"><br />\
<input type="file" name="filefield"><br />\
<input type="submit">\
</form>\
</body></html>');
}
}).listen(8003, function() {
console.log('Listening for requests');
});
*/
//get file on disk
/*
var multiparty = require('multiparty');
var http = require('http');
var util = require('util');
http.createServer(function(req, res) {
console.log(req.headers, req.url, req.method);
if (req.url === '/importPPTX' && req.method === 'POST') {
// parse a file upload
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
console.log('got data', fields, files);
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8003);
*/
|
JavaScript
| 0 |
@@ -795,90 +795,8 @@
');%0A
- form.append('user', params.user);%0A form.append('jwt', params.jwt);%0A
@@ -1725,24 +1725,77 @@
body.timeout
+,%0A headers: %7B '----jwt----': params.jwt %7D,
%0A %7D,
|
62ed8e7d01f84c8da20caee14b3d9f2622b4862e
|
Make sure to init chrome extension in all cases.
|
static/js/services/chromeextension.js
|
static/js/services/chromeextension.js
|
/*
* Spreed WebRTC.
* Copyright (C) 2013-2014 struktur AG
*
* This file is part of Spreed WebRTC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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/>.
*
*/
define(["underscore", "jquery"], function(_, $) {
// chromeExtension
return ["$window", "$q", function($window, $q) {
var ChromeExtension = function() {
this.available = false;
this.registry = {};
this.count = 0;
this.e = $({});
this.autoinstall = {};
this.initialize();
};
ChromeExtension.prototype.initialize = function() {
var marker = $window.document.getElementById("chromeextension-available");
if (marker && !this.available) {
this.available = true;
console.log("Chrome extension is available.");
this.e.triggerHandler("available", true);
} else if (!marker && this.available) {
this.available = false;
console.log("Chrome extension is no longer available.");
this.e.triggerHandler("available", false);
}
};
ChromeExtension.prototype.call = function(data) {
var deferred = $q.defer();
var n = this.count++;
this.registry[n] = deferred;
var msg = {
Type: "Call",
Call: data,
n: n
}
$window.postMessage(msg, $window.document.URL);
return deferred.promise;
};
ChromeExtension.prototype.onMessage = function(event) {
var data = event.data;
switch (data.Type) {
case "Call":
var deferred = this.registry[data.n];
if (deferred) {
var call = data.Call;
switch (call.Type) {
case "Result":
delete this.registry[data.n];
//console.log("Call complete with result", call);
deferred.resolve(call.Result);
break;
case "Notify":
//console.log("Notify", call);
deferred.notify(call.Notify);
break;
case "Error":
delete this.registry[data.n];
//console.log("Call failed with error", call);
deferred.reject(call.Error);
break
}
} else {
console.warn("Unknown call reference received", data, this.registry, this);
}
break;
case "Upgrade":
console.log("Extension installed or upgraded", data);
this.initialize();
break;
default:
console.log("Unknown message type", data.Type, data);
break;
}
};
ChromeExtension.prototype.registerAutoInstall = function(installFunc, cancelInstallFunc) {
this.autoinstall.install = installFunc;
this.autoinstall.cancel = cancelInstallFunc;
if (!this.available && installFunc) {
this.e.triggerHandler("available", true);
}
};
var extension = new ChromeExtension();
$window.addEventListener("message", function(event) {
//console.log("message", event.origin, event.source === window, event);
if (event.source === window && event.data.answer) {
// Only process answers to avoid loops.
extension.onMessage(event);
}
});
// Expose.
return extension;
}];
});
|
JavaScript
| 0 |
@@ -1222,27 +1222,8 @@
rker
- && !this.available
) %7B%0A
|
611f34328e030cc799894b87c9ae4426f5b76856
|
remove validation logic that wasn't finished
|
services/schema.js
|
services/schema.js
|
'use strict';
var fs = require('fs'),
path = require('path'),
yaml = require('js-yaml'),
_ = require('lodash'),
db = require('./db'),
bluebird = require('bluebird');
/**
*
*
* Duck-typing
*/
function isComponent(obj) {
return _.isString(obj._type);
}
/**
* @param obj
* @param filter
*
* NOTE: Should probably put this in our lodash utils
*/
function listDeepObjects(obj, filter) {
var cursor, items,
list = [],
queue = [obj];
while(queue.length) {
cursor = queue.pop();
items = _.filter(cursor, _.isObject);
list = list.concat(_.filter(items, filter || _.identity));
queue = queue.concat(items);
}
return list;
}
/**
* Get a single schema
* @param {string} dir
* @returns {{}}
*/
function getSchema(dir) {
if (fs.existsSync(dir)) {
return yaml.safeLoad(fs.readFileSync(path.resolve(dir, 'schema.yaml'), 'utf8'));
} else {
return null;
}
}
/**
* Get a component schema, and all the schema's within.
* @param {string} dir
* @returns {{}}
*/
function getSchemaComponents(dir) {
var schema = getSchema(dir);
if (schema) {
return listDeepObjects(schema, isComponent);
} else {
return null;
}
}
/**
*
* @param {{}} data
* @param {string} schema
* @returns {null||[Error]}
*/
function validateData(data, schema) {
var schema = getSchema(schema);
}
/**
* Find all _ref, and recursively expand them.
*/
function resolveDataReferences(data) {
var referenceProperty = '_ref',
placeholders = listDeepObjects(data, referenceProperty);
return bluebird.all(placeholders).each(function (placeholder) {
return db.get(placeholder[referenceProperty]).then(function (obj) {
//the thing we got back might have its own references
return resolveDataReferences(obj).finally(function () {
_.assign(placeholder, _.omit(obj, referenceProperty));
});
});
}).return(data);
}
module.exports.isComponent = isComponent;
module.exports.listDeepObjects = listDeepObjects;
module.exports.getSchema = getSchema;
module.exports.getSchemaComponents = getSchemaComponents;
module.exports.validateData = validateData;
module.exports.resolveDataReferences = resolveDataReferences;
|
JavaScript
| 0.000008 |
@@ -1187,168 +1187,8 @@
%0A%7D%0A%0A
-/**%0A *%0A * @param %7B%7B%7D%7D data%0A * @param %7Bstring%7D schema%0A * @returns %7Bnull%7C%7C%5BError%5D%7D%0A */%0Afunction validateData(data, schema) %7B%0A var schema = getSchema(schema);%0A%7D%0A%0A
/**%0A
@@ -1928,52 +1928,8 @@
ts;%0A
-module.exports.validateData = validateData;%0A
modu
|
8e5195c7473adb741195f3979a61cdeddb45bec9
|
Fix bug
|
eln/Nmr1dManager.js
|
eln/Nmr1dManager.js
|
'use strict'
define([
'file-saver',
'src/util/api',
'src/util/ui',
] , function (fileSaver, API, UI) {
class Nmr1dManager {
constructor() {
}
handleAction(action) {
switch (action.name) {
case 'downloadSVG':
var blob = new Blob([action.value+""], {type: "application/jcamp-dx;charset=utf-8"});
fileSaver(blob, 'spectra.svg');
break;
case 'toggleNMR1hAdvancedOptions':
API.cache('nmr1hAdvancedOptions', ! API.cache('nmr1hAdvancedOptions'));
break;
case 'reset1d':
case 'reset2d':
var type;
if (action.name === 'reset1d') type = '1'
else if (action.name === 'reset2d') type = '2'
else return;
var legend = API.cache('legend');
if (!legend) {
legend = {
1: {},
2: {}
}
API.cache('legend', legend);
}
legend[type] = {};
type = type + 'd';
API.createData('black', null);
API.createData('annot' + type, null);
API.createData('legend' + type, {});
API.createData('acs', null);
break;
case 'executePeakPicking':
//API.doAction("reset1d");
// the action may be generated by clicking on a line or clicking on the button to
// recalculate the peak picking.
var currentNmr;
if (action.value.dimension) { // Fired from click on row. We can not take variable because it may not exist yet
currentNmr = action.value;
if (currentNmr.dimension > 1) {
API.createData('black2d', currentNmr.jcamp.data);
API.switchToLayer('2D');
return;
} else {
API.switchToLayer('Default layer');
API.createData('black1d', currentNmr.jcamp.data);
}
} else { // we click on the button, show an alert if we want to redo peak picking
currentNmr = API.getData('currentNmr');
if (currentNmr.dimension > 1) {
if (typeof UI != "undefined")
UI.showNotification('Peak picking can only be applied on 1D spectra', 'warning');
return;
}
}
if (action.value.integral) {//Fired from button
this.doNmrAssignement();
} else {
if (!currentNmr.range || ! currentNmr.range.length) {
this.doNmrAssignement();
}
}
API.createData("nmrParams", {
"nucleus": currentNmr.nucleus[0],
"observe": Math.floor(currentNmr.frequency / 10) * 10
});
break;
default:
return false;
}
return true;
}
doNmrAssignement() {
var currentNmr=API.getData('currentNmr');
var jcamp = currentNmr.getChild(['jcamp', 'data']);
console.log(doNmrAssignement);
console.log('jcamp',jcamp.length);
jcamp.then(function(jcamp) {
jcamp = String(jcamp.get());
var ppOptions = JSON.parse(JSON.stringify(API.getData("nmr1hOptions"))) || {};
var integral = ppOptions.integral;
if(!ppOptions.noiseFactor){
ppOptions = {
noiseFactor:0.8,
clean:true,
compile:true,
optimize:false,
integralFn:"sum",
type:"1H"};
}
var spectrum = SD.NMR.fromJcamp(jcamp);
var intFN = 0;
if(ppOptions.integralFn=="peaks"){
intFN=1;
}
var peakPicking = spectrum.nmrPeakDetection({"nH":integral,
realTop:true,
thresholdFactor:ppOptions.noiseFactor,
clean:ppOptions.clean,
compile:ppOptions.compile,
optimize:ppOptions.optimize,
integralFn:intFN,
idPrefix:spectrum.getNucleus()+"",
gsdOptions:{minMaxRatio:0.001, smoothY:false, broadWidth:0},
format:"new"
});
currentNmr.setChildSync(['range'], peakPicking);
});
}
_initializeNMRAssignment() {
var promise = Promise.resolve();
promise = promise.then(() => API.createData('nmr1hOptions', {
"noiseFactor": 0.8,
"clean": true,
"compile": true,
"optimize": false,
"integralFn": "sum",
"integral": 30,
"type": "1H"
})
);
promise=promise.then(() => API.createData('nmr1hOndeTemplates', {
"full": {
"type": "object",
"properties": {
"integral": {
"type": "number",
"title": "value to fit the spectrum integral",
"label": "Integral"
},
"noiseFactor": {
"type": "number",
"title": "Mutiplier of the auto-detected noise level",
"label": "noiseFactor"
},
"clean": {
"type": "boolean",
"title": "Delete signals with integration less than 0.5",
"label": "clean"
},
"compile": {
"type": "boolean",
"title": "Compile the multiplets",
"label": "compile"
},
"optimize": {
"type": "boolean",
"title": "Optimize the peaks to fit the spectrum",
"label": "optimize"
},
"integralFn": {
"type": "string",
"title": "Type of integration",
"label": "Integral type",
"enum": [
"sum",
"peaks"
]
},
"type": {
"type": "string",
"title": "Nucleus",
"label": "Nucleus",
"editable": false
}
}
},
"short": {
"type": "object",
"properties": {
"integral": {
"type": "number",
"title": "value to fit the spectrum integral",
"label": "Integral"
}
}
}
}));
promise=promise.then((nmr1hOndeTemplates) => API.createData('nmr1hOndeTemplate', nmr1hOndeTemplates.short));
return promise;
}
}
return Nmr1dManager;
});
|
JavaScript
| 0.000001 |
@@ -536,32 +536,58 @@
+ var advancedOptions1H = !
API.cache('nmr1
@@ -573,33 +573,33 @@
H = ! API.cache(
-'
+%22
nmr1hAdvancedOpt
@@ -606,12 +606,31 @@
ions
-', !
+%22);%0A
API
@@ -636,17 +636,17 @@
I.cache(
-'
+%22
nmr1hAdv
@@ -661,12 +661,330 @@
ions
-'));
+%22, advancedOptions1H);%0A if (advancedOptions1H) %7B%0A API.createData(%22nmr1hOndeTemplate%22, API.getData(%22nmr1hOndeTemplates%22).full);%0A %7D else %7B%0A API.createData(%22nmr1hOndeTemplate%22, API.getData(%22nmr1hOndeTemplates%22).short);%0A %7D%0A
%0A
|
55ab17d1bc5d11439e7c6a931165ef289b720aff
|
remove obsolete code from file-manager.js,
|
public/js/src/module/file-manager.js
|
public/js/src/module/file-manager.js
|
/**
* Simple file manager with cross-browser support. That uses the FileReader
* to create previews. Can be replaced with a more advanced version that
* obtains files from storage.
*
* The replacement should support the same public methods and return the same
* types.
*/
'use strict';
var store = require( './store' );
var settings = require( './settings' );
var $ = require( 'jquery' );
var utils = require( './utils' );
var coreUtils = require( 'enketo-core/src/js/utils' );
var supported = typeof FileReader !== 'undefined';
var notSupportedAdvisoryMsg = '';
var instanceAttachments;
/**
* Initialize the file manager .
* @return {[type]} promise boolean or rejection with Error
*/
function init() {
return new Promise( function( resolve, reject ) {
if ( supported ) {
resolve( true );
} else {
reject( new Error( 'FileReader not supported.' ) );
}
} );
}
/**
* Whether filemanager is supported in browser
* @return {Boolean}
*/
function isSupported() {
return supported;
}
/**
* Whether the filemanager is waiting for user permissions
* @return {Boolean} [description]
*/
function isWaitingForPermissions() {
return false;
}
/**
* Sets instanceAttachments containing filename:url map
* to use in getFileUrl
*/
function setInstanceAttachments( attachments ) {
instanceAttachments = attachments;
}
/**
* Obtains a url that can be used to show a preview of the file when used
* as a src attribute.
*
* @param {?string|Object} subject File or filename
* @param {?string} filename filename override
* @return {[type]} promise url string or rejection with Error
*/
function getFileUrl( subject, filename ) {
return new Promise( function( resolve, reject ) {
if ( !subject ) {
resolve( null );
} else if ( typeof subject === 'string' ) {
if ( instanceAttachments && ( instanceAttachments.hasOwnProperty( subject ) ) ) {
resolve( instanceAttachments[ subject ] );
} else if ( !store.isAvailable() ) {
// e.g. in an online-only edit view
reject( new Error( 'store not available' ) );
} else {
// obtain file from storage
store.record.file.get( _getInstanceId(), subject )
.then( function( file ) {
if ( file.item ) {
if ( _isTooLarge( file.item ) ) {
reject( _getMaxSizeError() );
} else {
utils.blobToDataUri( file.item )
.then( resolve )
.catch( reject );
}
} else {
reject( new Error( 'File Retrieval Error' ) );
}
} )
.catch( reject );
}
} else if ( typeof subject === 'object' ) {
if ( _isTooLarge( subject ) ) {
reject( _getMaxSizeError() );
} else {
utils.blobToDataUri( subject, filename )
.then( resolve )
.catch( reject );
}
} else {
reject( new Error( 'Unknown error occurred' ) );
}
} );
}
/**
* Obtain files currently stored in file input elements of open record
*
* @return {Promise} array of files
*/
function getCurrentFiles() {
var files = [];
var $fileInputs = $( 'form.or input[type="file"], form.or input[type="text"][data-drawing="true"]' );
// first get any files inside file input elements
$fileInputs.each( function() {
var newFilename;
var file = null;
var canvas = null;
if ( this.type === 'file' ) {
file = this.files[ 0 ]; // Why doesn't this fail for empty file inputs?
} else if ( this.value ) {
canvas = $( this ).closest( '.question' )[ 0 ].querySelector( '.draw-widget canvas' );
if ( canvas ) {
// TODO: In the future, we could do canvas.toBlob()
file = utils.dataUriToBlobSync( canvas.toDataURL() );
file.name = this.value;
}
}
if ( file && file.name ) {
// Correct file names by adding a unique-ish postfix
// First create a clone, because the name property is immutable
// TODO: in the future, when browser support increase we can invoke
// the File constructor to do this.
newFilename = coreUtils.getFilename( file, this.dataset.filenamePostfix );
file = new Blob( [ file ], {
type: file.type
} );
file.name = newFilename;
files.push( file );
}
} );
// then get any file names of files that were loaded as DataURI and have remained unchanged (.i.e. loaded from Storage)
$fileInputs.filter( '[data-loaded-file-name]' ).each( function() {
files.push( $( this ).attr( 'data-loaded-file-name' ) );
} );
return files;
}
/**
* Traverses files currently stored in file input elements of open record to find a specific file.
*
* @return {Promise} array of files
*/
function getCurrentFile( filename ) {
var f;
// relies on all file names to be unique (which they are)
getCurrentFiles().some( function( file ) {
if ( file.name === filename ) {
f = file;
return true;
}
} );
return f;
}
/**
* Obtains the instanceId of the current record.
*
* @return {?string} [description]
*/
function _getInstanceId() {
return settings.recordId;
}
/**
* Whether the file is too large too handle and should be rejected
* @param {[type]} file the File
* @return {Boolean}
*/
function _isTooLarge( file ) {
return file && file.size > _getMaxSize();
}
function _getMaxSizeError() {
return new Error( 'File too large (max ' +
( Math.round( ( _getMaxSize() * 100 ) / ( 1024 * 1024 ) ) / 100 ) +
' Mb)' );
}
/**
* Returns the maximum size of a file
* @return {Number}
*/
function _getMaxSize() {
return settings.maxSize || 5 * 1024 * 1024;
}
module.exports = {
isSupported: isSupported,
notSupportedAdvisoryMsg: notSupportedAdvisoryMsg,
isWaitingForPermissions: isWaitingForPermissions,
init: init,
setInstanceAttachments: setInstanceAttachments,
getFileUrl: getFileUrl,
getCurrentFiles: getCurrentFiles,
getCurrentFile: getCurrentFile
};
|
JavaScript
| 0 |
@@ -484,95 +484,8 @@
);%0A
-%0Avar supported = typeof FileReader !== 'undefined';%0Avar notSupportedAdvisoryMsg = '';%0A%0A
var
@@ -625,17 +625,16 @@
nit() %7B%0A
-%0A
retu
@@ -640,331 +640,31 @@
urn
-new
Promise
-( function( resolve, reject ) %7B%0A if ( supported ) %7B%0A resolve( true );%0A %7D else %7B%0A reject( new Error( 'FileReader not supported.' ) );%0A %7D%0A %7D );%0A%7D%0A%0A/**%0A * Whether filemanager is supported in browser%0A * @return %7BBoolean%7D%0A */%0Afunction isSupported() %7B%0A return supported
+.resolve( true )
;%0A%7D%0A
@@ -5929,92 +5929,8 @@
= %7B%0A
- isSupported: isSupported,%0A notSupportedAdvisoryMsg: notSupportedAdvisoryMsg,%0A
|
ed7de25c2763b36b0bc0460bc977ebbd8af7001a
|
Clear the overriden permissions if the role is changed
|
public/js/views/admin-permissions.js
|
public/js/views/admin-permissions.js
|
define(function (require) {
// Dependencies
var $ = require('jquery')
, _ = require('lodash')
, Backbone = require('backbone')
;
/**
* Setup view
*/
var View = {};
View.initialize = function() {
_.bindAll(this);
// Cache
this.$customize = this.$('[name="_custom_permissions"]');
this.$permissions = this.$('.permissions-list');
this.$permissions_inner = this.$('.permissions-list-inner');
this.$controllers = this.$permissions.find('.controller');
// Listen for clicks on the override checkbox
this.$customize.on('change', this.togglePermissionsOptions);
};
/**
* Toggle the permissions options
*/
View.togglePermissionsOptions = function() {
// Inspect the clicked box
var show = this.$customize.is(':checked');
// Manually set the height whenever it's moving and then clear it when
// animation is done. The animation is defined in CSS.
this.$permissions.height(this.$permissions_inner.outerHeight());
_.delay(_.bind(function() { this.$permissions.height(''); }, this), 300);
// Toggle the open state of the permissions
_.defer(_.bind(function() { this.$el.toggleClass('closed', !show); }, this));
};
// Return view class
return Backbone.View.extend(View);
});
|
JavaScript
| 0.000001 |
@@ -238,16 +238,51 @@
/ Cache%0A
+%09%09this.$role = $('%5Bname=%22role%22%5D');%0A
%09%09this.$
@@ -329,24 +329,24 @@
ssions%22%5D');%0A
-
%09%09this.$perm
@@ -507,16 +507,18 @@
oller');
+%09%09
%0A%0A%09%09// L
@@ -623,16 +623,140 @@
ions);%0A%0A
+%09%09// Check for the role to change and clear the custom permissions%0A%09%09this.$role.on('change', this.clearCustomPermissions);%0A%0A
%09%7D;%0A%0A%09/*
@@ -1324,18 +1324,174 @@
));%0A%09%7D;%0A
-
%09%0A
+%09/**%0A%09 * Clear permissions customizations%0A%09 */%0A%09View.clearCustomPermissions = function() %7B%0A%09%09this.$customize.attr('checked', false).trigger('change');%0A%09%7D;%0A%0A
%09// Retu
|
8ce262a90920724d29a47c6b5dedb52f72f8cf24
|
Test coverage for poznamkyReducer.
|
ui/src/registrator/Poznamky/poznamkyReducer.test.js
|
ui/src/registrator/Poznamky/poznamkyReducer.test.js
|
import deepFreeze from 'deep-freeze';
import ucastniciTestData, {
AKTUALNI_DATUM_KONANI
} from '../../entities/ucastnici/ucastniciTestData';
import { getPoznamky } from './poznamkyReducer';
it('getPoznamky()', () => {
const state = ucastniciTestData;
const selected = [
{ datum: new Date(AKTUALNI_DATUM_KONANI), lines: 1, text: 'přihlášena na startu' },
{ datum: new Date(AKTUALNI_DATUM_KONANI), lines: 1, text: 'poběží s vodičem' },
{
datum: new Date('2019-05-21T08:53:49.154Z'),
lines: 4,
text:
'jedna moc super dlouhá poznámka\r\nkterá pokračuje na dalších a dalších\r\nřádcích dle libosti\r\naž do nekonečna'
}
];
deepFreeze(state);
const { entities } = state;
expect(getPoznamky({ id: '8344bc71dec1e99b7e1d01e', ...entities })).toEqual(selected);
});
|
JavaScript
| 0 |
@@ -1,42 +1,4 @@
-import deepFreeze from 'deep-freeze';%0A
impo
@@ -21,16 +21,16 @@
Data, %7B%0A
+
AKTUAL
@@ -165,16 +165,23 @@
znamky()
+ - n%C4%9Bco
', () =%3E
@@ -634,29 +634,8 @@
%5D;
-%0A deepFreeze(state);
%0A%0A
@@ -662,16 +662,16 @@
state;%0A
-
expect
@@ -755,8 +755,414 @@
d);%0A%7D);%0A
+%0Ait('getPoznamky() - nic', () =%3E %7B%0A const state = ucastniciTestData;%0A%0A const %7B entities %7D = state;%0A expect(getPoznamky(%7B id: '7a09b1fd371dec1e99b7e142', rok: 2018, ...entities %7D)).toEqual(%5B%5D);%0A%7D);%0A%0Ait('getPoznamky() - v%C5%AFbec nic', () =%3E %7B%0A const state = ucastniciTestData;%0A%0A const %7B entities %7D = state;%0A expect(getPoznamky(%7B id: '7a09b1fd371dec1e99b7e142', rok: 2017, ...entities %7D)).toEqual(%5B%5D);%0A%7D);%0A
|
742c0d531fa59bb4444208fec2185ff0e643d6b5
|
Add nonfunctional search bar
|
web/src/js/components/Search/SearchPageComponent.js
|
web/src/js/components/Search/SearchPageComponent.js
|
import React from 'react'
import PropTypes from 'prop-types'
import { isSearchPageEnabled } from 'js/utils/feature-flags'
import {
goTo,
dashboardURL
} from 'js/navigation/navigation'
import LogoWithText from 'js/components/Logo/LogoWithText'
class SearchPage extends React.Component {
constructor (props) {
super(props)
this.state = {
searchFeatureEnabled: isSearchPageEnabled()
}
}
componentDidMount () {
if (!this.state.searchFeatureEnabled) {
goTo(dashboardURL)
}
}
render () {
if (!this.state.searchFeatureEnabled) {
return null
}
return (
<div
data-test-id={'search-page'}
style={{
backgroundColor: '#fff',
minWidth: '100vw',
minHeight: '100vh'
}}
>
<div
style={{
backgroundColor: '#F2F2F2',
padding: 8
// borderBottom: '1px solid #BDBDBD'
}}
>
<LogoWithText
style={{
height: 34,
margin: 8
}}
/>
</div>
</div>
)
}
}
SearchPage.propTypes = {
user: PropTypes.shape({
id: PropTypes.string.isRequired
}),
app: PropTypes.shape({
// TODO: pass these to the MoneyRaised component
// moneyRaised: PropTypes.number.isRequired,
// dollarsPerDayRate: PropTypes.number.isRequired
})
}
SearchPage.defaultProps = {}
export default SearchPage
|
JavaScript
| 0.000003 |
@@ -54,16 +54,122 @@
-types'%0A
+import %7B withStyles %7D from '@material-ui/core/styles'%0Aimport TextField from '@material-ui/core/TextField'%0A
import %7B
@@ -347,16 +347,735 @@
hText'%0A%0A
+const styles = theme =%3E (%7B%0A bootstrapRoot: %7B%0A padding: 0,%0A 'label + &': %7B%0A marginTop: theme.spacing.unit * 3%0A %7D%0A %7D,%0A bootstrapInput: %7B%0A borderRadius: 3,%0A backgroundColor: theme.palette.common.white,%0A border: '1px solid #ced4da',%0A boxShadow: '0rem 0rem 0.02rem 0.02rem rgba(0, 0, 0, 0.1)',%0A fontSize: 16,%0A padding: '10px 12px',%0A transition: theme.transitions.create(%5B'border-color', 'box-shadow'%5D),%0A '&:focus': %7B%0A borderColor: '#bdbdbd',%0A boxShadow: '0rem 0.05rem 0.2rem 0.04rem rgba(0, 0, 0, 0.1)'%0A // borderColor: theme.palette.primary.main,%0A // boxShadow: %600 0 0 0.2rem rgba(157, 75, 163, 0.25)%60%0A %7D%0A %7D,%0A bootstrapFormLabel: %7B%0A fontSize: 18%0A %7D%0A%7D)%0A%0A
class Se
@@ -1345,24 +1345,59 @@
render () %7B%0A
+ const %7B classes %7D = this.props%0A
if (!thi
@@ -1735,17 +1735,19 @@
adding:
-8
+16,
%0A
@@ -1755,189 +1755,892 @@
-// borderBottom: '1px solid #BDBDBD'%0A %7D%7D%0A %3E%0A %3CLogoWithText%0A style=%7B%7B%0A height: 34,%0A margin: 8%0A %7D%7D%0A /
+display: 'flex',%0A alignItems: 'center',%0A justifyContent: 'flex-start'%0A %7D%7D%0A %3E%0A %3CLogoWithText%0A style=%7B%7B%0A width: 100,%0A height: 36%0A %7D%7D%0A /%3E%0A %3Cdiv%0A style=%7B%7B%0A maxWidth: 600,%0A marginLeft: 30,%0A flex: 1%0A %7D%7D%0A %3E%0A %3CTextField%0A placeholder='Search to raise money for charity...'%0A fullWidth%0A InputProps=%7B%7B%0A disableUnderline: true,%0A classes: %7B%0A root: classes.bootstrapRoot,%0A input: classes.bootstrapInput%0A %7D%0A %7D%7D%0A InputLabelProps=%7B%7B%0A shrink: true,%0A className: classes.bootstrapFormLabel%0A %7D%7D%0A /%3E%0A %3C/div
%3E%0A
@@ -2703,16 +2703,56 @@
pes = %7B%0A
+ classes: PropTypes.object.isRequired,%0A
user:
@@ -3045,16 +3045,35 @@
default
+withStyles(styles)(
SearchPa
@@ -3074,9 +3074,10 @@
archPage
+)
%0A
|
5506aaea97de889c3bb9077c378ab8245fd19429
|
Improve readability of test
|
test/event-component-factory-mocha.js
|
test/event-component-factory-mocha.js
|
// event-component-factory-mocha.js
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.should();
chai.use(chaiAsPromised);
var _ = require('underscore');
var noflo = require('noflo');
var componentFactory = require('../src/event-component-factory.js');
var test = require('./common-test');
describe('event-component-factory', function() {
it("should reject undefined definition", function() {
return Promise.resolve().then(componentFactory).should.be.rejected;
});
it("should trigger in port ondata function", function() {
var handler;
return Promise.resolve({
inPorts:{
'input':{
ondata: function(payload) {
handler(payload);
}
}
}
}).then(componentFactory).then(test.createComponent).then(function(component){
// have the handler call a Promise resolve function to
// check that the data sent on the port is passed to the handler
return new Promise(function(callback){
handler = callback;
var socket = noflo.internalSocket.createSocket();
component.inPorts.input.attach(socket);
socket.send("hello");
socket.disconnect();
component.inPorts.input.detach(socket);
});
}).should.become("hello");
});
it("should trigger out port ondata function", function() {
var handler;
return Promise.resolve({
inPorts:{
'input':{
ondata: function(payload) {
this.nodeInstance.outPorts.output.connect();
this.nodeInstance.outPorts.output.send(payload);
this.nodeInstance.outPorts.output.disconnect();
}
}
},
outPorts:{
'output':{
ondata: function(payload) {
handler(payload);
}
}
}
}).then(componentFactory).then(test.createComponent).then(function(component){
return new Promise(function(callback){
handler = callback;
var output = noflo.internalSocket.createSocket();
component.outPorts.output.attach(output);
component.outPorts.output.detach(output);
var input = noflo.internalSocket.createSocket();
component.inPorts.input.attach(input);
input.send("hello");
input.disconnect();
component.inPorts.input.detach(input);
});
}).should.be.fulfilled;
});
});
|
JavaScript
| 0.000248 |
@@ -600,38 +600,69 @@
-return Promise.resolve
+var component = test.createComponent(componentFactory
(%7B%0A
@@ -862,84 +862,10 @@
%7D)
-.then(componentFactory).then(test.createComponent).then(function(component)%7B
+);
%0A
@@ -869,20 +869,16 @@
-
// have
@@ -924,20 +924,16 @@
tion to%0A
-
@@ -997,36 +997,32 @@
handler%0A
-
-
return new Promi
@@ -1029,39 +1029,31 @@
se(function(
-callback)%7B%0A
+done)%7B%0A
@@ -1058,38 +1058,30 @@
handler =
-callback;%0A
+done;%0A
@@ -1122,36 +1122,32 @@
createSocket();%0A
-
comp
@@ -1190,28 +1190,24 @@
-
socket.send(
@@ -1224,28 +1224,24 @@
-
socket.disco
@@ -1253,36 +1253,32 @@
();%0A
-
-
component.inPort
@@ -1301,32 +1301,16 @@
ocket);%0A
- %7D);%0A
@@ -1436,38 +1436,69 @@
-return Promise.resolve
+var component = test.createComponent(componentFactory
(%7B%0A
@@ -2065,89 +2065,11 @@
%7D)
-.then(componentFactory).then(test.createComponent).then(function(component)%7B%0A
+);%0A
@@ -2104,23 +2104,15 @@
ion(
-callback)%7B%0A
+done)%7B%0A
@@ -2133,22 +2133,14 @@
r =
-callback;%0A
+done;%0A
@@ -2201,36 +2201,32 @@
();%0A
-
component.outPor
@@ -2255,70 +2255,8 @@
t);%0A
- component.outPorts.output.detach(output);%0A
@@ -2316,36 +2316,32 @@
();%0A
-
component.inPort
@@ -2371,28 +2371,24 @@
-
-
input.send(%22
@@ -2404,28 +2404,24 @@
-
input.discon
@@ -2432,36 +2432,32 @@
();%0A
-
-
component.inPort
@@ -2487,25 +2487,63 @@
-%7D
+component.outPorts.output.detach(output
);%0A %7D
|
9a353d599c792ff529cf591bbef17792a624fc1f
|
Add tests for processJWTIfExists
|
test/middleware/processJWTIfExists.js
|
test/middleware/processJWTIfExists.js
|
const processJWTIfExists = require('middleware/auth/processJWTIfExists.js');
const {createValidTestJWT} = require('test/helpers.js');
const config = require('config.js');
describe('processJWTIfExists Middleware', function () {
describe('when there is a JWT in the header', function () {
describe('when the JWT is valid', function () {
xit('should set the user identifier on req.feathers.userId', function () {
});
});
describe('when the JWT is invalid', function () {
// TODO: I would prefer to just use the AuthService.createToken method to create
// an invalid token, but the createToken function currently always uses
// the correct config.apiSecret. Is there a way to use the existing AuthService.createToken
// method, but swap out the config.apiSecret it uses with a wrong apiSecret value?
// If yes, would we want to do that here?
xit('should throw an unauthorized error', function () {
});
});
});
xdescribe('when there is a JWT in a cookie', function () {
// TODO: later, if ever.
});
});
|
JavaScript
| 0.000001 |
@@ -66,24 +66,68 @@
xists.js');%0A
+const appFactory = require('appFactory.js')%0A
const %7Bcreat
@@ -266,16 +266,770 @@
n () %7B%0A%0A
+ beforeEach(function () %7B%0A this.app = appFactory();%0A%0A this.app%0A .get('/test-jwt', function (req, res) %7B%0A if (req.feathers.userId === undefined) %7B%0A res.status(600, 'No authorization header was provided.').send();%0A %7D else %7B%0A res.status(200).send(req.feathers);%0A %7D%0A %7D);%0A%0A this.request = chai.request(this.app)%0A .get('/test-jwt');%0A %7D);%0A%0A describe('when there is undefined in the authorization header', function () %7B%0A%0A beforeEach(function (done) %7B%0A this.request%0A .end((err, res) =%3E %7B%0A this.response = res;%0A done();%0A %7D);%0A %7D);%0A%0A it('should immediately call next()', function () %7B%0A expect(this.response).to.have.status(600);%0A %7D);%0A%0A %7D);%0A%0A
descri
@@ -1059,16 +1059,30 @@
in the
+authorization
header',
@@ -1148,33 +1148,295 @@
ion () %7B%0A%0A
-x
+beforeEach(function (done) %7B%0A this.validToken = createValidTestJWT();%0A%0A this.request%0A .set('Authorization', this.validToken)%0A .end((err, res) =%3E %7B%0A this.response = res;%0A done();%0A %7D);%0A %7D);%0A%0A
it('should set t
@@ -1485,32 +1485,104 @@
, function () %7B%0A
+ expect(this.response.body.userId).to.equal('[email protected]');
%0A %7D);%0A%0A
@@ -2048,17 +2048,287 @@
%0A%0A
-x
+beforeEach(function (done) %7B%0A this.invalidToken = 'the price is wrong bob';%0A%0A this.request%0A .set('Authorization', this.invalidToken)%0A .end((err, res) =%3E %7B%0A this.response = res;%0A done();%0A %7D);%0A %7D);%0A%0A
it('shou
@@ -2370,24 +2370,75 @@
nction () %7B%0A
+ expect(this.response.status).to.equal(401);
%0A %7D);%0A
|
f602727ab07f08dc3d829fa8383feb2b5226dd6f
|
Add tests to resultatService
|
test/spec/services/resultatService.js
|
test/spec/services/resultatService.js
|
'use strict';
describe('ResultatService', function () {
describe('processOpenfiscaResult', function() {
var DROITS_DESCRIPTION = {
prestationsNationales : {
caf: {
label: 'CAF',
imgSrc: 'img',
prestations: {
acs: { shortLabel: 'ACS' },
apl: { shortLabel: 'APL' },
ass: { shortLabel: 'ASS' },
aah: { shortLabel: 'AAH' },
rsa: { shortLabel: 'RSA' },
cmu_c: { shortLabel: 'CMU C' },
},
},
},
partenairesLocaux: {},
};
var service, droits, openfiscaResult;
beforeEach(function() {
module('ddsApp');
module(function($provide) {
$provide.constant('droitsDescription', DROITS_DESCRIPTION);
});
inject(function(ResultatService) {
service = ResultatService;
});
openfiscaResult = {
params: {
scenarios: [{
period: 'month:2014-11',
test_case: {
familles: [{
apl: {
'2014-11': 1
}
}],
individus: [{
aah: {
'2014-11':1
}
}]
}
}]
},
value: [{
familles: [{
rsa_non_calculable: {
'2014-11': 'error'
}
}],
individus: [{
acs: {
'2014-11':1
},
cmu_c: {
'2014-11': false
}
}]
}]
};
droits = service.processOpenfiscaResult(openfiscaResult);
});
it('should extract eligibles droits from openfisca result', function() {
expect(droits.droitsEligibles.prestationsNationales.acs).toBeTruthy();
expect(droits.droitsEligibles.prestationsNationales.acs.provider.label).toEqual('CAF');
});
it('should extract reason of uncomputability', function() {
expect(droits.droitsEligibles.prestationsNationales.rsa.montant).toEqual('error');
});
it('should extract injected droits', function() {
expect(droits.droitsInjectes).toEqual([{ shortLabel: 'APL' }, { shortLabel: 'AAH' }]);
});
});
});
|
JavaScript
| 0 |
@@ -350,24 +350,80 @@
l: 'ACS' %7D,%0A
+ missing: %7B shortLabel: 'TBD' %7D,%0A
@@ -763,16 +763,55 @@
ocaux: %7B
+%0A paris: %7B%7D%0A
%7D,%0A
@@ -2646,32 +2646,195 @@
);%0A %7D);%0A%0A
+ it('should not contain irrelevant result', function() %7B%0A expect(droits.droitsEligibles.prestationsNationales.missing).toBeFalsy();%0A %7D);%0A%0A
it('shou
@@ -3157,24 +3157,195 @@
%0A %7D);
+%0A%0A it('should exclude local partenaire without prestation', function() %7B%0A expect(droits.droitsEligibles.partenairesLocaux.paris).toBeFalsy();%0A %7D);
%0A %7D);%0A%7D);
|
9b87e11c2527689ffe8b319acc48519a7b984b37
|
use ipv4
|
Crawler.js
|
Crawler.js
|
const JOIN_URL = 'https://join.gov.tw';
const JOIN_COMPLETED_URL = JOIN_URL + '/idea/index/search/COMPLETED?size=2';
const JOIN_ENDORSING_URL = JOIN_URL + '/idea/index/search/ENDORSING?size=2&status=FirstSigned';
const ARCHIVE_FOLDER = 'archive/';
const COMPLETED_ARCHIVE_FOLDER = ARCHIVE_FOLDER + 'completed/';
const ENDORSING_ARCHIVE_FOLDER = ARCHIVE_FOLDER + 'endorsing/';
const JOIN_DETAIL_URL = JOIN_URL + '/idea/detail/';
const JOIN_SUGGESTION_URL = JOIN_URL + '/idea/export/endorse/suggestion/';
const ENDORSES_JSON = 'endorses.json';
const JOB_URL = [JOIN_COMPLETED_URL, JOIN_ENDORSING_URL];
const JOB_FOLDER = [COMPLETED_ARCHIVE_FOLDER, ENDORSING_ARCHIVE_FOLDER];
var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
var process = require("child_process");
var JOB_INDEX = 0;
var ENDORSES = [];
page.viewportSize = { width: 1024, height: 768 };
console.log("Delete previous data")
console.log("Crawling Start ...")
fs.makeDirectory(ARCHIVE_FOLDER);
execute();
// 執行每一項工作,目前工作有「已完成附議的議題」與「附議中的議題」
function execute() {
if (JOB_INDEX === JOB_URL.length) {
finish();
}
//為避免沒有資料夾,先建立工作相對應的資料夾
fs.makeDirectory(JOB_FOLDER[JOB_INDEX]);
page.open(JOB_URL[JOB_INDEX], function(status) {
if (status !== "success") {
console.log("Unable to access network");
} else {
// 取得searchResult,這個是在JOIN頁面上可以直接取得的物件,工程師留的禮物XD
ENDORSES = page.evaluate(function() { return searchResult.result });
ENDORSES = ENDORSES.map(function(endorse) { return cleanObject(endorse) });
console.log('Get ' + ENDORSES.length + ' endorses...');
if (ENDORSES.length > 0) {
getProjectContent(0);
} else {
console.log('Something wrong, no project on list');
finish();
}
}
});
}
// 採用遞迴的方式把每一個提案的資訊抓回來,因為JS會異步執行,所以採用遞迴作法
function getProjectContent(current) {
console.log(JOIN_DETAIL_URL + ENDORSES[current].id);
var link = JOIN_DETAIL_URL + ENDORSES[current].id;
page.open(link, function(status) {
if (status !== "success") {
console.log("Unable to access network");
} else {
waitFor(
function() {
// idea也是JOIN工程師留的禮物XD,集中放到ENDORSE變數,最後存成一個大JSON
endorse = page.evaluate(function() { return idea });
ENDORSES[current] = endorse;
//但是對每個提案,個別下載附議名單
downloadCSV(ENDORSES[current].id);
},
function() {
console.log("get " + (current + 1) + "/" + ENDORSES.length + " " + ENDORSES[current].title + " content success.");
if (current < ENDORSES.length - 1) {
//要等,不然會被JOIN擋掉....
setTimeout(
function() { //不知道為什麼不用function包起來就不會睡...
getProjectContent(current + 1);
}, 2000);
} else {
console.log("Get " + ENDORSES.length + " endorses content. Job done.");
// 工作完成,把大JSON寫進檔案
fs.write(JOB_FOLDER[JOB_INDEX] + '/' + ENDORSES_JSON, JSON.stringify(ENDORSES, null, 2), 'w');
// 休息10秒後,繼續下一個工作
setTimeout(
function() {
JOB_INDEX += 1;
execute();
}, 10000);
}
});
}
});
}
function downloadCSV(id) {
var execFile = process.execFile;
execFile("curl", ["-XGET", JOIN_SUGGESTION_URL + id], null, function(err, stdout, stderr) {
fs.write(JOB_FOLDER[JOB_INDEX] + '/' + id + '.csv', stdout, 'w');
console.log("execFileSTDERR:", stderr);
})
}
function cleanObject(object) {
for (key in object) {
if (object[key] === null || object[key].length === 0)
delete object[key];
}
return object;
}
function waitFor(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 5000,
start = new Date().getTime(),
condition = -1,
interval = setInterval(function() {
if ((new Date().getTime() - start < maxtimeOutMillis) && condition < 0) {
// If not time-out yet and condition not yet fulfilled
condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
if (condition === true) condition = 0;
if (condition === false) condition = -1;
} else {
if (condition < 0) {
// If condition still not fulfilled (timeout but condition is 'false')
console.log("'waitFor()' timeout");
console.log(onReady);
page.render('waitfor.png');
phantom.exit(1);
} else {
// Condition fulfilled (timeout and/or condition is 'true')
//console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
var func;
if (onReady instanceof Array) {
func = onReady[condition];
} else {
func = onReady;
}
typeof(func) === "string" ?
eval(func): func(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat waitForCheckbox every 250ms
};
function finish() {
// 全部結束 寫入日期 關閉phantomjs
fs.write(ARCHIVE_FOLDER + 'UPDATE_TIMESTAMP', new Date().toLocaleString(), 'w');
phantom.exit();
}
|
JavaScript
| 0.000013 |
@@ -3756,16 +3756,21 @@
%22-XGET%22,
+%22-4%22,
JOIN_SU
|
e129100f6d284fe64c32b02529f265b28f282af9
|
check for non-existence of #init-data and handle gracefully
|
public/javascripts/main.js
|
public/javascripts/main.js
|
requirejs.config({
baseUrl: '',
paths: {
'flight': '/assets/bower_components/flight',
'component': '/assets/javascripts/component',
'page': '/assets/javascripts/page'
}
});
require(
[
'flight/lib/compose',
'flight/lib/registry',
'flight/lib/advice',
'flight/lib/logger',
'flight/lib/debug'
],
function(compose, registry, advice, withLogging, debug) {
debug.enable(true);
compose.mixin(registry, [advice.withAdvice, withLogging]);
var pageComponentsToRequire = ['page/default'];
var initData = JSON.parse($("#init-data").val());
if (typeof(initData.pageName) != "undefined") {
pageComponentsToRequire.push('page/' + initData.pageName);
}
require(pageComponentsToRequire, function() {
var args = Array.prototype.slice.call(arguments, 0);
args.forEach(function (pageInitializer) {
pageInitializer.call(initData);
});
});
}
);
|
JavaScript
| 0 |
@@ -386,24 +386,62 @@
g, debug) %7B%0A
+ var $initData;%0A var initData;%0A%0A
debug.
@@ -450,24 +450,24 @@
able(true);%0A
-
compos
@@ -577,27 +577,94 @@
t'%5D;%0A%0A
-var
+$initData = $('#init-data');%0A if ($initData.length %3E 0) %7B%0A
initData =
@@ -679,22 +679,16 @@
se($
-(%22#
init
--d
+D
ata
-%22)
.val
@@ -692,16 +692,18 @@
val());%0A
+
if
@@ -752,24 +752,26 @@
) %7B%0A
+
+
pageComponen
@@ -813,24 +813,34 @@
.pageName);%0A
+ %7D%0A
%7D%0A%0A
@@ -836,16 +836,17 @@
%7D%0A%0A
+%0A
re
@@ -1014,39 +1014,152 @@
-pageInitializer.call(initData);
+if (typeof(initData) != %22undefined%22) %7B%0A pageInitializer.call(initData);%0A %7D else %7B%0A pageInitializer();%0A %7D
%0A
|
7c2ab02f41730eb3d9ce073893affb945e276c06
|
add support gravatar
|
app/scripts/controllers/signup.js
|
app/scripts/controllers/signup.js
|
'use strict';
angular.module('chatApp')
.controller('SignupCtrl', function ($scope, Auth, $location, mySocket) {
$scope.user = {};
$scope.errors = {};
$scope.register = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.createUser({
name: $scope.user.name,
email: $scope.user.email,
password: $scope.user.password,
})
.then( function() {
// Reconnect to socket as logged in user
mySocket.reconnect();
// Account created, redirect to home
$location.path('/');
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.type;
});
});
}
};
});
|
JavaScript
| 0 |
@@ -389,16 +389,134 @@
ssword,%0A
+ profileImg: %22http://www.gravatar.com/avatar/%22 + md5($scope.user.email.toLowerCase()) + %22?s=200&d=identicon%22%0A
|
7f28254fed423097e9b96e43340d28db3d8f610c
|
Fix CSP compatibility
|
webservice/src/main/resources/static/preferences.js
|
webservice/src/main/resources/static/preferences.js
|
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
render(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "./api/v1/preferences", true);
xhttp.send();
function render(preferences) {
for(var i = 0; i < preferences.length; ++i) {
renderPref(preferences[i]);
}
}
function renderPref(pref) {
console.log(pref);
var div = document.createElement("div");
switch(pref.type) {
case "boolean":
var checked = getBoolean(pref.key, pref.defaultValue) ? "checked " : "";
div.innerHTML = "<input " + checked + " onchange=\"updatedBoolean('" + pref.key + "', this.checked)\" type=\"checkbox\">" + pref.name;
break;
case "enum":
var selectedValue = getEnum(pref.key, pref.defaultValue);
var innerHTML = pref.name + ": <select onchange=\"updatedEnum('" + pref.key + "', this.selectedOptions[0].value)\">";
for(var key in pref.values){
if(!pref.values.hasOwnProperty(key)) continue;
var selected = selectedValue === key ? " selected" : "";
innerHTML += "<option" + selected + " value=\""+ key +"\">" + pref.values[key] + "</option>";
}
innerHTML += "</select>";
div.innerHTML= innerHTML;
break;
default:
div.innerHTML = pref.name + " is not supported by the UI";
}
content.appendChild(div);
}
function updatedBoolean(key, value) {
localStorage.setItem(key, value);
}
function updatedEnum(key, value) {
localStorage.setItem(key, value);
}
function getBoolean(key, defaultValue) {
if(!localStorage.hasOwnProperty(key)){
return defaultValue;
}
return localStorage.getItem(key) === "true";
}
function getEnum(key, defaultValue) {
if(!localStorage.hasOwnProperty(key)){
return defaultValue;
}
return localStorage.getItem(key);
}
|
JavaScript
| 0.000005 |
@@ -588,27 +588,100 @@
ked + %22
-onchange=%5C%22
+type=%5C%22checkbox%5C%22%3E%22 + pref.name;%0A%09%09div.firstElementChild.onchange = function() %7B%0A%09%09%09
updatedB
@@ -687,29 +687,24 @@
Boolean(
-'%22 +
pref.key
+ %22', t
@@ -691,29 +691,24 @@
ean(pref.key
- + %22'
, this.check
@@ -714,42 +714,13 @@
ked)
-%5C%22 type=%5C%22checkbox%5C%22%3E%22 + pref.name
+;%0A%09%09%7D
;%0A%09%09
@@ -847,84 +847,8 @@
lect
- onchange=%5C%22updatedEnum('%22 + pref.key + %22', this.selectedOptions%5B0%5D.value)%5C%22
%3E%22;%0A
@@ -1145,16 +1145,107 @@
erHTML;%0A
+%09%09div.firstElementChild.onchange = function() %7B%0A%09%09%09updatedEnum(pref.key, this.value);%0A%09%09%7D;%0A
%09%09break;
|
65e259ccdef32c9e7049d31cbd4ca17068a77e2e
|
Set cli working dir to null if not defined in cli task take 3
|
plugins/kalabox-cli/lib/tasks.js
|
plugins/kalabox-cli/lib/tasks.js
|
'use strict';
/**
* This is a wrapper to build cli commands when an app has a cli.yml file
*/
module.exports = function(kbox) {
// Node
var fs = require('fs');
var path = require('path');
// Npm
var _ = require('lodash');
kbox.whenAppRegistered(function(app) {
// Load the tasks
if (_.get(app.config.pluginconfig, 'cli') === 'on') {
// Cli tasks and compose yml files
var tasksFile = path.join(app.root, 'cli.yml');
/*
* Return the task defaults
*/
var taskDefaults = function() {
return {
services: ['cli'],
entrypoint: ['/bin/sh', '-c'],
description: 'Run a command against a container'
};
};
/*
* Return a run object
*/
var getRun = function(options) {
return {
compose: app.composeCore,
project: app.name,
opts: {
mode: 'attach',
services: [options.service],
entrypoint: options.entrypoint,
cmd: options.cmd
}
};
};
/*
* Map a mapping to a app config prop
*/
var getMappingProp = function(prop) {
if (_.startsWith(prop, '<') && _.endsWith(prop, '>')) {
return _.get(app, _.trimRight(_.trimLeft(prop, '<'), '>'));
}
else {
return prop;
}
};
// Check for our tasks and then generate tasks if we have a
// file
if (fs.existsSync(tasksFile)) {
var tasks = kbox.util.yaml.toJson(tasksFile);
_.forEach(tasks, function(data, cmd) {
// Merge in default options
var options = _.merge(taskDefaults(), data);
// Build the command task
kbox.tasks.add(function(task) {
task.path = [app.name, cmd];
task.category = 'appCmd';
task.kind = 'delegate';
task.description = options.description;
task.func = function() {
// If our task has a working directory mapping specified lets set
// a working directory plus env so we have something to use to
// drop the user into the right location in the container to run
// their task
// @todo: clean this up so we only call env.setEnv once
if (_.has(data, 'mapping')) {
// Resolve any path mappings that are in config
var dirs = _.map(data.mapping.split(':'), function(path) {
return getMappingProp(path);
});
// Get relevant directories so we can determine the correct
// working directory
var localSplit = path.join(app.root, dirs[0]).split(path.sep);
var pwdSplit = process.cwd().split(path.sep);
var diffDir = _.drop(pwdSplit, localSplit.length).join('/');
var workingDir = path.join(dirs[1], diffDir);
var env = kbox.core.env;
env.setEnv('KALABOX_CLI_WORKING_DIR', workingDir);
}
// Shift off our first cmd arg if its also the entrypoint
// or the name of the command
// @todo: this implies that our entrypoint should be in the path
// and not constructed absolutely
var payload = kbox.core.deps.get('argv').payload;
if (options.entrypoint === payload[0] || options.stripfirst) {
payload.shift();
}
// Set the payload to be the command
options.cmd = payload;
// If we have pre cmd opts then unshift them
if (options.precmdopts) {
options.cmd.unshift(options.precmdopts);
}
// If we have posrt cmd opts then unshift them
if (options.postcmdopts) {
options.cmd.push(options.postcmdopts);
}
// Get teh run definition objecti
var runDef = getRun(options);
// RUN IT!
return kbox.engine.run(runDef);
};
});
});
}
}
});
};
|
JavaScript
| 0.00012 |
@@ -3083,17 +3083,16 @@
%7D%0A%0A
-%0A
|
42c19e54aef5c3cc2e221e96d1bb590dca4dc704
|
Tweak to zero pad times. Closes #31.
|
http/public/javascripts/application.js
|
http/public/javascripts/application.js
|
var Display = {
add_message: function(text) {
$('messages').insert({ bottom: '<li>' + text + '</li>' });
$('messages').scrollTop = $('messages').scrollHeight;
},
message: function(message) {
var text = '<span class="time">\#{time}</span> <span class="user">\#{user}</span> <span class="message">\#{message}</span>';
var d = new Date;
var date_text = d.getHours() + ':' + d.getMinutes();
text = text.interpolate({ time: date_text, room: message['room'], user: this.truncateName(message['user']), message: this.decorateMessage(message['message']) });
this.add_message(text);
},
truncateName: function(text) {
return text.truncate(12);
},
extractURLs: function(text) {
return text.match(/(http:\/\/[^\s]*)/g);
},
decorateMessage: function(text) {
try {
var links = this.extractURLs(text);
if (links) {
links.each(function(url) {
if (url.match(/(jp?g|png|gif)/i)) {
text = text.replace(url, '<a href="\#{url}" target="_blank"><img class="inline-image" src="\#{image}" /></a>'.interpolate({ url: url, image: url }));
} else {
text = text.replace(url, '<a href="\#{url}">\#{link_name}</a>'.interpolate({ url: url, link_name: url}));
}
});
}
} catch (exception) {
console.log(exception);
}
return text;
},
names: function(names) {
$('names').innerHTML = '';
names.each(function(name) {
$('names').insert({ bottom: '<li>' + this.truncateName(name) + '</li>' });
}.bind(this));
},
join: function(join) {
$('room-name').innerHTML = join['room'];
},
join_notice: function(join) {
$('names').insert({ bottom: '<li>' + this.truncateName(join['user']) + '</li>' });
this.add_message(join['user'] + ' has joined the room');
},
remove_user: function(name) {
$$('#names li').each(function(element) { if (element.innerHTML == name) element.remove(); });
},
part_notice: function(part) {
this.remove_user(part['user']);
this.add_message(part['user'] + ' has left the room');
},
quit_notice: function(quit) {
this.remove_user(quit['user']);
this.add_message(quit['user'] + ' has quit');
}
};
function displayMessages(text) {
var json_set = text.evalJSON(true);
if (json_set.length == 0) {
return;
}
json_set.each(function(json) {
Display[json['display']](json[json['display']]);
});
}
function updateMessages() {
new Ajax.Request('/messages', {
method: 'get',
parameters: { time: new Date().getTime() },
onSuccess: function(transport) {
displayMessages(transport.responseText);
}
});
}
function adaptSizes() {
var windowSize = document.viewport.getDimensions();
$('messages').setStyle({ width: windowSize.width - 220 + 'px' });
$('messages').setStyle({ height: windowSize.height - 90 + 'px' });
$('message').setStyle({ width: windowSize.width - 290 + 'px' });
}
document.observe('dom:loaded', function() {
if ($('room') && window.location.hash) {
$('room').value = window.location.hash;
}
if ($('post_message')) {
adaptSizes();
Event.observe(window, 'resize', function() {
adaptSizes();
});
$('message').activate();
$('post_message').observe('submit', function(e) {
var element = Event.element(e);
var message = $('message').value;
$('message').value = '';
new Ajax.Request('/message', {
method: 'post',
parameters: { 'message': message },
onSuccess: function(transport) {
}
});
Event.stop(e);
});
Event.observe(window, 'unload', function() {
new Ajax.Request('/quit');
});
}
if ($('messages')) {
new PeriodicalExecuter(updateMessages, 3);
}
});
|
JavaScript
| 0 |
@@ -353,16 +353,122 @@
w Date;%0A
+ var minutes = d.getMinutes().toString();%0A minutes = minutes.length == 1 ? '0' + minutes : minutes;%0A
var
@@ -504,23 +504,17 @@
' +
-d.getM
+m
inutes
-()
;
+
%0A
|
69813b0722e6b58ed2a063318e7f3551511ca8e9
|
Remove uglify from EmbedBlock.
|
entry/EmbedBlock.js
|
entry/EmbedBlock.js
|
const BlockCaption = require('./BlockCaption')
const React = require('react')
const shiny = require('shiny')
const UglifyJS = require('uglify-es')
const url = require('url')
const r = React.createElement
function parseVideoURL (_url) {
const parsed_url = url.parse(_url, true)
if (null == parsed_url.hostname) {
return null
}
switch (parsed_url.hostname.replace('www.','')) {
case 'youtube.com':
return `//www.youtube.com/embed/${ parsed_url.query.v }?modestbranding=1`
break
case 'youtu.be':
return `//www.youtube.com/embed${ parsed_url.pathname }?modestbranding=1`
break
case 'vimeo.com':
return `//player.vimeo.com/video${ parsed_url.pathname }`
break
case 'player.vimeo.com':
return _url
break
}
return null
}
const EmbedCard = (props) => (
r('a', { className: props.plain ? null : 'EmbedCard', href: props.url },
r('img', { src: props.thumbnail_url }),
r('h1', null, props.title),
r('p', null, props.description)
)
)
const EmbedMarkup = (props) => (
r('div', {
dangerouslySetInnerHTML: {
__html: props.markup
}
})
)
const EmbedVideo = (props) => {
if (props.plain) {
return r('iframe', {
src : props.url,
frameBorder : 0,
allowFullScreen : true,
})
}
return r('div', { className: '_EmbedWrapper' },
r('iframe', {
id : props.id,
className : '_EmbedFrame',
'data-frame_src' : props.url,
frameBorder : 0,
allowFullScreen : true,
}),
r('script', {
dangerouslySetInnerHTML: {
__html: UglifyJS.minify(`
;(function(window){
window.addEventListener('load', function(){
var target = document.getElementById('${ props.id }');
if (target) {
target.setAttribute('src', target.dataset.frame_src);
}
});
})(window);
`).code
}
})
)
}
const EmbedBlock = (props) => {
if (null == props.block.content) {
return null
}
const tag_props = {}
const { credit, caption } = props.block
if (!props.plain) {
const layout = props.block.layout || {}
const size = layout.size || 'medium'
const position = layout.position || 'center'
tag_props.className = shiny('Block', 'EmbedBlock')
tag_props.className.set('size', size)
if ('full' !== size) {
tag_props.className.set('position', position)
}
tag_props.id = props.block.id
}
let embed_content
if (null != props.block.embedly_result) {
if (null != props.block.embedly_result.html) {
embed_content = r(EmbedMarkup, { plain: props.plain, markup: props.block.embedly_result.html })
if (!props.plain) { tag_props.className.set('source', 'embedly_html') }
} else {
embed_content = r(props.link_card, props.block.embedly_result)
if (!props.plain) { tag_props.className.set('source', 'embedly_link') }
}
} else {
const embed_video_url = parseVideoURL(props.block.content)
if (embed_video_url) {
const embed_id = `${ props.block.id }_content`
embed_content = r(EmbedVideo, { plain: props.plain, url: embed_video_url, id: embed_id })
if (!props.plain) { tag_props.className.set('source', 'video') }
} else {
embed_content = r(EmbedMarkup, { plain: props.plain, markup: props.block.content })
if (!props.plain) { tag_props.className.set('source', 'markup') }
}
}
if (props.plain) {
return r('figure', null,
embed_content,
r(BlockCaption, { plain: props.plain, caption: caption, credit: credit })
)
}
return r('figure', tag_props,
r('div', { className: '_Content' },
embed_content,
r(BlockCaption, { plain: props.plain, caption: caption, credit: credit })
)
)
}
EmbedBlock.defaultProps = {
plain: false,
link_card: EmbedCard,
}
EmbedBlock.parseVideoURL = parseVideoURL
module.exports = EmbedBlock
|
JavaScript
| 0 |
@@ -123,51 +123,8 @@
y')%0A
-const UglifyJS = require('uglify-es')%0A
cons
@@ -1863,46 +1863,9 @@
ml:
-UglifyJS.minify(%60%0A
+%60
;(fu
@@ -1880,36 +1880,16 @@
indow)%7B%0A
-
wind
@@ -1928,36 +1928,16 @@
tion()%7B%0A
-
@@ -2003,62 +2003,22 @@
- if (target) %7B%0A
+if (target) %7B%0A
@@ -2091,113 +2091,31 @@
- %7D%0A %7D);%0A %7D)(window);%0A %60).code
+%7D%0A %7D);%0A%7D)(window);%0A%60
%0A
|
f91c602d43efc122016fc53db5f44a163ed3b74e
|
move to latest atom-shell
|
shell/Gruntfile.js
|
shell/Gruntfile.js
|
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
"download-atom-shell": {
version: "0.20.4",
outputDir: "./atom-shell",
rebuild: true
}
});
grunt.loadNpmTasks('grunt-download-atom-shell');
};
|
JavaScript
| 0 |
@@ -176,11 +176,11 @@
%220.2
-0.4
+1.2
%22,%0A
|
e8c477b1a5e420b606c161ee336a3fdaa8b40df3
|
Update uiselect.js
|
ngapp/app/directives/uiselect.js
|
ngapp/app/directives/uiselect.js
|
function uiselect() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'UISelectController',
scope: {
list: '=',
value: '=ngModel',
valuefield: '=?valuefield',
change: '=?change'
},
templateUrl: './ngapp/app/view/directives/uiselect.html',
link: function(scope, element, attrs, UISelectCtrl) {
// UISelectCtrl.addBar(scope, angular.element(element.children()[0]));
}
};
}
|
JavaScript
| 0.000001 |
@@ -270,16 +270,20 @@
Url: './
+jfc/
ngapp/ap
|
2c5701a7651548d9b3aaf3864ebc2f65e3e58cb1
|
Add aria key-value pairs so that a bunch of magic strings can be removed.
|
rocketbelt/base/rocketbelt.js
|
rocketbelt/base/rocketbelt.js
|
(function rocketbelt(window, document) {
window.rb = window.rb || {};
window.rb.getShortId = function getShortId() {
// Break the id into 2 parts to provide enough bits to the random number.
// This should be unique up to 1:2.2 bn.
var firstPart = (Math.random() * 46656) | 0;
var secondPart = (Math.random() * 46656) | 0;
firstPart = ('000' + firstPart.toString(36)).slice(-3);
secondPart = ('000' + secondPart.toString(36)).slice(-3);
return firstPart + secondPart;
};
window.rb.onDocumentReady = function onDocumentReady(fn) {
if (
document.readyState === 'complete' ||
(document.readyState !== 'loading' && !document.documentElement.doScroll)
) {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
};
})(window, document);
|
JavaScript
| 0 |
@@ -794,16 +794,423 @@
%7D%0A %7D;
+%0A%0A window.rb.aria = %7B%0A 'current': 'aria-current',%0A 'describedby': 'aria-describedby',%0A 'disabled': 'aria-disabled',%0A 'expanded': 'aria-expanded',%0A 'haspopup': 'aria-haspopup',%0A 'hidden': 'aria-hidden',%0A 'invalid': 'aria-invalid',%0A 'label': 'aria-label',%0A 'labelledby': 'aria-labelledby',%0A 'live': 'aria-live',%0A 'role': 'role'%0A %7D;
%0A%7D)(wind
|
fa09a307b047aef177a10bb207d9f1cccc56d499
|
Make ApplicationRoute Classy
|
tests/dummy/app/routes/application.js
|
tests/dummy/app/routes/application.js
|
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default Route.extend({
storage: service(),
setupController() {
this._super(...arguments);
this.get('storage').write('test', 'it works');
},
});
|
JavaScript
| 0 |
@@ -108,44 +108,66 @@
ult
+class Application
Route
-.
+
extend
-(%7B%0A storage: service(),
+s Route %7B%0A @service storage;
%0A%0A
@@ -194,17 +194,27 @@
-this._sup
+super.setupControll
er(.
@@ -241,22 +241,15 @@
his.
-get('
storage
-')
.wri
@@ -279,10 +279,7 @@
%0A %7D
-,
%0A%7D
-);
%0A
|
3c4d8f9e5378ba12e0e7bbd966c21f6b70bad158
|
Improve debug logging in reqOpt decorator. (#367)
|
app/steps/decorateProxyReqOpts.js
|
app/steps/decorateProxyReqOpts.js
|
'use strict';
function defaultDecorator(proxyReqOptBuilder /*, userReq */) {
return proxyReqOptBuilder;
}
function decorateProxyReqOpt(container) {
var resolverFn = container.options.proxyReqOptDecorator || defaultDecorator;
return Promise
.resolve(resolverFn(container.proxy.reqBuilder, container.user.req))
.then(function(processedReqOpts) {
delete processedReqOpts.params;
container.proxy.reqBuilder = processedReqOpts;
return Promise.resolve(container);
});
}
module.exports = decorateProxyReqOpt;
|
JavaScript
| 0 |
@@ -8,16 +8,69 @@
rict';%0A%0A
+var debug = require('debug')('express-http-proxy');%0A%0A
function
@@ -386,16 +386,17 @@
function
+
(process
@@ -408,18 +408,16 @@
Opts) %7B%0A
-
de
@@ -452,18 +452,16 @@
;%0A
-
containe
@@ -497,24 +497,108 @@
dReqOpts;%0A
+
+ debug('Request options (after processing):', JSON.stringify(processedReqOpts));%0A
return
|
94f60ccc0a9440555da176d4a6f809c00ed87a9e
|
Complete string tests to pass
|
topics/about_strings.js
|
topics/about_strings.js
|
module("About Strings (topics/about_strings.js)");
test("delimiters", function() {
var singleQuotedString = 'apple';
var doubleQuotedString = "apple";
equal(__, singleQuotedString === doubleQuotedString, 'are the two strings equal?');
});
test("concatenation", function() {
var fruit = "apple";
var dish = "pie";
equal(__, fruit + " " + dish, 'what is the value of fruit + " " + dish?');
});
test("character Type", function() {
var characterType = typeof("Amory".charAt(1)); // typeof will be explained in about reflection
equal(__, characterType, 'Javascript has no character type');
});
test("escape character", function() {
var stringWithAnEscapedCharacter = "\u0041pple";
equal(__, stringWithAnEscapedCharacter, 'what is the value of stringWithAnEscapedCharacter?');
});
test("string.length", function() {
var fruit = "apple";
equal(__, fruit.length, 'what is the value of fruit.length?');
});
test("slice", function() {
var fruit = "apple pie";
equal(__, fruit.slice(0,5), 'what is the value of fruit.slice(0,5)?');
});
|
JavaScript
| 0.000003 |
@@ -164,18 +164,20 @@
equal(
-__
+true
, single
@@ -337,26 +337,35 @@
;%0A equal(
-__
+%22apple pie%22
, fruit + %22
@@ -569,18 +569,24 @@
equal(
-__
+'string'
, charac
@@ -738,18 +738,23 @@
equal(
-__
+%22Apple%22
, string
@@ -900,34 +900,33 @@
ple%22;%0A equal(
-__
+5
, fruit.length,
@@ -1039,10 +1039,15 @@
ual(
-__
+%22apple%22
, fr
|
cac2368d201eca584f2b5c54afb10b3b30e3cbe9
|
Fix CoffeeScript error reporting.
|
packages/coffeescript/package.js
|
packages/coffeescript/package.js
|
Package.describe({
summary: "Javascript dialect with fewer braces and semicolons"
});
Npm.depends({"coffee-script": "1.6.2"});
var coffeescript_handler = function(bundle, source_path, serve_path, where) {
var fs = Npm.require('fs');
var path = Npm.require('path');
var coffee = Npm.require('coffee-script');
serve_path = serve_path + '.js';
var contents = fs.readFileSync(source_path);
var options = {bare: true, filename: source_path, literate: path.extname(source_path) === '.litcoffee'};
try {
contents = coffee.compile(contents.toString('utf8'), options);
} catch (e) {
return bundle.error(e.message);
}
contents = new Buffer(contents);
bundle.add_resource({
type: "js",
path: serve_path,
data: contents,
where: where
});
}
Package.register_extension("coffee", coffeescript_handler);
Package.register_extension("litcoffee", coffeescript_handler);
Package.on_test(function (api) {
api.add_files([
'coffeescript_tests.coffee',
'coffeescript_strict_tests.coffee',
'litcoffeescript_tests.litcoffee',
'coffeescript_tests.js'
], ['client', 'server']);
});
|
JavaScript
| 0 |
@@ -616,16 +616,109 @@
e.error(
+%0A source_path + ':' +%0A (e.location ? (e.location.first_line + ': ') : ' ') +%0A
e.messag
@@ -718,16 +718,21 @@
.message
+%0A
);%0A %7D%0A%0A
|
f1015a4f8c888e740d699e7f5fec08eec1e0fceb
|
Allow more flexible matching and remove default ordering
|
public/assets/js/app.js
|
public/assets/js/app.js
|
/*!
* Author: Abdullah A Almsaeed
* Date: 4 Jan 2014
* Description:
* This file should be included in all pages
!**/
$(function() {
"use strict";
//Enable sidebar toggle
$("[data-toggle='offcanvas']").click(function(e) {
e.preventDefault();
//If window is small enough, enable sidebar push menu
if ($(window).width() <= 992) {
$('.row-offcanvas').toggleClass('active');
$('.left-side').removeClass("collapse-left");
$(".right-side").removeClass("strech");
$('.row-offcanvas').toggleClass("relative");
} else {
//Else, enable content streching
$('.left-side').toggleClass("collapse-left");
$(".right-side").toggleClass("strech");
}
});
//Add hover support for touch devices
$('.btn').bind('touchstart', function() {
$(this).addClass('hover');
}).bind('touchend', function() {
$(this).removeClass('hover');
});
//Activate tooltips & popovers
$("[data-toggle='tooltip']").tooltip();
$("[data-toggle='popover']").popover();
/*
* Add collapse and remove events to boxes
*/
$("[data-widget='collapse']").click(function() {
//Find the box parent
var box = $(this).parents(".box").first();
//Find the body and the footer
var bf = box.find(".box-body, .box-footer");
if (!box.hasClass("collapsed-box")) {
box.addClass("collapsed-box");
bf.slideUp();
} else {
box.removeClass("collapsed-box");
bf.slideDown();
}
});
$("[data-widget='remove']").click(function() {
//Find the box parent
var box = $(this).parents(".box").first();
box.slideUp();
});
/* Sidebar tree view */
$(".sidebar .treeview").tree();
/*
* Make sure that the sidebar is streched full height
* ---------------------------------------------
* We are gonna assign a min-height value every time the
* wrapper gets resized and upon page load. We will use
* Ben Alman's method for detecting the resize event.
**/
function _fix() {
//Get window height and the wrapper height
var height = $(window).height() - $("body > .header").height();
$(".wrapper").css("min-height", height + "px");
var content = $(".wrapper").height();
//If the wrapper height is greater than the window
if (content > height)
//then set sidebar height to the wrapper
$(".left-side, html, body").css("min-height", content + "px");
else {
//Otherwise, set the sidebar to the height of the window
$(".left-side, html, body").css("min-height", height + "px");
}
}
//Fire upon load
_fix();
//Fire when wrapper is resized
$(".wrapper").resize(function() {
_fix();
});
});
/*
* SIDEBAR MENU
* ------------
* This is a custom plugin for the sidebar menu. It provides a tree view.
*
* Usage:
* $(".sidebar).tree();
*
* Note: This plugin does not accept any options. Instead, it only requires a class
* added to the element that contains a sub-menu.
*
* When used with the sidebar, for example, it would look something like this:
* <ul class='sidebar-menu'>
* <li class="treeview active">
* <a href="#>Menu</a>
* <ul class='treeview-menu'>
* <li class='active'><a href=#>Level 1</a></li>
* </ul>
* </li>
* </ul>
*
* Add .active class to <li> elements if you want the menu to be open automatically
* on page load. See above for an example.
*/
(function($) {
"use strict";
$.fn.tree = function() {
return this.each(function() {
var btn = $(this).children("a").first();
var menu = $(this).children(".treeview-menu").first();
var isActive = $(this).hasClass('active');
//initialize already active menus
if (isActive) {
menu.show();
btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
}
//Slide open or close the menu on link click
btn.click(function(e) {
e.preventDefault();
if (isActive) {
//Slide up to close menu
menu.slideUp();
isActive = false;
btn.children(".fa-angle-down").first().removeClass("fa-angle-down").addClass("fa-angle-left");
btn.parent("li").removeClass("active");
} else {
//Slide down to open menu
menu.slideDown();
isActive = true;
btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down");
btn.parent("li").addClass("active");
}
});
/* Add margins to submenu elements to give it a tree look */
menu.find("li > a").each(function() {
var pad = parseInt($(this).css("margin-left")) + 10;
$(this).css({"margin-left": pad + "px"});
});
});
};
}(jQuery));
/* CENTER ELEMENTS */
(function($) {
"use strict";
jQuery.fn.center = function(parent) {
if (parent) {
parent = this.parent();
} else {
parent = window;
}
this.css({
"position": "absolute",
"top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
"left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
});
return this;
}
}(jQuery));
/*
* Set the CSRF Token for Ajax too
*/
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
}
});
});
// Get some confirmations prepared. Generally speaking we can just class a element and
// then these will be used for confirmation
// Generic 'confirm' dialog code for forms.
// Make your submit button part of class confirmform, and viola
var currentForm;
$(document).on("click", ".confirmform", function(e){
currentForm = $(this).closest("form");
e.preventDefault();
bootbox.confirm("Are you sure you want to continue?", function(confirmed) {
if ( confirmed ) {
currentForm.submit();
}
});
});
// Generic 'confirm' dialog code for links.
// Make your link button part of class confirmlink, and viola
$(document).on("click", "a.confirmlink", function(event){
event.preventDefault()
var url = $(this).attr("href");
bootbox.confirm("Are you sure you want to continue?", function(confirmed) {
if ( confirmed ) {
window.location = url;
}
});
});
// Init datatables on, tables
(function($) {
$("table#datatable").dataTable({ paging:false });
}(jQuery));
|
JavaScript
| 0 |
@@ -6992,14 +6992,13 @@
$(%22
-table#
+%5Bid%5E=
data
@@ -7002,16 +7002,17 @@
atatable
+%5D
%22).dataT
@@ -7030,16 +7030,26 @@
ng:false
+, order:%5B%5D
%7D);%0A%7D(j
|
1bba3ddd1dbab2370970f8b71e57ac9fb2bd9ead
|
fix inbetween party
|
app/views/countries/search-map.js
|
app/views/countries/search-map.js
|
define(['text!./search-map.html',
'app',
'jquery',
'lodash',
'text!./pin-popup-abs.html',
'scbd-map/ammap3',
'scbd-map/ammap3-service', '/app/js/common.js', '/app/services/search-service.js',
'../directives/block-region-directive.js'
], function(template, app, $, _, popoverTemplate) {
'use strict';
app.directive('searchMap', ['ammap3Service', function(ammap3Service) {
return {
restrict: 'E',
template: template,
replace: true,
require: 'searchMap',
scope : {
height:"@",
},
//=======================================================================
//
//=======================================================================
controller: ["$scope", '$q', 'commonjs', 'searchService', '$timeout', '$filter',
function($scope, $q, commonjs, searchService, $timeout, $filter) {
if(!$scope.height)
$scope.height="500px";
function calculateListViewFacets(countryFacets, countries) {
_.each(countries, function(country) {
var countryFacet = _.where(countryFacets, {
government : country.code.toLowerCase()
});
if (countryFacet.length > 0) {
_.each(countryFacet.schemas, function(document, key) {
country[$filter("schemaShortName")(key)] = document.count;
});
country.total = countryFacet.recordCount;
}
country = normalizeCountryData(country);
});
} //calculateListViewFacets
//====================================================
function loadCountries() {
$scope.loading = true;
return $q.when(commonjs.getCountries()).then(function(countries) {
return $q.when(searchService.governmentSchemaFacets())
.then(function(countryFacets){
calculateListViewFacets(countryFacets, countries);
ammap3Service.loadCountries('search-map', countries);
var exceptionCountryCodes = ['GL', 'FO', 'SJ'];
ammap3Service.eachCountry('search-map', function(mapCountry){
var countryDetails = _.findWhere(countries, {code : mapCountry.id});
if(countryDetails){
if(countryDetails.isNPInbetweenParty)
mapCountry.colorReal= mapCountry.baseSettings.color="#EC971F";
if(countryDetails.isNPParty)
mapCountry.colorReal= mapCountry.baseSettings.color="#5F4586";
else
mapCountry.colorReal= mapCountry.baseSettings.color="#333";
}
else{
if(_.contains(exceptionCountryCodes, mapCountry.id))
mapCountry.colorReal= mapCountry.baseSettings.color="#5F4586";
else
mapCountry.colorReal= mapCountry.baseSettings.color="#333";
}
});
return;
});
})
.finally(function() {
$scope.loading = false;
});
}
//=======================================================================
//// should be done in client
//=======================================================================
function normalizeCountryData(country) {
if (!country.CNA)
country.CNA = 0;
if (!country.CP)
country.CP = 0;
if (!country.CPC)
country.CPC = 0;
if (!country.IRCC)
country.IRCC = 0;
if (!country.MSR)
country.MSR = 0;
if (!country.NDB)
country.NDB = 0;
if (!country.NFP)
country.NFP = 0;
if (country.isNPParty)
country.status = '<p style="width:100%;text-align:center;background-color: #5F4586;margin:0;padding:0;" class="party-status" ng-if="isNPParty">Party</p>';
else if (country.isNPInbetweenParty)
country.status = '<p style="width:100%;text-align:center;background-color: #EC971F;margin:0;padding:0;" class="party-status" ng-if="isNPInbetweenParty">Ratified not yet Party</p>';
else
country.status = '<p style="width:100%;text-align:center;background-color: #333;margin:0;padding:0;" class="party-status" ng-if="isNPSignatory">Non Party</p>';
return country;
}
// $timeout(function(){
// close all popovers on click anywhere
ammap3Service.setGlobalClickListener('search-map',
function() {
ammap3Service.closePopovers('search-map');
// ammap3Service.selectObject('search-map');
});
//set pin
ammap3Service.setPinImage('search-map', 'invisi-pixel');
//set popover
ammap3Service.setPinPopOver('search-map', popoverTemplate);
//set on country click event to open country popup
ammap3Service.setCountryClickListener('search-map',
function(event) {
var id = event.mapObject.id;
ammap3Service.closePopovers('search-map');
if(event.mapObject.id === 'GL')
{ var mObj =ammap3Service.getMapObject('search-map','DK');
ammap3Service.clickMapObject('search-map', mObj);
id = 'DK';
}
if(event.mapObject.id === 'FO')
{
ammap3Service.selectObject('search-map',ammap3Service.getMapObject('search-map','DK'));
id = 'DK';
}
if(event.mapObject.id === 'SJ')
{
ammap3Service.clickMapObject('search-map',ammap3Service.getMapObject('search-map','NO'));
id = 'NO';
}
if(event.mapObject.id === 'EH')
{
ammap3Service.clickMapObject('search-map',ammap3Service.getMapObject('search-map','MA'));
id = 'MA';
}
if(event.mapObject.id === 'TW')
{
ammap3Service.clickMapObject('search-map',ammap3Service.getMapObject('search-map','CN'));
id = 'CN';
}
if(id != 'FK'){ // Falkland Islands no popover
ammap3Service.openCountryPopup('search-map', id); //pin, popup,
}
});
loadCountries();
// },1500);
$scope.$on('$destroy', function(){
ammap3Service.clear('search-map');
});
}] //controlerr
}; //return
}]); //directive
}); //define
|
JavaScript
| 0.000001 |
@@ -2440,32 +2440,33 @@
+
if(countryDetail
@@ -2615,32 +2615,37 @@
+else
if(countryDetail
@@ -2750,32 +2750,33 @@
olor=%22#5F4586%22;%0A
+
|
4140af4c776aa8cb2dbd52ed7a05c44268094ec8
|
normalize backup title
|
packages/docs/src/mixins/meta.js
|
packages/docs/src/mixins/meta.js
|
export default {
data: () => ({
meta: {},
_description: {},
_keywords: {},
}),
computed: {
title () {
return this.meta.title || 'Material Component Framework'
},
description () {
return this.meta.description
},
keywords () {
return this.meta.keywords
},
},
watch: {
$route () {
this.setMeta()
},
meta: {
deep: true,
handler () {
if (typeof document !== 'undefined') {
document.title = `${this.title} — Vuetify.js`
}
this._description.setAttribute('content', this.description)
this._keywords.setAttribute('content', this.keywords)
},
},
},
created () {
if (process.env.VUE_ENV === 'client') return
this.setMeta()
this.$ssrContext.title = `${this.title} — Vuetify.js`
this.$ssrContext.description = this.description
this.$ssrContext.keywords = this.keywords
},
mounted () {
this.bootstrapMeta()
},
methods: {
bootstrapMeta () {
if (typeof document === 'undefined') return
this._title = document.title
this._description = document.querySelector('meta[name="description"]')
this._keywords = document.querySelector('meta[name="keywords"]')
this.setMeta()
},
setMeta () {
const [, lang, namespace, page] = this.$route.path.split('/')
const key = namespace ? `${namespace}/${page}` : ''
const meta = this.$i18n.getLocaleMessage(lang).Meta || {}
this.meta = meta[key] || this.getFallbackMeta(key) || {}
},
getFallbackMeta (path) {
const fallbackmeta = this.$i18n.getLocaleMessage(this.$i18n.fallbackLocale).Meta || {}
if (process.env.NODE_ENV === 'development') {
console.warn('Falling back to english meta for ' + (path || '/'))
}
return fallbackmeta[path]
},
},
}
|
JavaScript
| 0.000002 |
@@ -151,16 +151,20 @@
tle %7C%7C '
+Vue
Material
|
91b5a4800392322263e2f891c0521bf7988c7989
|
Check when browser is open
|
public/js/background.js
|
public/js/background.js
|
chrome.browserAction.setBadgeText({text: "0"});
//localStorage.removeItem('azubu_extension');
if (!localStorage.getItem('azubu_extension')) {
localStorage.setItem('azubu_extension', '{"usernames": [], "online": []}');
}
setInterval(function () {
var extData = JSON.parse(localStorage.getItem('azubu_extension'));
var following = new Following(extData.usernames);
var online = new Online(extData.online);
for (var k in online.getAll()) {
if (!following.has(online.getAll()[k])) {
online.remove(online.getAll()[k]);
}
}
}, 1000);
var extData = JSON.parse(localStorage.getItem('azubu_extension'));
extData.online = [];
localStorage.setItem('azubu_extension', JSON.stringify(extData));
setInterval(function () {
var extData = JSON.parse(localStorage.getItem('azubu_extension'));
var following = new Following(extData.usernames);
var online = new Online(extData.online);
for (var k in following.getAll()) {
var username = following.getAll()[k];
$.ajax({
method: 'GET',
url: 'http://api.azubu.tv/public/channel/' + username + '/info',
type: 'json',
async: false,
success: function (data) {
if (data.data.is_live) {
if (!online.has(username)) {
var n = new Notification(username, {
tag: 'started streamming on Azubu.tv',
icon: data.data.url_thumbnail
});
n.onclick = function () {
window.open('http://azubu.tv/' + username);
};
setTimeout(function () {n.close()}, 3000);
online.add(username);
}
} else {
if (online.has(username)) {
online.remove(username);
}
}
}
});
}
chrome.browserAction.setBadgeText({text: "" + online.getAll().length + ""});
}, 30000);
|
JavaScript
| 0.000001 |
@@ -1,770 +1,24 @@
-chrome.browserAction.setBadgeText(%7Btext: %220%22%7D);%0A//localStorage.removeItem('azubu_extension');%0Aif (!localStorage.getItem('azubu_extension')) %7B%0A localStorage.setItem('azubu_extension', '%7B%22usernames%22: %5B%5D, %22online%22: %5B%5D%7D');%0A%7D%0A%0AsetInterval(function () %7B%0A var extData = JSON.parse(localStorage.getItem('azubu_extension'));%0A var following = new Following(extData.usernames);%0A var online = new Online(extData.online);%0A%0A for (var k in online.getAll()) %7B%0A if (!following.has(online.getAll()%5Bk%5D)) %7B%0A online.remove(online.getAll()%5Bk%5D);%0A %7D%0A %7D%0A%7D, 1000);%0A%0Avar extData = JSON.parse(localStorage.getItem('azubu_extension'));%0A extData.online = %5B%5D;%0A localStorage.setItem('azubu_extension', JSON.stringify(extData));%0A%0AsetInterval(function
+function checkOnline
()
@@ -1369,16 +1369,886 @@
%22%22%7D);%0A%7D
+%0A%0Achrome.browserAction.setBadgeText(%7Btext: %220%22%7D);%0A//localStorage.removeItem('azubu_extension');%0Aif (!localStorage.getItem('azubu_extension')) %7B%0A localStorage.setItem('azubu_extension', '%7B%22usernames%22: %5B%5D, %22online%22: %5B%5D%7D');%0A%7D%0A%0AsetInterval(function () %7B%0A var extData = JSON.parse(localStorage.getItem('azubu_extension'));%0A var following = new Following(extData.usernames);%0A var online = new Online(extData.online);%0A%0A for (var k in online.getAll()) %7B%0A if (!following.has(online.getAll()%5Bk%5D)) %7B%0A online.remove(online.getAll()%5Bk%5D);%0A %7D%0A %7D%0A%0A chrome.browserAction.setBadgeText(%7Btext: %22%22 + online.getAll().length + %22%22%7D);%0A%7D, 500);%0A%0Avar extData = JSON.parse(localStorage.getItem('azubu_extension'));%0A extData.online = %5B%5D;%0A localStorage.setItem('azubu_extension', JSON.stringify(extData));%0A%0AcheckOnline();%0A%0AsetInterval('checkOnline'
, 30000)
|
0b5e0df1c1635e2b9e206fe32515093702ce5cde
|
Fix the handling of the new osmOwners attribute
|
public/js/core/theme.js
|
public/js/core/theme.js
|
import Diacritics from 'diacritic';
export default class Theme {
/**
* Returns a URL-friendly name of the theme.
*
* @author Guillaume AMAT
* @static
* @access public
* @param {string} nameArg
* @return {string}
*/
static buildWebLinkName(nameArg) {
let name = nameArg || '';
name = Diacritics.clean(name);
name = name.replace(/-/g, '_');
name = name.replace(/ /g, '_');
name = name.replace(/_{2,}/g, '_');
name = name.replace(/[^a-zA-Z0-9_]/g, '');
return name;
}
/**
* Returns the theme path.
*
* @author Guillaume AMAT
* @static
* @access public
* @param {string} fragment
* @param {string} name
* @return {string}
*/
static buildPath(fragment, name) {
const basePath = `/t/${fragment}`;
const webName = this.buildWebLinkName(name);
if (webName) {
return `${basePath}-${webName}`;
}
return basePath;
}
/**
* Returns the theme url.
*
* @author Guillaume AMAT
* @static
* @access public
* @param {object} window - The browser's window object
* @param {string} fragment
* @param {string} name
* @return {string}
*/
static buildUrl(window, fragment, name) {
const urlParts = [
window.location.protocol,
'//',
window.location.host,
this.buildPath(fragment, name)
];
return urlParts.join('');
}
/**
* Tells if a user is the owner of the theme.
*
* @author Guillaume AMAT
* @static
* @access public
* @param {object} theme - The theme
* @param {string} userId
* @param {string} osmId
* @return {boolean}
*/
static isThemeOwner(theme, userId, osmId) {
if (theme.userId === userId) {
return true;
}
if (theme.owners.indexOf(userId) !== -1) {
return true;
}
if (theme.owners.indexOf('*') !== -1) {
return true;
}
if (theme.osmOwners.indexOf(osmId) !== -1) {
return true;
}
if (theme.osmOwners.indexOf('*') !== -1) {
return true;
}
return false;
}
}
|
JavaScript
| 0.000128 |
@@ -1942,32 +1942,61 @@
rn true;%0A %7D%0A%0A
+ if (theme.osmOwners) %7B%0A
if (theme.os
@@ -2026,32 +2026,34 @@
!== -1) %7B%0A
+
return true;%0A
@@ -2045,39 +2045,43 @@
eturn true;%0A
+
%7D%0A%0A
+
+
if (theme.osmOwn
@@ -2105,32 +2105,34 @@
!== -1) %7B%0A
+
return true;%0A
@@ -2120,32 +2120,40 @@
return true;%0A
+ %7D%0A
%7D%0A%0A retur
|
762a3800a5b8b6cac5f50ce96515e3f670197831
|
Add 5-10 minute estimate before anticipation questions
|
public/js/experiment.js
|
public/js/experiment.js
|
/**
* Experiment view blocks for jsSART
*/
var experiment = [];
var participant_id = getParticipantId();
var conditions = generateConditions();
// prospective survey notice and questions
var prospective_survey_text = "<p>Before we begin, we would like to know what you <strong>expect to experience</strong> on this <strong>sustained attention task</strong>. The <strong>sustained attention task</strong> that will follow is identical to the practice trial you have just completed, although it will be longer.</p>";
var prospective_survey_notice = createTextBlock(prospective_survey_text);
var prospective_survey = generateMultiChoiceSurvey(
jsSART.QUESTIONS.ANTICIPATION);
experiment.push(prospective_survey_notice);
experiment.push(prospective_survey);
// pre-experiment notice
var experiment_notice_text = "<p>This was an overview of the task, and you have completed the practice trials.</p> <p>The <strong>sustained attention</strong> task that will follow is identical to the practice trial you have just completed. Altogether, it will be 5-10 minutes long.</p> <p>Remember, if you get lost, just jump back in because we can’t stop the experiment once it has started. At several points in the task you will pause briefly to report your experience and then continue with the task.</p> <p>The <strong>sustained attention</strong> task will now follow.";
var experiment_notice = createTextBlock(experiment_notice_text);
experiment.push(experiment_notice);
// generate the experiment blocks
var formatted_block_stimuli = generateSartBlockStimuli(conditions);
experiment = experiment.concat(formatted_block_stimuli);
// post-experiment valance and arousal questions
var valence_and_arousal = generateMultiChoiceSurvey(jsSART.QUESTIONS.AROUSAL);
experiment.push(valence_and_arousal);
// end notice
var experiment_end_notice = createTextBlock(
"<p><strong>You have completed the sustained attention task.</strong></p>"
);
experiment.push(experiment_end_notice);
// add generated experiment settings to saved data
jsPsych.data.addProperties({
num_trials: conditions.num_trials,
trials_per_block: conditions.trials_per_block,
participant_id: participant_id,
});
jsPsych.init({
display_element: $('#jspsych-target'),
timeline: experiment,
on_finish: function() {
var redirect_url = 'follow_up?pid=' + participant_id;
postDataToDb(jsPsych.data.getData(), participant_id, redirect_url);
}
});
|
JavaScript
| 0 |
@@ -503,16 +503,44 @@
e longer
+, approximately 5-10 minutes
.%3C/p%3E%22;%0A
|
5210a66069d18c880b7fc67f959b55fe17e63a9f
|
Add instructions for custom titles
|
app/views/private-beta-01/data.js
|
app/views/private-beta-01/data.js
|
var data = require('../../../data/titles');
var search = require('../../../data/search');
// Use this space to insert any prototype specific entries onto the available
// set of data.
// For example:
data.push({
data: {},
title_number: 'FAKE123123',
address: [
'Seaton Court',
'2',
'William Prance Rd',
'Plymouth',
'PL6 5WS'
]
});
module.exports = function(searchTerm, callback) {
search(data, searchTerm, function(results) {
// Limit the results returned to 50
// (This limit is performed here rather than in the search so that future prototypes
// can more easily experiment with derestricting the results)
results = results.slice(0, 50);
callback(results);
});
};
|
JavaScript
| 0.000003 |
@@ -185,181 +185,243 @@
%0A//
-For example:%0Adata.push(%7B%0A data: %7B%7D,%0A title_number: 'FAKE123123',%0A address: %5B%0A 'Seaton Court',%0A '2',%0A 'William Prance Rd',%0A 'Plymouth',%0A 'PL6 5WS'%0A %5D%0A%7D
+To inspect the structure of the data, uncomment the following line. This will%0A// log the data structure to your console which you can then copy and paste here%0A// before making any modifications you wish to.%0A%0A// console.log(data%5B0%5D
);%0A%0A
+%0A
modu
|
d4dc1b56c648f0a6edd0f5880e009d9b9b8c50a4
|
Copy files from public dir to output path (#70)
|
packages/pack/webpack/plugins.js
|
packages/pack/webpack/plugins.js
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WriteWebpackPlugin = require('write-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const SriPlugin = require('webpack-subresource-integrity');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const { getSource } = require('./helpers/source');
const transformOpenpgpFiles = require('./helpers/openpgp');
const { OPENPGP_FILES } = require('./constants');
const { logo, ...logoConfig } = require(getSource('src/assets/logoConfig.js'));
const HTML_MINIFY = {
removeAttributeQuotes: true,
collapseWhitespace: true,
html5: true,
minifyCSS: true,
removeComments: true,
removeEmptyAttributes: true
};
const PRODUCTION_PLUGINS = [
new OptimizeCSSAssetsPlugin({
cssProcessorPluginOptions: {
preset: [
'default',
{
reduceInitial: false,
discardComments: {
removeAll: true
},
svgo: false
}
]
}
}),
new ImageminPlugin({
cacheFolder: path.resolve('./node_modules/.cache'),
maxConcurrency: Infinity,
disable: false,
test: /\.(jpe?g|png)$/i,
optipng: {
optimizationLevel: 7
},
pngquant: {
quality: '80-100'
},
jpegtran: {
progressive: true
},
plugins: [
imageminMozjpeg({
quality: 80,
progressive: true
})
]
})
];
module.exports = ({ isProduction, publicPath, appMode, featureFlags, writeSRI }) => {
const { main, worker, elliptic, compat, definition } = transformOpenpgpFiles(
OPENPGP_FILES,
publicPath,
isProduction
);
return [
...(isProduction
? [new webpack.HashedModuleIdsPlugin()]
: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new ReactRefreshWebpackPlugin({
overlay: false
})
]),
new WriteWebpackPlugin(
[main, compat, elliptic, worker].map(({ filepath, contents }) => ({
name: filepath,
data: Buffer.from(contents)
}))
),
new MiniCssExtractPlugin({
filename: isProduction ? '[name].[contenthash:8].css' : '[name].css',
chunkFilename: isProduction ? '[id].[contenthash:8].css' : '[id].css'
}),
new HtmlWebpackPlugin({
template: getSource('src/app.ejs'),
inject: 'body',
minify: isProduction && HTML_MINIFY
}),
new FaviconsWebpackPlugin({
logo: getSource(logo),
...logoConfig
}),
...(writeSRI
? [
new SriPlugin({
hashFuncNames: ['sha384'],
enabled: isProduction
})
]
: []),
new webpack.DefinePlugin({
WEBPACK_OPENPGP: JSON.stringify(definition),
WEBPACK_APP_MODE: JSON.stringify(appMode),
WEBPACK_PUBLIC_PATH: JSON.stringify(publicPath),
WEBPACK_FEATURE_FLAGS: JSON.stringify(featureFlags)
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
new webpack.SourceMapDevToolPlugin({
test: /.js$/,
filename: '[file].map'
}),
...(isProduction ? PRODUCTION_PLUGINS : [])
].filter(Boolean);
};
|
JavaScript
| 0 |
@@ -173,24 +173,82 @@
k-plugin');%0A
+const CopyWebpackPlugin = require('copy-webpack-plugin');%0A
const Imagem
@@ -944,24 +944,25 @@
onstants');%0A
+%0A
const %7B logo
@@ -2914,24 +2914,136 @@
),%0A%0A
+ new CopyWebpackPlugin(%7B%0A patterns: %5B%7B from: 'public', noErrorOnMissing: true %7D%5D%0A %7D),%0A%0A
new
|
343dc864a84c712277af37ac2e59bf8b3a72e9ec
|
make symbol.tree getter immutable
|
packages/svg-baker/lib/symbol.js
|
packages/svg-baker/lib/symbol.js
|
const { renderer } = require('posthtml-svg-mode');
const { getRoot, getHash } = require('./utils');
const defaultFactory = require('./symbol-factory');
const FileRequest = require('./request');
class SpriteSymbol {
constructor({ id, tree, request }) {
this.id = id;
this.tree = tree;
this.request = request;
}
/**
* @param {Object} options
* @param {string} options.id
* @param {string} options.content
* @param {string|FileRequest} options.request
* @param {Function<Promise<PostHTMLProcessingResult>>} [options.factory]
* @return {Promise<SpriteSymbol>}
*/
static create(options) {
const { content, factory = defaultFactory } = options;
const request = typeof options.request === 'string' ? new FileRequest(options.request) : options.request;
const id = typeof options.id === 'undefined' ? getHash(`${request.toString()}_${content}`) : options.id;
return factory({ content, request, id })
.then(({ tree }) => new SpriteSymbol({ id, request, tree }));
}
/**
* @return {string}
*/
get viewBox() {
const root = getRoot(this.tree);
return root.attrs ? root.attrs.viewBox : null;
}
/**
* @return {string}
*/
get useId() {
return `${this.id}-usage`;
}
/**
* @return {string}
*/
render() {
return renderer(this.tree);
}
}
module.exports = SpriteSymbol;
|
JavaScript
| 0.000029 |
@@ -186,16 +186,48 @@
quest');
+%0Aconst clone = require('clone');
%0A%0Aclass
@@ -303,24 +303,25 @@
d;%0A this.
+_
tree = tree;
@@ -1191,24 +1191,74 @@
null;%0A %7D%0A%0A
+ get tree() %7B%0A return clone(this._tree);%0A %7D%0A%0A
/**%0A * @
|
25c86969ee0ae5a197e2377ae9d44c2ffa508ed8
|
disable log assertions when the user is customizing logging
|
packages/test-support/prepare.js
|
packages/test-support/prepare.js
|
const util = require('util');
const chai = require('chai');
global.expect = chai.expect;
chai.use(require('chai-things'));
chai.use(require('./collection-contains'));
chai.use(require('./has-status'));
// Without this, we can't see stack traces for certain failures within
// promises during the test suite.
process.on('warning', (warning) => {
/* eslint-disable no-console */
console.warn(warning.stack);
/* eslint-enable no-console */
});
// If the user isn't customizing anything about logging, we generate
// log messages for warnings or higher, and we install a handler that
// will cause any unexpected log message to fail the tests.
if (!process.env['DEBUG']) {
// these third-party deps have loud logging even at warn level
process.env.DEBUG='*,-eslint:*,-koa:*,-koa-*,-superagent';
if (!process.env['DEBUG_LEVEL']) {
process.env.DEBUG_LEVEL='warn';
}
let debug = require('debug');
debug.log = function(...args) {
let logLine = util.format(...args);
let match = [...expected.keys()].find(pattern => pattern.test(logLine));
if (match) {
expected.set(match, expected.get(match) + 1);
} else {
throw new Error("Unexpected log message during tests: " + logLine);
}
};
}
if (!process.env['ELASTICSEARCH_PREFIX']) {
// Avoid stomping on any existing content in elasticsearch by
// namespacing the test indices differently.
process.env['ELASTICSEARCH_PREFIX'] = 'test';
}
let expected = new Map();
global.expectLogMessage = async function(pattern, fn) {
expected.set(pattern, 0);
await fn();
let count = expected.get(pattern);
expected.delete(pattern);
if (count !== 1) {
throw new Error(`Expected a log mesage to match ${pattern} but none did`);
}
};
|
JavaScript
| 0.000001 |
@@ -1228,217 +1228,10 @@
%7D;%0A
-%7D%0A%0Aif (!process.env%5B'ELASTICSEARCH_PREFIX'%5D) %7B%0A // Avoid stomping on any existing content in elasticsearch by%0A // namespacing the test indices differently.%0A process.env%5B'ELASTICSEARCH_PREFIX'%5D = 'test';%0A%7D%0A%0A
+
let
@@ -1249,24 +1249,26 @@
new Map();%0A%0A
+
global.expec
@@ -1311,16 +1311,18 @@
, fn) %7B%0A
+
expect
@@ -1341,16 +1341,18 @@
rn, 0);%0A
+
await
@@ -1357,16 +1357,18 @@
t fn();%0A
+
let co
@@ -1396,16 +1396,18 @@
ttern);%0A
+
expect
@@ -1426,16 +1426,18 @@
ttern);%0A
+
if (co
@@ -1445,24 +1445,26 @@
nt !== 1) %7B%0A
+
throw ne
@@ -1536,9 +1536,309 @@
;%0A
-%7D%0A%7D;
+ %7D%0A %7D;%0A%7D else %7B%0A global.expectLogMessage = async function(pattern, fn) %7B%0A await fn();%0A %7D;%0A%7D%0A%0Aif (!process.env%5B'ELASTICSEARCH_PREFIX'%5D) %7B%0A // Avoid stomping on any existing content in elasticsearch by%0A // namespacing the test indices differently.%0A process.env%5B'ELASTICSEARCH_PREFIX'%5D = 'test';%0A%7D
%0A
|
c8f65709b4b451038fa360a87b4cfbaa772e0aac
|
Allow configuring layer attribution and tile extension.
|
public_html/groupxiv.js
|
public_html/groupxiv.js
|
/*
Options:
viewport: DOM id of the viewport
scale: image scale (nm/px)
layers: array of:
URL: URL of the original image
width: original image width
height: original image height
tileSize: tile dimension
imageSize: smallest square image size that fits all tiles at maximum zoom
minZoom: minimum zoom level (default: 1)
maxZoom: maximum zoom level (default: ceil(log2(imageSize/tileSize)))
*/
function GroupXIV(options) {
var viewport = options.viewport,
scale = options.scale,
layers = options.layers;
var maxImageSize = 0, maxWidth = 0, maxHeight = 0, minZoom = 1, maxZoom = 1;
layers.forEach(function(layer) {
if(layer.imageSize > maxImageSize)
maxImageSize = layer.imageSize;
if(layer.width > maxWidth)
maxWidth = layer.width;
if(layer.height > maxHeight)
maxHeight = layer.height;
var layerMaxDim = Math.max(layer.width, layer.height);
var layerMinZoom = layer.minZoom, layerMaxZoom = layer.maxZoom;
if(layerMinZoom === undefined)
layerMinZoom = 1;
if(layerMaxZoom === undefined)
layerMaxZoom = Math.ceil(Math.log2(layer.imageSize / layer.tileSize));
if(layerMinZoom < minZoom)
minZoom = layerMinZoom;
if(layerMaxZoom > maxZoom)
maxZoom = layerMaxZoom;
});
var map = L.map(options.viewport, {
minZoom: minZoom,
maxZoom: maxZoom,
crs: L.CRS.Simple,
});
var center = map.unproject([maxImageSize / 2, maxImageSize / 2], maxZoom);
map.setView(center, minZoom);
if(options.tilesAlignedTopLeft) {
map.setMaxBounds(new L.LatLngBounds(
map.unproject([0, 0], maxZoom),
map.unproject([maxWidth, maxHeight], maxZoom)));
} else {
var marginX = (maxImageSize - maxWidth) / 2,
marginY = (maxImageSize - maxHeight) / 2;
map.setMaxBounds(new L.LatLngBounds(
map.unproject([maxImageSize - marginX, marginY], maxZoom),
map.unproject([marginX, maxImageSize - marginY], maxZoom)));
}
layers.forEach(function(layer) {
var layerMaxZoom = layer.maxZoom;
if(layerMaxZoom === undefined)
layerMaxZoom = Math.ceil(Math.log2(layer.imageSize / layer.tileSize));
L.tileLayer(layer.URL + "-tiles/{z}/{x}/{y}.png", {
maxNativeZoom: layerMaxZoom,
tileSize: layer.tileSize,
continuousWorld: true,
detectRetina: true,
attribution: layer.URL,
}).addTo(map);
});
if(scale !== undefined) {
L.control.nanoscale({
nanometersPerPixel: scale,
ratioAtZoom: maxZoom,
}).addTo(map);
L.control.nanomeasure({
nanometersPerPixel: scale,
ratioAtZoom: maxZoom,
}).addTo(map);
}
L.control.fullscreen({
forceSeparateButton: true,
}).addTo(map);
map.on('enterFullscreen', function(){
document.getElementById('viewer').style.position = 'relative';
});
map.on('exitFullscreen', function(){
document.getElementById('viewer').style.position = 'absolute';
});
L.Control.loading({
separate: true,
}).addTo(map);
return map;
}
|
JavaScript
| 0 |
@@ -2203,24 +2203,358 @@
ileSize));%0A%0A
+ var attribution = %22Layer %22;%0A if(layer.name) %7B%0A attribution += layer.name + %22 (%22 + layer.URL + %22)%22;%0A %7D else %7B%0A attribution += layer.URL;%0A %7D%0A if(layer.copyright) %7B%0A attribution += %22 %5Cu00a9 %22 + layer.copyright;%0A %7D%0A%0A var tileExt = %22.png%22;%0A if(layer.tileExt) %7B%0A tileExt = layer.tileExt;%0A %7D%0A%0A
L.tileLa
@@ -2588,21 +2588,27 @@
/%7Bx%7D/%7By%7D
-.png%22
+%22 + tileExt
, %7B%0A
@@ -2760,25 +2760,27 @@
on:
-layer.URL
+attribution
,%0A %7D)
|
4fb0cd4d6da192473220bdfc73e35506c3eb9c4c
|
Fix bug in kafka lib
|
oada/libs/oada-lib-kafka/base.js
|
oada/libs/oada-lib-kafka/base.js
|
/* Copyright 2017 Open Ag Data Alliance
*
* 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 process = require('process');
const EventEmitter = require('events');
const Bluebird = require('bluebird');
const { Kafka } = require('kafkajs');
const config = require('./config');
const info = require('debug')('@oada/lib-kafka:info');
const error = require('debug')('@oada/lib-kafka:error');
const REQ_ID_KEY = 'connection_id';
const CANCEL_KEY = 'cancel_request';
const CONNECT = Symbol('kafka-lib-connect');
const DATA = Symbol('kafa-lib-data');
function topicTimeout(topic) {
let timeout = config.get('kafka:timeouts:default');
let topics = config.get('kafka:topics');
Object.keys(topics).forEach((topick) => {
if (topics[topick] === topic) {
timeout = config.get('kafka:timeouts:' + topick) || timeout;
}
});
return timeout;
}
// Make it die on unhandled error
// TODO: Figure out what is keeping node from dying on unhandled exception?
function die(err) {
error('Unhandled error: %O', err);
process.abort();
}
class Base extends EventEmitter {
constructor({ consumeTopic, consumer, produceTopic, producer, group }) {
super();
this.consumeTopic = consumeTopic;
this.produceTopic = produceTopic;
this.group = group;
this.requests = {};
this.kafka = new Kafka({
brokers: config.get('kafka:broker').split(','),
});
this.consumer =
consumer ||
this.kafka.consumer({
groupId: this.group,
});
this.producer = producer || this.kafka.producer();
// see: https://github.com/Blizzard/node-rdkafka/issues/222
// says fixed, but seems to still be an issue for us.
process.on('uncaughtExceptionMonitor', async () => {
error('Disconnect kafka clients due to uncaught exception');
// Disconnect kafka clients on uncaught exception
try {
await this.consumer.disconnect();
} catch (err) {
error(err);
}
try {
await this.producer.disconnect();
} catch (err) {
error(err);
}
});
this.ready = Bluebird.fromCallback((done) => {
this[CONNECT] = async () => {
try {
await this.consumer.connect();
await this.producer.connect();
this.consumer.subscribe({ topic: this.consumeTopic });
this.consumer.run({
eachMessage: async ({
message: { value, ...data },
}) => {
// Assume all messages are JSON
const resp = JSON.parse(value);
super.emit(DATA, resp, data);
},
});
} catch (err) {
return done(err);
}
done();
};
});
}
on(event, listener) {
if (event === 'error') {
// Remove our default error handler?
super.removeListener('error', die);
}
super.on(event, listener);
}
async produce({ mesg, topic, part = null }) {
// Assume all messages are JSON
const value = JSON.stringify({
time: Date.now(),
group: this.group,
...mesg,
});
return this.producer.send({
topic: topic || this.produceTopic,
messages: [{ value }],
});
}
async disconnect() {
await this.consumer.disconnect();
await this.producer.disconnect();
}
}
module.exports = {
REQ_ID_KEY,
CANCEL_KEY,
Base,
topicTimeout,
CONNECT,
DATA,
};
|
JavaScript
| 0.000001 |
@@ -3005,32 +3005,38 @@
+await
this.consumer.su
@@ -3086,32 +3086,38 @@
+await
this.consumer.ru
|
41b847b212b7c9b92de8ce2271b1f38110dea107
|
Make the pillar clickthrough work in all cases
|
texcavator/static/js/uva/metagraph.js
|
texcavator/static/js/uva/metagraph.js
|
// Create metadata graphics for a query
function metadataGraphics(query) {
console.log("metadataGraphics()");
// TODO: it's better not to pass the search parameters here. See also TODO in backend.
var params = getSearchParameters();
params.query = query;
dojo.xhrGet({
url: "services/metadata/",
handleAs: "json",
content: params,
}).then(function(response) {
// Add pie charts
addPieChart(response.articletype.buckets, "#chart_articletype");
addPieChart(response.distribution.buckets, "#chart_distribution");
addPieChart(response.pillar, "#chart_pillar");
// Create newspapers bar chart
data_newspapers = [{
"key": "Newspapers",
"values": response.newspapers.buckets
}];
nv.addGraph(function() {
var chart = nv.models.multiBarHorizontalChart()
.x(function(d) {
return d.key;
})
.y(function(d) {
return d.doc_count;
})
.margin({
top: 30,
right: 20,
bottom: 50,
left: 175
})
.valueFormat(d3.format(",d"))
.showValues(true)
.tooltips(true);
chart.yAxis
.tickFormat(d3.format(",d"));
d3.select("#chart_newspapers svg")
.datum(data_newspapers)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}, function(err) {
console.error(err);
});
}
// Create a pie chart for a set of data points
function addPieChart(data, id) {
nv.addGraph(function() {
var chart = nv.models.pieChart()
.x(function(d) {
return d.key;
})
.y(function(d) {
return d.doc_count;
})
.valueFormat(d3.format(",d"))
.showLabels(true);
chart.pie.dispatch.on('elementClick', filterSearch(id));
d3.select(id + " svg")
.datum(data)
.transition().duration(1200)
.call(chart);
return chart;
});
}
// Issue a new search when a pie segment is clicked, filtered by the segment
function filterSearch(id) {
if (id === "#chart_articletype") return function(segmentData) {
var selected = ES_REVERSE_MAPPING.st[segmentData.label].slice(3);
for (key in config.search.type) {
if (key === selected) {
config.search.type[key] = true;
} else {
config.search.type[key] = false;
}
}
searchSubmit();
}; else if (id === "#chart_distribution") return function(segmentData) {
var selected = ES_REVERSE_MAPPING.sd[segmentData.label].slice(3);
for (key in config.search.distrib) {
if (key === selected) {
config.search.distrib[key] = true;
} else {
config.search.distrib[key] = false;
}
}
searchSubmit();
}; else /* id === "#chart_pillar" */ return function(segmentData) {
var selected = segmentData.label;
$('.pillars input').each(function(i) {
var elem = $(this);
if (elem.attr('id') === 'cb-pillar-' + selected) {
elem.prop('checked') = true;
} else {
elem.prop('checked') = false;
}
});
searchSubmit();
}
}
|
JavaScript
| 0.000002 |
@@ -3260,32 +3260,97 @@
(segmentData) %7B%0A
+ getToolbarConfig(); // ensure that the checkboxes exist%0A
var sele
@@ -3353,18 +3353,35 @@
selected
+ID
=
+ 'cb-pillar-' +
segment
@@ -3410,17 +3410,16 @@
'.pillar
-s
input')
@@ -3505,31 +3505,16 @@
id') ===
- 'cb-pillar-' +
selecte
@@ -3506,32 +3506,34 @@
d') === selected
+ID
) %7B%0A
@@ -3559,16 +3559,15 @@
ked'
-) =
+,
true
+)
;%0A
@@ -3624,17 +3624,16 @@
ked'
-) =
+,
false
+)
;%0A
@@ -3685,10 +3685,11 @@
);%0A %7D
+;
%0A%7D
|
a816f7795e74711bb14829ef36c585250b44391a
|
Use global directive to avoid jslint errors
|
pic2map/server/static/js/main.js
|
pic2map/server/static/js/main.js
|
var LocationMap = {
'initialize': function initialize() {
// Map centered in NowSecure HQ by default
this.map = L.map('map').setView([40.2001925,-89.0876265], 3);
this.markerCluster = L.markerClusterGroup();
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
this.map.addLayer(this.markerCluster);
},
'addMarkers': function addMarkers(markersData) {
console.log('Adding ' + markersData.length + ' markers');
markersData.forEach(function(markerData) {
var marker = L.marker([markerData.latitude, markerData.longitude]);
var text = 'Filename: ' + markerData.filename;
if (markerData.datetime) {
text += '<br>GPS datetime: ' + markerData.datetime;
}
marker.bindPopup(text);
this.markerCluster.addLayer(marker);
}, this);
}
};
|
JavaScript
| 0 |
@@ -1,12 +1,66 @@
+// Avoid jslint errors for known globals%0A/*global L*/%0A
var Location
|
94a96c0adf1adea66f3a7f6d2887daf2a8822264
|
Fix permalinks
|
openbas/client/plot.js
|
openbas/client/plot.js
|
function parsePixelsToInt(q) {
return parseFloat(q.slice(0, q.length - 2));
}
instances = [];
if (Meteor.isClient) {
var localtest = false;
Template.plot.plot_data = [
{
tagsURL: localtest ? 'http://localhost:7856' : (Meteor.settings.public.archiverUrl + "/api/query?"),
dataURLStart: localtest ? 'http://localhost:7856/data/uuid' : 'http://archiver.cal-sdb.org:9000/data/uuid/',
bracketURL: "http://archiver.cal-sdb.org:9000/q/bracket",
width: function () {
var $parent = $(instances[instances.length-1].find('.chartContainer')) /* hack */
var width = $parent.css("width");
var leftpadding = $parent.css("padding-left");
var rightpadding = $parent.css("padding-right");
return parsePixelsToInt(width) - parsePixelsToInt(leftpadding) - parsePixelsToInt(rightpadding);
}/*,
hide_main_title: true,
hide_graph_title: true,
hide_settings_title: true*/
},
function (inst)
{
instances.push(inst);
},
window.location.search.length == 0 ? '' : window.location.search.slice(1)];
}
|
JavaScript
| 0.000001 |
@@ -499,748 +499,153 @@
- width: function () %7B%0A var $parent = $(instances%5Binstances.length-1%5D.find('.chartContainer')) /* hack */%0A var width = $parent.css(%22width%22);%0A var leftpadding = $parent.css(%22padding-left%22);%0A var rightpadding = $parent.css(%22padding-right%22);%0A return parsePixelsToInt(width) - parsePixelsToInt(leftpadding) - parsePixelsToInt(rightpadding);%0A %7D/*,%0A hide_main_title: true,%0A hide_graph_title: true,%0A hide_settings_title: true*/%0A %7D, %0A function (inst) %0A %7B %0A instances.push(inst);%0A %7D,%0A window.location.search.length == 0 ? '' : window.location.search.slice(1)
+%7D, %0A function (inst) %0A %7B %0A instances.push(inst);%0A s3ui.default_cb1(inst);%0A %7D,%0A s3ui.default_cb2
%5D;%0A%7D
|
76035eed658d9353625e8ffeeb5d828ac1e19742
|
Use Cadence for `Coordinator.listen`.
|
reconfigure/coordinator.js
|
reconfigure/coordinator.js
|
function Coordinator (consensus) {
this._consensus = consensus
}
Coordinator.prototype.listen = function (url, callback) { // <- listen, POST, -> get them started
this._consensus.addListener(url, function (error, act) {
if (!act) {
callback(null, false)
} else {
callback(null, act.node.value == url)
}
})
}
Coordinator.prototype.unlisten = function (url, callback) {
this._consensus.removeListener(url, function (error, act) {
if (!act) {
callback(null, false)
} else {
callback(null, true)
}
})
}
/*
Coordinator.prototype.update = cadence(function (async) {
async.forEach(function (urls) {
async(function () {
// http POST and service is missing
}, function (body, response) {
if (!response.okay) {
setTimeout(function () { }, 60000)
}
}, function () {
})
})(this._listeners)
})
*/
/* Coordinator.prototype.set = cadence(function (async) {
function (callback) { self.update(callback) }
})
Coordinator.prototype.list = cadence(function (async) {
}) */
module.exports = Coordinator
|
JavaScript
| 0 |
@@ -1,16 +1,50 @@
+var cadence = require('cadence')%0A%0A
function Coordin
@@ -120,32 +120,40 @@
totype.listen =
+cadence(
function (url, c
@@ -146,29 +146,26 @@
nction (
-url, callback
+async, url
) %7B // %3C
@@ -200,16 +200,44 @@
started%0A
+ async(function () %7B%0A
this
@@ -256,32 +256,48 @@
addListener(url,
+ async())%0A %7D,
function (error
@@ -283,39 +283,32 @@
%7D, function (
-error,
act) %7B%0A i
@@ -302,33 +302,32 @@
) %7B%0A if (
-!
act) %7B%0A
@@ -333,74 +333,16 @@
-callback(null, false)%0A %7D else %7B%0A callback(null,
+return (
act.
@@ -370,24 +370,45 @@
%7D%0A
+ return false%0A
%7D)%0A%7D
%0A%0ACoordi
@@ -399,16 +399,17 @@
%7D)%0A%7D
+)
%0A%0ACoordi
|
834d24b6463f91b8f5c7cec9e3cd1286ab03aa51
|
improve latest transactions listing
|
scripts/account_trx_recent.js
|
scripts/account_trx_recent.js
|
/**
* Part of the evias/nem-utils package.
*
* NOTICE OF LICENSE
*
* Licensed under MIT License.
*
* This source file is subject to the MIT License that is
* bundled with this package in the LICENSE file.
*
* @package evias/nem-utils
* @author Grégory Saive <[email protected]> (https://github.com/evias)
* @license MIT License
* @copyright (c) 2017, Grégory Saive <[email protected]>
* @link https://github.com/evias/nem-utils
*/
(function() {
var sdk = require("nem-sdk").default;
var Command = function(ConsoleInput) {
this.run = function() {
console.log("");
ConsoleInput.ask("Your XEM Address", /[A-Z\-0-9]+/, function(address) {
var nodeChar = address.substr(0, 1);
var nodeHost = "http://bob.nem.ninja";
if (nodeChar === 'N') {
nodeHost = "http://alice7.nem.ninja";
}
readTrxs_(address, nodeHost, null, printTrxs_, true);
});
};
};
var globalCnt = 0;
var hasTrxs = {};
var readTrxs_ = function(addr, host, lastId, doneCallback, last25 = false) {
var node = sdk.model.objects.create("endpoint")(host, 7890);
sdk.com.requests.account.transactions.all(node, addr, null, lastId)
.then(function(res) {
if (res.code >= 2) {
console.log("error: ", res);
return false;
}
var isDone = last25;
var cntTrx = res.data.length;
for (var i = 0; i < res.data.length; i++) {
lastId = res.data[i].meta.id;
if (hasTrxs.hasOwnProperty(lastId)) {
isDone = true;
break;
}
hasTrxs[lastId] = res.data[i];
globalCnt++;
}
if (isDone || cntTrx < 25) {
return doneCallback(hasTrxs);
}
readTrxs_(addr, host, lastId, doneCallback);
}, function(err) {
console.log("error: ", err);
return false;
});
};
var printTrxs_ = function(transactions) {
console.log("Recent Transactions: ");
console.log("----------------------------------");
for (var txHash in transactions) {
var metaDataPair = transactions[txHash];
var meta = metaDataPair.meta;
var content = metaDataPair.transaction;
var isMultiSig = content.type === sdk.model.transactionTypes.multisigTransaction;
var realContent = isMultiSig ? content.otherTrans : content;
var trxId = meta.id;
var trxHash = meta.hash.data;
if (meta.innerHash.data && meta.innerHash.data.length)
trxHash = meta.innerHash.data;
var xemAmount = (realContent.amount / Math.pow(10, 6)).toFixed(6);
//XXX add mosaics listing
console.log("- " + "ID: " + trxId + ", Amount: " + xemAmount + " XEM" + ", Hash: " + trxHash);
}
console.log("----------------------------------");
process.exit();
};
module.exports.Command = Command;
}());
|
JavaScript
| 0 |
@@ -1037,44 +1037,341 @@
var
-globalCnt = 0;%0A var hasTrxs = %7B%7D;
+nemEpoch = Date.UTC(2015, 2, 29, 0, 6, 25, 0);%0A var globalCnt = 0;%0A var hasTrxs = %7B%7D;%0A var byDate = %5B%5D;%0A%0A var nemTrxDateCompare_ = function(a, b) %7B%0A if (a.transaction.timeStamp %3C b.transaction.timeStamp) return -1;%0A if (a.transaction.timeStamp %3E b.transaction.timeStamp) return 1;%0A%0A return 0;%0A %7D;%0A
%0A
@@ -2161,16 +2161,70 @@
ata%5Bi%5D;%0A
+ array_push(byDate, res.data%5Bi%5D);%0A%0A
@@ -2308,24 +2308,87 @@
Trx %3C 25) %7B%0A
+ byDate.sort(nemTrxDateCompare_).reverse();%0A
@@ -2415,23 +2415,28 @@
allback(
-hasTrxs
+addr, byDate
);%0A
@@ -2670,16 +2670,25 @@
unction(
+address,
transact
@@ -2822,17 +2822,18 @@
var
-txHash in
+i = 0; i %3C
tra
@@ -2833,32 +2833,44 @@
i %3C transactions
+.length; i++
) %7B%0A
@@ -2905,14 +2905,9 @@
ons%5B
-txHash
+i
%5D;%0A%0A
@@ -3358,16 +3358,260 @@
.data;%0A%0A
+ var nemTime = content.timeStamp;%0A var trxDate = new Date(nemEpoch + (nemTime * 1000));%0A var fmtDate = trxDate.toISOString().replace(/T/, ' ').replace(/%5C..+/, '');%0A var recipient = content.recipient;%0A
@@ -3720,16 +3720,100 @@
isting%0A%0A
+ if (recipient != address)%0A xemAmount = %22-%22 + xemAmount;%0A%0A
@@ -3908,16 +3908,69 @@
trxHash
+ + %22, Recipient: %22 + recipient + %22, Time: %22 + trxDate
);%0A
|
3b68a80addf8e20d9bb30356eaaf919a4e36cb55
|
change surface-datas-2-ts code
|
scripts/surface-datas-2-ts.js
|
scripts/surface-datas-2-ts.js
|
// Usage:
// node ./scripts/surface-datas-2-ts.js [path to the folder contains surface datas]
let input = process.argv[2];
if (!input) {
console.error("Usage");
console.error(" node ./scripts/surface-datas-2-ts.js [path to the folder contains surface datas]");
process.exit();
}
let glob = require("glob");
let fs = require("fs");
let path = require("path");
let output = 'import {IPlanetSurface} from "./genPlanetSurfaceImageData";\n';
output += '/* tslint:disable max-line-length object-literal-key-quotes whitespace*/\n'
glob(path.join(input, "*.json"), {}, (err, files) => {
if (err) {
throw err;
}
for (const name of files) {
const bname = path.basename(name, ".json");
const obj = JSON.parse(fs.readFileSync(name, 'utf8'));
for (const layer of obj.layers) {
const fixedData = [];
let numEmpty = 0;
for (const d of layer.data) {
if (!d.length) {
++numEmpty;
continue;
}
if (numEmpty) {
fixedData.push(numEmpty);
}
fixedData.push(d);
numEmpty = 0;
}
if (numEmpty) {
fixedData.push(numEmpty);
}
layer.data = fixedData;
}
output += `\nexport let ${bname}: IPlanetSurface = ${JSON.stringify(obj)};`;
}
console.log(output);
});
|
JavaScript
| 0 |
@@ -800,87 +800,52 @@
-const fixedData = %5B%5D;%0A let numEmpty = 0;%0A for (const d of layer.data)
+layer.data = layer.data.reduce((ans, cur) =%3E
%7B%0A
@@ -859,10 +859,11 @@
if (
-!d
+cur
.len
@@ -871,122 +871,137 @@
th)
-%7B%0A ++numEmpty;%0A continue;%0A %7D%0A if (numEmpty) %7B%0A fixedData.push(numEmpty
+ans.push(cur);%0A else %7B%0A if (!ans.length %7C%7C typeof ans%5Bans.length - 1%5D !== %22number%22) %7B%0A ans.push(0
);%0A
+
@@ -1001,24 +1001,25 @@
%0A %7D
+
%0A fix
@@ -1019,149 +1019,75 @@
-fixedData.push(d);%0A numEmpty = 0;%0A %7D%0A if (numEmpty) %7B%0A fixedData.push(numEmpty);%0A %7D%0A layer.data = fixedData
+ ans%5Bans.length - 1%5D++;%0A %7D%0A return ans;%0A %7D, %5B%5D)
;%0A
|
948e883f8833a3c6b8182fcde4783a4c7186f2b8
|
update trello-integration
|
scripts/trello-integration.js
|
scripts/trello-integration.js
|
module.exports = function(robot) {
'use strict'
var slackmsg = require("./slackMsgs.js");
var trello = require("./trello-api.js");
var request = require('request');
function sendMessageToSlackResponseURL(responseURL, JSONmessage){
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'Content-type': 'application/json'
},
json: JSONmessage
};
request(postOptions, (error, response, body) => {
if (error){
// handle errors as you see fit
};
})
}
/*******************************************************************/
/* trello api BOARDS */
/*******************************************************************/
// Associate a board with a specific Channel
robot.hear(/trello board (.*)/i, function(res_r) {
let board = res_r.match[1];
// TODO!
})
// trello board
robot.hear(/trello board/i, trello_board)
function trello_board(res_r){
// TODO: fetch the board id from other source (env, redis or mongodb)
let boardId = 'BE7seI7e';
let pars = {lists:"all"};
trello.getBoard(boardId, pars)
.then(function(data){
// customize slack's interactive message
let msg = slackmsg.buttons();
msg.attachments[0].title = `<https://trello.com/b/${boardId}|${data.name}>`;
msg.attachments[0].title_url = 'www.google.com'
msg.attachments[0].author_name = 'Board'
msg.attachments[0].callback_id = `trello_board`;
// attach the board lists to buttons
let joinBtn = {"name": "join", "text": "Join","type":"button", "value": "join"};
let subBtn = {"name": "sub", "text": "Subscribe","type":"button", "value": "sub"};
let starBtn = {"name": "star", "text": "Star","type":"button", "value": "star"};
let listsBtn= {"name": "lists", "text": "Lists","type":"button", "value": "lists"};
let doneBtn = {"name": "done", "text": "Done","type":"button", "value": "done","style": "danger"};
msg.attachments[0].actions.push(joinBtn);
msg.attachments[0].actions.push(subBtn);
msg.attachments[0].actions.push(starBtn);
msg.attachments[0].actions.push(listsBtn);
msg.attachments[0].actions.push(doneBtn);
res_r.send(msg);
})
.fail(function(err){
console.log(err);
})
/*
t.get("/1/board/"+boardId, {lists:"all"}, function(err, data){
if (err){
res_r.send('Error Encountered: '+ err['responseBody']);
return false;
}
// customize slack's interactive message
let msg = slackmsg.buttons();
msg.text = `Board Name: *${data.name}*`;
msg.attachments[0].text = `Board's Lists`;
msg.attachments[0].callback_id = `trello_board`;
// attach the board lists to buttons
let listsNum = Object.keys(data.lists).length;
for (var i=0; i<listsNum; i++){
let list = data.lists[i].name;
let listId = data.lists[i].id;
let item = {"name": list, "text": list,"type":"button", "value": listId};
msg.attachments[0].actions.push(item);
}
res_r.send(msg);
})*/
}
/*******************************************************************/
/* robot.on listeners */
/*******************************************************************/
var slackCB = 'slack:msg_action:';
// responding to 'trello_board' interactive message
robot.on(slackCB + 'trello_board', function(data, res){
console.log(`robot.on: ${slackCB}trello_board`);
let btnId = data.actions[0].value;
let btnName = data.actions[0].name;
let response_url = data.response_url;
switch (btnId) {
case 'join':
break;
case 'sub':
break;
case 'star':
break;
case 'lists':
res.status(200).end() // best practice to respond with 200 status
let listsNum = Object.keys(data.lists).length;
let msg = slackmsg.menu();
for (var i=0; i<listsNum; i++){
// TODO change value to some id or something similar
let list = {"text": data.lists[i], "value": data.lists[i]};
msg.attachments[0].actions[0].options.push(list);
}
sendMessageToSlackResponseURL(response_url, msg);
break;
case 'done':
res.status(200).end() // best practice to respond with 200 status
let msg = slackmsg.plainText();
sendMessageToSlackResponseURL(response_url, msg);
// res.send(msg);
break;
default:
//Statements executed when none of the values match the value of the expression
break;
}
})
// responding to 'trello_list' interactive message
robot.on(slackCB + 'trello_list', function(data_board, res){
console.log(`robot.on: ${slackCB}trello_list`);
let listId = data_board.actions[0].value;
let listName = data_board.actions[0].name;
// call function to fetch list - provide list id
let pars = {cards: "all"};
trello.getList(listId, pars)
.then(function(data_list){
// create buttons msg
let msg = slackmsg.buttons();
msg.text = `*${listName}* list`;
msg.attachments[0].text = `Available Cards`;
msg.attachments[0].callback_id = `trello_list`;
let cardsNum = Object.keys(data_list.cards).length;
console.log(`total cards: ${cardsNum}`);
for (var i=0; i<cardsNum; i++){
let card = data_list.cards[i].name;
let cardId = data_list.cards[i].id;
let item = {"name": card, "text": card,"type":"button", "value": cardId};
msg.attachments[0].actions.push(item);
}
// respond with information for that list
res.send(msg);
console.log(msg.attachments[0].actions);
})
.fail(function(err){
res.send(err);
console.log(err);
});
})
/* TODO: add more functionality */
}
/* template */
// robot.respond(/trello /i, function(res_r) {
// t.post("/1/", function(err, data){
// if (err){
// res_r.send('Error Encountered: '+ err['responseBody']);
// }
// })
// })
/* An example of using slack's response_url. ~For future use */
/* Add this snippet inside robot.on that u want to trigger */
// var response_url = data.response_url;
// var slackMsg = require('./slackMsgs');
// var response = slackMsg.ephemeralMsg();
// sendMessageToSlackResponseURL(response_url, response);
|
JavaScript
| 0 |
@@ -4214,16 +4214,33 @@
nse_url;
+%0A let msg;
%0A%0A
@@ -4552,36 +4552,32 @@
th;%0A
-let
msg = slackmsg.m
@@ -5038,36 +5038,32 @@
tus%0A
-let
msg = slackmsg.p
|
eab5f9ad205fcbcb2c0be1c39c58bf4ccb3d7beb
|
Remove default output of all env vars
|
packages/info/index.js
|
packages/info/index.js
|
const _ = {
pick: require('lodash.pick'),
};
const express = require('express');
const fs = require('fs');
const path = require('path');
module.exports = () => {
const router = new express.Router();
const version = require('@maxdome/version')();
router.get('/version', (req, res) => {
res.send(version);
});
let env = process.env;
try {
const keys = fs
.readFileSync(path.join(process.cwd(), '.env.example'), 'utf-8')
.split('\n')
.map(line => {
const matches = line.match(/([A-Z_]*)=.*? #info/);
if (matches) {
return matches[1];
}
})
.filter(key => key);
env = _.pick(env, keys);
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
router.get('/env', (req, res) => {
res.send(env);
});
return router;
};
|
JavaScript
| 0.000001 |
@@ -197,16 +197,17 @@
uter();%0A
+%0A
const
@@ -317,16 +317,17 @@
;%0A %7D);%0A
+%0A
let en
@@ -334,19 +334,10 @@
v =
-process.env
+%7B%7D
;%0A
@@ -647,16 +647,24 @@
_.pick(
+process.
env, key
@@ -739,16 +739,19 @@
%7D%0A %7D%0A
+ %0A
router
@@ -804,16 +804,17 @@
;%0A %7D);%0A
+%0A
return
|
de13a1eb804d288cd88b17c30090a560947437fd
|
update end dialog
|
server/controllers/newsbot.js
|
server/controllers/newsbot.js
|
const fetch = require('node-fetch');
const builder = require('botbuilder');
const newsSource = require('../resources/newsapi');
const db = require('./db');
const env = process.env;
function init(app) {
// Create chat bot and binding
const connector = new builder.ChatConnector({
appId: env.BOT_APP_ID,
appPassword: env.BOT_APP_PASSWORD,
});
app.post('/api/news', connector.listen());
const bot = new builder.UniversalBot(connector, (session) => {
session.send('Sorry, I did not understand \'%s\'. Send \'help\' if you need assistance.', session.message.text);
});
// Create LUIS recognizer that points at our model
const recognizer = new builder.LuisRecognizer(env.LUIS_MODEL);
bot.recognizer(recognizer);
// Get all news
bot.dialog('GetNews', [
(session, args, next) => {
session.send('Welcome to the Keep Me Updated! We are analyzing your message: \'%s\'', session.message.text);
// try extracting entities
const cityEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'builtin.geography.city');
if (cityEntity) {
// city entity detected, continue to next step
session.dialogData.searchType = 'city';
next({ response: cityEntity.entity });
} else {
// no entities detected, get news everywhere
session.dialogData.searchType = 'world';
next({ response: 'everywhere' });
}
},
(session, results) => {
// Send initial replied message
const location = results.response;
let message = 'Looking for news';
if (session.dialogData.searchType === 'city') {
message += ' around %s for you...'; // around Seattle...
} else {
message += ' %s for you...'; // everywhere...
}
session.send(message, location);
// Get news
// GET https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=<key>
fetch(`https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=${env.NEWS_API_KEY}`)
.then(res => res.json())
.then((json) => {
session.send('I found %d articles:', json.articles.length);
const responseMessage = new builder.Message()
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(json.articles.map(newsAsAttachment));
session.send(responseMessage);
session.endDialog();
});
},
]).triggerAction({
matches: 'GetNews',
onInterrupted: (session) => {
session.send('Please try again');
},
});
// Get news from specific source
bot.dialog('GetNewsFromSource', (session, args) => {
session.send('Welcome to the Keep Me Updated! We are analyzing your message: \'%s\'', session.message.text);
// try extracting entities
const customNewsOrgEntity = builder.EntityRecognizer.findEntity(args.intent.entities, 'NewsOrg');
if (customNewsOrgEntity && customNewsOrgEntity.entity) {
// Okay, seems like we detect a legit new knownOrganization
session.send('Looking for news at \'%s\'...', customNewsOrgEntity.entity);
// Check with our eixsting set of supported new org
const formattedNewSource = newsSource.getFormattedSourceNews(customNewsOrgEntity.entity);
// Get news
fetch(`https://newsapi.org/v1/articles?source=${formattedNewSource}&sortBy=latest&apiKey=${env.NEWS_API_KEY}`)
.then(res => res.json())
.then((json) => {
const responseMessage = new builder.Message()
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(json.articles.map(newsAsAttachment));
session.send(responseMessage);
session.endDialog();
});
} else {
session.send('Hmm we don\'t have that source, but here\'s google news...');
fetch(`https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=${env.NEWS_API_KEY}`)
.then(res => res.json())
.then((json) => {
session.send('I found %d articles:', json.articles.length);
const responseMessage = new builder.Message()
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(json.articles.map(newsAsAttachment));
session.send(responseMessage);
session.endDialog();
});
}
}).triggerAction({
matches: 'GetNewsFromSource'
});
// List all news sources
bot.dialog('listNewsSource', (session) => {
session.send('Hi! I pull the news from these sources: ');
session.send(newsSource.getAllSources());
session.endDialog();
}).triggerAction({
matches: 'listNewsSource',
});
// Print out help message
bot.dialog('Help', (session) => {
session.endDialog('Hi! Try asking me things like \'show me supported news sources\' \'get news from Times\', \'show me news today\' or \'show me techcrunch news\'');
}).triggerAction({
matches: 'Help',
});
// set schedule for chef
bot.dialog('setChefSchedule', [
(session) => {
builder.Prompts.text(session, 'Ahh.. you found my easter egg... So what\'s the secret code?');
},
(session, results) => {
session.userData.secret = results.response;
if (session.userData.secret === env.DB_SECRET) {
builder.Prompts.text(session, 'Great!, When do you want to make chefs available at 3am? (yyyy-mm-dd)?');
} else {
session.endDialog('Sorry, wrong answer. You should ask srve for the code and try again');
}
},
(session, results) => {
db.setScheduleDate(results.response, 1).then((rows) => {
session.endDialog(`Done! I just updated the chef schedules. Chef will available on ${results.response} at 3am. Open the app and see if that works.`);
}).catch((err) => {
console.log(err);
session.endDialog(`Hmm... I didn't feel well and couldn't bring chef online on ${results.response} at 3am. Pick up the phone and call my owner...`);
});
},
]).triggerAction({
matches: 'setChefSchedule',
});
}
// Helpers
function newsAsAttachment(news) {
return new builder.HeroCard()
.title(news.title)
.subtitle(news.description)
.images([new builder.CardImage().url(news.urlToImage)])
.buttons([
new builder.CardAction()
.title('More details')
.type('openUrl')
.value(news.url),
]);
}
module.exports.init = init;
|
JavaScript
| 0.000001 |
@@ -5398,25 +5398,20 @@
session.
+s
end
-Dialog
('Sorry,
@@ -5471,24 +5471,53 @@
ry again');%0A
+ session.endDialog();%0A
%7D%0A
@@ -5626,25 +5626,20 @@
session.
+s
end
-Dialog
(%60Done!
@@ -5759,24 +5759,53 @@
t works.%60);%0A
+ session.endDialog();%0A
%7D).cat
@@ -5860,25 +5860,20 @@
session.
+s
end
-Dialog
(%60Hmm...
@@ -5992,24 +5992,53 @@
owner...%60);%0A
+ session.endDialog();%0A
%7D);%0A
|
48459bf968f57d115d82cfc885a2183a53a0cb1a
|
Make haproxy file more compact
|
server/lib/HAProxyTemplate.js
|
server/lib/HAProxyTemplate.js
|
var fs = require('fs');
module.exports = function () {
return new HAProxyTemplate();
}
//function constructor for making HAProxy conf files
function HAProxyTemplate () {
this.mainPort;
this.webAppAddress;
this.tcpMaps = [];
this.httpMaps = [];
this.file = getTemplate();
}
//the port used to redirect all HTTP connections to places such as the web app and the HMI
HAProxyTemplate.prototype.setMainPort = function (port) {
this.mainPort = port;
return this;
};
//the port used to redirect all HTTP connections to places such as the web app and the HMI
HAProxyTemplate.prototype.setWebAppAddress = function (address) {
this.webAppAddress = address;
return this;
};
//route all traffic from one address to another
HAProxyTemplate.prototype.addHttpRoute = function (from, to) {
this.httpMaps.push({
from: from,
to: to
});
return this;
};
//expose a port for a single TCP connection to core, and route traffic to another address
HAProxyTemplate.prototype.addTcpRoute = function (port, to) {
this.tcpMaps.push({
port: port,
to: to
});
return this;
};
//uses all the information in the object and makes a proper HAProxy configuration file out of it
HAProxyTemplate.prototype.generate = function () {
//first, add all the front ends. the HTTP front end binds to the main port
this.file += `
frontend main
bind *:${this.mainPort}
mode http`;
//for each http address (don't distinguish http and websocket connection)
//create an ACL for checking the subdomain address
for (let i = 0; i < this.httpMaps.length; i++) {
let map = this.httpMaps[i];
this.file += `
acl http-front-${i} hdr_end(host) -i ${map.from}.${process.env.DOMAIN_NAME}:${this.mainPort}`;
}
//set up the redirections to the (currently nonexisting) backends
for (let i = 0; i < this.httpMaps.length; i++) {
let map = this.httpMaps[i];
this.file += `
use_backend http-back-${i} if http-front-${i}`;
}
//set the default backend to the web app
this.file += `
default_backend app
`;
//now add the TCP frontends
for (let i = 0; i < this.tcpMaps.length; i++) {
let map = this.tcpMaps[i];
this.file += `
frontend tcp-front-${i}
bind *:${map.port}
mode tcp
default_backend tcp-back-${i}
`;
}
//next, specify the backends
//the web app backend
this.file += `
backend app
mode http
server webapp ${this.webAppAddress}
`;
//http backends
for (let i = 0; i < this.httpMaps.length; i++) {
let map = this.httpMaps[i];
this.file += `
backend http-back-${i}
mode http
server http-server-${i} ${map.to}
`;
}
//tcp backends
for (let i = 0; i < this.tcpMaps.length; i++) {
let map = this.tcpMaps[i];
this.file += `
backend tcp-back-${i}
mode tcp
server tcp-server-${i} ${map.to}
`;
}
return this.file;
}
//returns an HAProxy template
function getTemplate () {
return fs.readFileSync(`${__dirname}/../templates/haproxyConfig`, 'utf-8');
}
|
JavaScript
| 0.000012 |
@@ -1991,17 +1991,19 @@
app%0A%60;%0A
+/*
%0A
-
%09//now a
@@ -2209,17 +2209,19 @@
%7D%0A%60;%0A%09%7D%0A
+*/
%0A
-
%09//next,
@@ -2535,17 +2535,19 @@
%0A%60;%09%0A%09%7D%0A
+/*
%0A
-
%09//tcp b
@@ -2715,22 +2715,285 @@
map.to%7D%0A
-
%60;%09%0A%09%7D
+%0A*/%0A%09//tcp proxying, from front to back, using the listen directive%0A%09for (let i = 0; i %3C this.tcpMaps.length; i++) %7B%0A%09%09let map = this.tcpMaps%5Bi%5D;%0A%09%09this.file += %60%0Alisten tcp-$%7Bi%7D%0A%09bind *:$%7Bmap.port%7D%0A%09mode tcp%0A%09option tcplog%0A%09server tcp-server-$%7Bi%7D $%7Bmap.to%7D%0A%60;%0A%09%7D
%0A%0A re
|
4cc5faafc36b0e85c10f50dff5c9e5d7364b18e5
|
Clean up output from wmic
|
server/lib/getDriveLetters.js
|
server/lib/getDriveLetters.js
|
const childProcess = require('child_process')
const command = 'wmic logicaldisk get caption'
module.exports = function () {
return new Promise((resolve, reject) => {
childProcess.exec(command, (err, stdout) => {
if (err) {
return reject(err)
}
const rows = stdout.split(/\r?\n/)
resolve(rows)
})
})
}
|
JavaScript
| 0.99997 |
@@ -309,27 +309,86 @@
%5Cn/)
-%0A resolve(rows
+.filter(row =%3E row.trim().endsWith(':'))%0A resolve(rows.map(r =%3E r.trim())
)%0A
|
2dd44cecf1ae06e8febf33cf036794adee46a090
|
Fix typo in function name
|
server/models/favorite_tag.js
|
server/models/favorite_tag.js
|
import cozydb from 'cozydb';
import invariant from 'invariant';
import logger from 'debug';
import hasValue from '../hasValue';
const debug = logger('app:model:favorite_tag');
const FavoriteTag = cozydb.getModel('FavoriteTag', {
'label': String,
'application': String,
});
export default FavoriteTag;
FavoriteTag.allForTasky = (callback) => {
invariant(hasValue(callback), '`callback` is a mandatory parameter');
invariant(typeof callback === 'function', '`callback` must be a function');
debug('Retrieve all favorite tag for app Tasky.');
FavoriteTag.request('allByApp', {key: 'tasky'}, (err, tags) => {
const error = err || tags.error;
if (hasValue(error)) {
callback(error);
} else {
const labels = tags.map(tag => tag.label);
callback(null, labels);
}
});
};
FavoriteTag.ByLabelForTasky = (label, callback) => {
invariant(hasValue(label), '`label` is a mandatory parameter');
invariant(hasValue(callback), '`callback` is a mandatory parameter');
invariant(typeof label === 'string', '`label` must be a string');
invariant(typeof callback === 'function', '`callback` must be a function');
debug('Retrieve a favorite tag given a label, for app Tasky.');
const options = {
key: ['tasky', label],
};
FavoriteTag.request('byAppByLabel', options, callback);
};
|
JavaScript
| 0.999921 |
@@ -870,17 +870,17 @@
riteTag.
-B
+b
yLabelFo
|
725abf4ea9bd41c929f67686fa3efd51c7ea6d19
|
Add navy available-services command
|
packages/navy/src/cli/program.js
|
packages/navy/src/cli/program.js
|
import program from 'commander'
import {NavyError} from '../errors'
import {getConfig} from '../config'
import {startDriverLogging, stopDriverLogging} from '../driver-logging'
const loadingLabelMap = {
destroy: 'Destroying services...',
start: 'Starting services...',
stop: 'Stopping services...',
restart: 'Restarting services...',
kill: 'Killing services...',
rm: 'Removing services...',
pull: 'Pulling service images...',
}
function wrapper(res) {
if (res.catch) {
res.catch(ex => {
stopDriverLogging({ success: false })
if (ex instanceof NavyError) {
ex.prettyPrint()
} else {
console.error(ex.stack)
}
})
}
return res
}
function basicCliWrapper(fnName, opts = {}) {
const driverLogging = opts.driverLogging == null ? true : opts.driverLogging
return async function (maybeServices, ...args) {
const { getNavy } = require('../navy')
const opts = args.length === 0 ? maybeServices : args[args.length - 1]
const otherArgs = args.slice(0, args.length - 1)
const envName = opts.navy
if (driverLogging) startDriverLogging(loadingLabelMap[fnName])
const returnVal = await wrapper(getNavy(envName)[fnName](
Array.isArray(maybeServices) && maybeServices.length === 0
? undefined
: maybeServices,
...otherArgs,
))
if (driverLogging) stopDriverLogging()
if (returnVal != null) {
console.log(returnVal)
}
}
}
function lazyRequire(path) {
return function (...args) {
const mod = require(path)
return wrapper((mod.default || mod)(...args))
}
}
const defaultNavy = getConfig().defaultNavy
program
.command('launch [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Launches the given services in an navy')
.action(lazyRequire('./launch'))
.on('--help', () => console.log(`
This will prompt you for the services that you want to bring up.
You can optionally provide the names of services to bring up which will disable the interactive prompt.
`))
program
.command('destroy')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.option('-f, --force', 'don\'t prompt before removing the navy')
.description('Destroys an navy and all related data and services')
.action(basicCliWrapper('destroy'))
.on('--help', () => console.log(`
This will destroy an entire navy and all of its data and services.
Examples:
$ navy destroy # destroy "${defaultNavy}" navy
$ navy destroy -e dev # destroy "dev" navy
$ navy destroy -e test # destroy "test" navy
`))
program
.command('ps')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.option('--json', 'output JSON instead of a table')
.description('Lists the running services for an navy')
.action(lazyRequire('./ps'))
program
.command('start [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Starts the given services')
.action(basicCliWrapper('start'))
program
.command('stop [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Stops the given services')
.action(basicCliWrapper('stop'))
program
.command('restart [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Restarts the given services')
.action(basicCliWrapper('restart'))
program
.command('kill [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Kills the given services')
.action(basicCliWrapper('kill'))
program
.command('rm [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Removes the given services')
.action(basicCliWrapper('rm'))
program
.command('pull [services...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Pulls the given services\' images from their respective registries')
.action(basicCliWrapper('pull'))
program
.command('host <service>')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Prints the external host for the given service')
.action(basicCliWrapper('host', { driverLogging: false }))
.on('--help', () => console.log(`
Examples:
$ navy host mywebserver
localhost
`))
program
.command('port <service> <port>')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Prints the external port for the given internal port of the given service')
.action(basicCliWrapper('port', { driverLogging: false }))
.on('--help', () => console.log(`
Examples:
$ navy port mywebserver 80
35821
`))
program
.command('develop [service]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Puts the given service into development using the current working directory')
.action(lazyRequire('./develop'))
program
.command('live [service]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Takes the given service out of development')
.action(lazyRequire('./live'))
program
.command('run <name> [args...]')
.option('-e, --navy [env]', `set the navy name to be used [${defaultNavy}]`, defaultNavy)
.description('Runs a named command specific to the given Navy')
.action(lazyRequire('./run'))
program
.command('status')
.option('--json', 'output JSON instead of a table')
.description('List all of the running navies and the status of their services')
.action(lazyRequire('./status'))
program
.command('set-default <navy>')
.description('Set the default navy')
.action(lazyRequire('./set-default'))
export default program
|
JavaScript
| 0.000155 |
@@ -1383,16 +1383,106 @@
ging()%0A%0A
+ if (Array.isArray(returnVal)) %7B%0A return console.log(returnVal.join('%5Cn'))%0A %7D%0A%0A
if (
@@ -5059,32 +5059,335 @@
35821%0A %60))%0A%0A
+program%0A .command('available-services')%0A .option('-e, --navy %5Benv%5D', %60set the navy name to be used %5B$%7BdefaultNavy%7D%5D%60, defaultNavy)%0A .description('Prints the names of the services that are launched or can be launched')%0A .action(basicCliWrapper('getAvailableServiceNames', %7B driverLogging: false %7D))%0A%0A
program%0A .comma
|
88599a0bd4ada01e14f274376c76265739819e8f
|
add curry2 and curry3 implementations
|
packages/prelude/src/function.js
|
packages/prelude/src/function.js
|
/** @license MIT License (c) copyright 2010-2016 original author or authors */
// id :: a -> a
export const id = x => x;
// compose :: (b -> c) -> (a -> b) -> (a -> c)
export const compose = (f, g) => x => f(g(x));
// apply :: (a -> b) -> a -> b
export const apply = (f, x) => f(x);
|
JavaScript
| 0.000234 |
@@ -279,8 +279,658 @@
%3E f(x);%0A
+%0A// curry2 :: (a -%3E b -%3E c) -%3E a -%3E b -%3E c%0Aexport function curry2(f) %7B%0A function curried(a, b) %7B%0A switch (arguments.length) %7B%0A case 0: return curried;%0A case 1: return b =%3E f(a, b);%0A default:return f(a, b);%0A %7D%0A %7D%0A return curried;%0A%7D%0A%0A// curry3 :: (a -%3E b -%3E c -%3E d) -%3E a -%3E b -%3E c -%3E d%0Aexport function curry3(f) %7B%0A function curried(a, b, c) %7B%0A switch (arguments.length) %7B%0A case 0: return curried;%0A case 1: return curry2((b, c) =%3E f(a, b, c));%0A case 2: return c =%3E f(a, b, c);%0A default:return f(a, b, c);%0A %7D%0A %7D%0A return curried;%0A%7D%0A
|
afff9c9431cc74c17eb2149466bbe343b02bb6a4
|
remove style none value filter (#1461)
|
packages/stylesheet/src/index.js
|
packages/stylesheet/src/index.js
|
import * as R from 'ramda';
import expandStyles from './expand';
import flattenStyles from './flatten';
import transformStyles from './transform';
import resolveMediaQueries from './mediaQueries';
/**
* Filter styles with `none` value
*
* @param {Object} style object
* @returns {Object} style without none values
*/
const filterNoneValues = R.reject(R.equals('none'));
/**
* Resolves styles
*
* @param {Object} container
* @param {Object} style object
* @returns {Object} resolved style object
*/
const resolveStyles = (container, style) =>
R.compose(
transformStyles(container),
expandStyles,
resolveMediaQueries(container),
filterNoneValues,
flattenStyles,
)(style);
export default R.curryN(2, resolveStyles);
|
JavaScript
| 0 |
@@ -196,187 +196,8 @@
';%0A%0A
-/**%0A * Filter styles with %60none%60 value%0A *%0A * @param %7BObject%7D style object%0A * @returns %7BObject%7D style without none values%0A */%0Aconst filterNoneValues = R.reject(R.equals('none'));%0A%0A
/**%0A
@@ -473,30 +473,8 @@
r),%0A
- filterNoneValues,%0A
|
02540e4cb05c2f4bdee056f9ebb4eb0c32033a5b
|
fix failing test that used old selected rows key format (integer)
|
packages/table/src/Table.test.js
|
packages/table/src/Table.test.js
|
import React from "react";
import Adapter from "enzyme-adapter-react-16";
import { mount, configure } from "enzyme";
import Table from "./Table";
import Column from "./Column";
const dataFixture = [{ name: "foo" }, { name: "bar" }];
describe("Table", function() {
configure({ adapter: new Adapter() });
test("Checking the Select All checkbox of a table should select all it's rows", function() {
const component = mount(
<Table selectableRows data={dataFixture}>
<Column title="Name" text={row => row.name} />
</Table>
);
const selectAllButton = component.find("th input");
selectAllButton.simulate("change", { target: { checked: true } });
const newState = component.state();
expect(newState.selectedRows.length).toBe(dataFixture.length);
});
test("Unchecking the Select All checkbox of a table should select all it's rows", function() {
const component = mount(
<Table selectableRows data={dataFixture}>
<Column title="Name" text={row => row.name} />
</Table>
);
component.setState({ selectedRows: [0, 1] });
expect(component.state().selectedRows.length).toBe(dataFixture.length);
const selectAllButton = component.find("th input");
selectAllButton.simulate("change", { target: { checked: false } });
expect(component.state().selectedRows.length).toBe(0);
});
test("Selecting a row should change the selectedRows state", function() {
const component = mount(
<Table selectableRows data={dataFixture}>
<Column title="Name" text={row => row.name} />
</Table>
);
const firstRowCheckbox = component.find("td input").first();
expect(component.state().selectedRows.length).toBe(0);
firstRowCheckbox.simulate("change", { target: { checked: true } });
expect(component.state().selectedRows.length).toBe(1);
});
test("Deselecting a row should change the selectedRows state", function() {
const component = mount(
<Table selectableRows data={dataFixture}>
<Column title="Name" text={row => row.name} />
</Table>
);
component.setState({ selectedRows: [0] });
const firstRowCheckbox = component.find("td input").first();
expect(component.state().selectedRows.length).toBe(1);
firstRowCheckbox.simulate("change", { target: { checked: false } });
expect(component.state().selectedRows.length).toBe(0);
});
test("Clicking on a column title on a table without onTitleClick should return null", function() {
const component = mount(
<Table data={dataFixture}>
<Column clickable title="Name" text={row => row.name} />
</Table>
);
const firstTitleLink = component.find("th Link").first();
const preventDefaultMock = jest.fn();
const clickReturn = firstTitleLink
.props()
.onClick({ preventDefault: preventDefaultMock });
firstTitleLink.simulate("click", { preventDefault: preventDefaultMock });
expect(preventDefaultMock).toBeCalled();
expect(clickReturn).toBe(null);
});
test("Clicking on a column title on a clickable column should call onTitleClick", function() {
const preventDefaultMock = jest.fn();
const onTitleClickMock = jest.fn();
const component = mount(
<Table data={dataFixture} onTitleClick={onTitleClickMock}>
<Column clickable title="Name" text={row => row.name} />
</Table>
);
const firstTitleLink = component.find("th Link").first();
firstTitleLink.props().onClick({ preventDefault: preventDefaultMock });
expect(preventDefaultMock).toBeCalled();
expect(onTitleClickMock).toBeCalled();
});
test("Table with selection header bar should clear all selected row if the passed clearFunction is called", function() {
const selectionHeaderRenderer = (data, clearFunction) => (
<button id="testButton" onClick={clearFunction} />
);
const component = mount(
<Table
data={dataFixture}
selectableRows
selectionHeader={selectionHeaderRenderer}
>
<Column clickable title="Name" text={row => row.name} />
</Table>
);
const firstRowCheckbox = component.find("td input").first();
firstRowCheckbox.simulate("change", { target: { checked: true } });
const testButton = component.find("#testButton");
expect(component.state().selectedRows.length).toBe(1);
testButton.simulate("click");
expect(component.state().selectedRows.length).toBe(0);
});
});
|
JavaScript
| 0.000003 |
@@ -2129,17 +2129,20 @@
dRows: %5B
-0
+%220,%22
%5D %7D);%0A
|
9c299907c8253f5e6647937970c6adb24325e123
|
fix tests
|
packages/zent/__tests__/affix.js
|
packages/zent/__tests__/affix.js
|
import Affix from 'affix';
import React from 'react';
import { mount } from 'enzyme';
describe('Affix component', () => {
it('Affix has props', () => {
const wrapper = mount(<Affix />);
expect(wrapper.find('.zent-affix').length).toBe(1);
const props = wrapper.find('Affix').props();
expect(props.offsetTop).toBe(0);
expect(props.prefix).toBe('zent');
expect(props.zIndex).toBe(10);
});
it('Affix set props', () => {
const wrapper = mount(
<Affix prefix="wulv" className="affix" zIndex={100} offsetTop={50} />
);
const props = wrapper.props();
const state = wrapper.state();
expect(props.offsetTop).toBe(50);
expect(props.prefix).toBe('wulv');
expect(props.zIndex).toBe(100);
expect(props.className).toBe('affix');
expect(wrapper.node.affix).toBe(true);
expect(state.position).toBe('fixed');
expect(state.width).toBe(0);
});
it('Affix scroll events', () => {
const wrapper = mount(<Affix offsetTop={50} />);
const state = wrapper.state();
expect(wrapper.node.affix).toBe(true);
expect(state.width).toBe(0);
expect(state.position).toBe('fixed');
expect(state.placeHoldStyle.width).toBe('100%');
expect(state.placeHoldStyle.height).toBe(0);
expect(wrapper.node.affix).toBe(true);
wrapper.setProps({ offsetTop: -100 });
wrapper.node.checkFixed();
class Test extends React.Component {
state = {
value: 0
};
onUnpin = () => {
this.setState({ value: 10 });
};
onPin = () => {
this.setState({ value: 20 });
};
render() {
const { value } = this.state;
return (
<Affix onUnpin={this.onUnpin} onPin={this.onPin} offsetBottom={50}>
<p id="value">{value}</p>
</Affix>
);
}
}
const wrapper1 = mount(<Test />);
const affix = wrapper1.find('Affix');
const state1 = affix.node.state;
expect(state1.width).toBe(0);
affix.node.handleScroll();
affix.node.pin();
affix.node.unpin();
wrapper1.unmount();
});
it('unpin if offset is not reached', () => {
const wrapper = mount(
<Affix prefix="wulv" className="affix" zIndex={100} offsetTop={50} />
);
const { node } = wrapper;
expect(node.affix).toBe(true);
wrapper.setProps({ offsetTop: -100 });
expect(node.affix).toBe(true);
});
});
|
JavaScript
| 0.000001 |
@@ -1354,18 +1354,17 @@
ode.
-checkFixed
+updatePin
();%0A
|
d0c0b814e31d19d5eaf06d4c079272f2793a671c
|
change color
|
src/map-generator/object/room.js
|
src/map-generator/object/room.js
|
const Color ='#ff00ff';
class Room extends Phaser.Sprite {
constructor(game, width, height) {
let bmd = game.add.bitmapData(width,height);
// draw to the canvas context like normal
bmd.ctx.beginPath();
bmd.ctx.rect(0,0,width,height);
bmd.ctx.fillStyle = '#ff0000';
bmd.ctx.fill();
super(game,width,height, bmd);
}
}
export default Room;
|
JavaScript
| 0.000018 |
@@ -10,17 +10,17 @@
or =
-'#ff00ff'
+ %22473B3B%22
;%0A%0Ac
@@ -275,17 +275,13 @@
e =
-'#ff0000'
+Color
;%0A
|
513cd683e0590095ae3ddb0b1d9a726cb2dc3d3d
|
Simplify futureTimeout code
|
src/middleware/authentication.js
|
src/middleware/authentication.js
|
import _ from 'lodash/fp'
import { REHYDRATE } from 'redux-persist/constants'
import {
refreshAuthenticationToken,
scheduleAuthRefresh,
} from '../actions/authentication'
import { AUTHENTICATION } from '../constants/action_types'
const toMilliseconds = seconds => seconds * 1000
const fromNow = (time) => time - new Date()
const atLeastFifty = _.partial(Math.max, 50)
// Reverse arity, curried version of https://lodash.com/docs#subtract
const subtract = subtrahend => minuend => minuend - subtrahend
// Get a timeout value about 100ms before a given date,
// or 50ms from this moment if the given date is too close
const futureTimeout = _.pipe(
fromNow,
subtract(100),
atLeastFifty
)
export const authentication = store => next => action => {
const { payload, type } = action
switch (type) {
case REHYDRATE:
if (action.key === 'authentication') {
const { createdAt, expiresIn, refreshToken } = payload
if (!refreshToken) break
const now = new Date()
const expirationDate = new Date(toMilliseconds(createdAt + expiresIn))
if (expirationDate < now) {
store.dispatch(refreshAuthenticationToken(refreshToken))
} else {
const newTimeout = futureTimeout(expirationDate)
store.dispatch(scheduleAuthRefresh(refreshToken, newTimeout))
}
}
break
case AUTHENTICATION.REFRESH_SUCCESS:
case AUTHENTICATION.USER_SUCCESS:
store.dispatch(scheduleAuthRefresh(
payload.response.refreshToken,
toMilliseconds(7100)
))
break
default:
break
}
next(action)
}
|
JavaScript
| 0.00134 |
@@ -1,30 +1,4 @@
-import _ from 'lodash/fp'%0A
impo
@@ -256,420 +256,332 @@
00%0A%0A
-const fromNow = (time) =%3E time - new Date()%0Aconst atLeastFifty = _.partial(Math.max, 50)%0A// Reverse arity, curried version of https://lodash.com/docs#subtract%0Aconst subtract = subtrahend =%3E minuend =%3E minuend - subtrahend%0A%0A// Get a timeout value about 100ms before a given date,%0A// or 50ms from this moment if the given date is too close%0Aconst futureTimeout = _.pipe(%0A fromNow,%0A subtract(100),%0A atLeastFifty%0A)
+// Get a timeout value about 100ms before a given date,%0A// or at least not in the past%0Aconst futureTimeout = time =%3E %7B%0A let msFromNow = time - new Date()%0A%0A // Establish a lead time of 100ms before expiration date%0A msFromNow = msFromNow - 100%0A%0A // Let's not set a timeout for in the past%0A return Math.max(msFromNow, 0)%0A%7D
%0A%0Aex
|
f64ed61876e544768522a86e09cf2725283cf733
|
update test
|
test-workspace/config/spa/test.js
|
test-workspace/config/spa/test.js
|
// import '../task';
import jsConfig from './main-sync';
// import jsConfig from './main-async';
// import jsConfig from './vendor-all';
// import jsConfig from './vendor-custom';
// import jsConfig from './cdn';
// import jsConfig from './extract-css';
export default jsConfig;
|
JavaScript
| 0.000001 |
@@ -247,16 +247,49 @@
ct-css';
+%0A// import jsConfig from './vue';
%0A%0Aexport
|
40b9bfeef5afd27a9a393fe35f013cf0a771fde5
|
Fix bug in jsonParse that misses values which are equivalent to false (like 0).
|
src/models/internal/jsonParse.js
|
src/models/internal/jsonParse.js
|
var mapValueToType = function(rawValue, type) {
var initialValue = null;
if (typeof type === 'object') {
if (type) {
if (type instanceof Array) {
var innerType = type[0];
if (rawValue !== null && rawValue !== undefined) {
initialValue = rawValue.map( v => {
try {
return mapValueToType(v, innerType);
}
catch(e) {
console.log(e);
return v;
}
});
}
}
else {
if (type.mapper && typeof type.mapper === 'function') {
initialValue = (rawValue !== null && rawValue !== undefined) ? type.mapper(rawValue) : null;
}
}
}
}
else if (type === String) {
initialValue = (rawValue !== null && rawValue !== undefined) ? String(rawValue) : null;
}
else if (type === Number) {
initialValue = (rawValue !== null && rawValue !== undefined) ? Number(rawValue) : null;
if (Number.isNaN(initialValue)) {
initialValue = null;
}
}
else if (type === Boolean) {
initialValue = (rawValue !== null && rawValue !== undefined) ? Boolean(rawValue) : null;
}
else if (type === Object) {
initialValue = rawValue || null;
}
else if (type === Date) {
initialValue = new Date(rawValue * 1000);
if(isNaN(initialValue)) {
initialValue = null;
}
else if(initialValue === 'Invalid Date') {
initialValue = null;
}
else{
initialValue = new Date(initialValue.valueOf() + initialValue.getTimezoneOffset() * 60000);
}
}
else if (typeof type === 'function') {
initialValue = (rawValue !== null && rawValue !== undefined) ? new type(rawValue) : null;
}
return initialValue;
};
var setPropertyFromArgs = function(args, obj, name, type, optional, merge) {
if (!obj[name]) {
var rawValue = args[name];
var convertedValue = mapValueToType(rawValue, type);
if (!optional && !convertedValue) {
throw TypeError('non-optional field `' + name + '` found null value. Args:', args);
}
if (convertedValue) {
if (merge) {
obj[name] = convertedValue;
}
else {
Object.defineProperty(obj, name, {
configurable: false,
enumerable: true,
writable: true,
value: convertedValue
});
}
}
}
};
var jsonParseArgs = function(args, obj, merge) {
var properties = obj.jsonProperties;
for (var name in properties) {
if(properties.hasOwnProperty(name)) {
var value = properties[name];
var optional = true;
var type;
if (typeof value === 'object') {
if (value.type !== undefined) {
type = value.type;
}
else if (value.mapper !== undefined) {
type = value;
}
else if (value instanceof Array) {
type = value;
}
if (value.optional !== undefined) {
optional = value.optional;
}
}
else {
type = value;
}
setPropertyFromArgs(args, obj, name, type, optional, merge);
}
}
};
export var jsonCreateWithArgs = function(args, obj) {
jsonParseArgs(args, obj, false);
};
export var jsonMergeWithArgs = function(args, obj) {
jsonParseArgs(args, obj, true);
};
export var jsonCreateFromArrayData = function(arr, type) {
return mapValueToType(arr, type);
};
|
JavaScript
| 0 |
@@ -2071,32 +2071,46 @@
(convertedValue
+ !== undefined
) %7B%0A if (me
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.