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
|
---|---|---|---|---|---|---|---|
3f2d0d93f308a52c533d3e5fd079942e90b0b6e7 | Clean up code | scripts/js/020-components/06-searchresults.js | scripts/js/020-components/06-searchresults.js | // Get URL parameters as an object
// USAGE:
// getAllUrlParams().product; // 'shirt'
// getAllUrlParams().color; // 'blue'
// getAllUrlParams().newuser; // true
// getAllUrlParams().nonexistent; // undefined
// getAllUrlParams('http://test.com/?a=abc').a; // 'abc'
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
// Strip the + delimeters
function stripDelimeters(string) {
return string.split('+').join(' ');
}
// specialCombos()
// if the query matches the predefined combination word terms, use a
// keyword search
function specialCombos(query) {
// query = "keywords:product keywords:manager";
var specials = new Array();
specials[0] = "delivery manager";
specials[1] = "service designer";
specials[2] = "service manager";
specials[3] = "product manager";
specials[4] = "interaction designer";
specials[5] = "visual designer";
specials[6] = "service design";
specials[7] = "technical architect";
specials[8] = "user researcher";
specials[9] = "content designer";
specials[10] = "performance analyst";
var words = query.split(' ');
for (var i = 0; i < specials.length ; i++) {
if (query == specials[i]) {
return "+keywords:" + words[0] + " " + "+keywords:" + words[1];
continue;
}
}
return query;
}
// only run Lunr code on the search page
// as Lunr.min.js is not loaded by default
if (window.location.pathname == "/search/" ) {
var rawQuery = getAllUrlParams().q;
// strip + delimeters from query
var query = stripDelimeters(rawQuery);
//var query = rawQuery.replace("+"," ");
var searchresults__count = document.getElementById("searchresults__count");
var searchresults__resultslist = document.getElementById("searchresults__resultslist");
var searchresults__query = document.getElementById("searchresults__query");
var resultsObj = new Object();
var htmlstring = "";
function reqListener() {
var obj = JSON.parse(this.responseText);
var index = lunr.Index.load(obj);
var searchresults_json = index.search(specialCombos(query), {});
if (searchresults_json.length > 0) {
resultsObj = searchresults_json;
} else { //fuzzy search now
searchresults_json = index.search(specialCombos(query) + "~1", {});
if (searchresults_json.length > 0) {
resultsObj = searchresults_json;
} else {
searchresults_json = index.search(specialCombos(query) + "~2", {});
resultsObj = searchresults_json;
}
}
if (resultsObj.length == 0){
searchresults__count.innerHTML = "No";
}
else {
searchresults__count.innerHTML = resultsObj.length;
}
searchresults__query.innerHTML = "<strong>" + query + "</strong>";
//console.log(JSON.stringify(searchresults_json));
// fetch the path map to lookup title and form the link
var load_pathmap = new XMLHttpRequest();
load_pathmap.onload = pmListener;
load_pathmap.onerror = reqError;
load_pathmap.open('get', '../pathmap.json', true);
load_pathmap.send();
}
function pmListener() {
var documentsjson = JSON.parse(this.responseText);
var resultcount = 0;
// form the results list
resultsObj.forEach (function (result) {
resultcount ++;
// lookup the title
var pagetitle = "";
var pagedescription = "";
var url = "";
for (var i = 0; i < documentsjson.length; i++ ) {
if (documentsjson[i].id == result.ref) {
pagetitle = documentsjson[i].title;
pagedescription = documentsjson[i].description;
url = documentsjson[i].path;
continue;
}
}
// form the HTML list result item
var rel = "";
if (url.substring(0,1) == "h") {
rel = "rel='external'";
}
htmlstring = htmlstring + "<li><h3><a " + rel + "href='" + url +"'>" + pagetitle + "</a></h3><p>" + pagedescription + "</p></li>";
});
searchresults__resultslist.innerHTML = htmlstring;
}
function reqError(err) {
console.log('Fetch Error :-S', err);
}
var load_index = new XMLHttpRequest();
load_index.onload = reqListener;
load_index.onerror = reqError;
load_index.open('get', '../search_index.json', true);
load_index.send();
}
| JavaScript | 0.000004 | @@ -2304,56 +2304,8 @@
) %7B%0A
-%09// query = %22keywords:product keywords:manager%22;
%0A%09va
|
c21bb763e20b48f0eccf0f9205de7e1bb10ad41d | add few more tests | test.js | test.js | /*!
* is-number <https://github.com/jonschlinkert/is-number>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
/* deps: mocha */
var assert = require('assert');
var isNumber = require('./');
var shouldPass = [
0xff,
5e3,
0,
-1.1,
37,
3.14,
1,
1.1,
10,
10.10,
100,
-100,
'-1.1',
'0',
'012',
'0xff',
'1',
'1.1',
'10',
'10.10',
'100',
'5e3',
Math.LN2,
Number(1),
new Number(1),
// 012, Octal literal not allowed in strict mode
parseInt('012'),
parseFloat('012'),
Math.abs(1),
Math.acos(1),
Math.asin(1),
Math.atan(1),
Math.atan2(1, 2),
Math.ceil(1),
Math.cos(1),
Math.E,
Math.exp(1),
Math.floor(1),
Math.LN10,
Math.LN2,
Math.log(1),
Math.LOG10E,
Math.LOG2E,
Math.max(1, 2),
Math.min(1, 2),
Math.PI,
Math.pow(1, 2),
Math.pow(5, 5),
Math.random(1),
Math.round(1),
Math.sin(1),
Math.sqrt(1),
Math.SQRT1_2,
Math.SQRT2,
Math.tan(1),
Number.MAX_VALUE,
Number.MIN_VALUE,
'0.0',
'0x0',
'0e+5',
'000',
'0.0e-5',
'0.0E5',
+'',
+1,
+3.14,
+37,
+5,
+[],
+Boolean(true),
+false,
+Math.LN2,
+String(100),
+true,
+null,
+Number(1),
+new Array(''),
+new Array(0),
+new Boolean(true),
+new Buffer(''),
+new Date,
+new Date(),
+new Number(1),
];
var shouldFail = [
'',
'3a',
'abc',
'false',
'null',
'true',
'undefined',
+'abc',
+/foo/,
+[1, 2, 4],
+function () {},
+function() {},
+function(){},
+Infinity,
+Math.sin,
+NaN,
+new Array('abc'),
+new Array(2),
+new RegExp('foo'),
+new String("abc"),
+String('foo'),
+undefined,
+{a:1},
+{},
// Symbol('foo'),
// Symbol(),
// Symbol.iterator,
/foo/,
[1, 2, 3],
[1],
[],
Boolean(true),
false,
function () {},
function() {},
function(){},
Infinity,
Math.sin,
NaN,
new Array(''),
new Array('abc'),
new Array(0),
new Boolean(true),
new Buffer(''),
new Buffer('abc'),
new Date(),
new RegExp('foo'),
new String("abc"),
null,
String("abc"),
true,
undefined,
{a:1},
{abc: 'abc'},
{},
];
describe('is a number', function () {
shouldPass.forEach(function (num) {
it('"' + JSON.stringify(num) + '" should be a number', function () {
assert.equal(isNumber(num), true);
});
});
});
describe('is not a number', function () {
shouldFail.forEach(function (num) {
it('"' + JSON.stringify(num) + '" should not be a number', function () {
assert.equal(isNumber(num), false);
});
});
});
| JavaScript | 0 | @@ -277,16 +277,31 @@
3,%0A 0,%0A
+ 0.1,%0A -0.1,%0A
-1.1,%0A
@@ -358,16 +358,35 @@
-100,%0A%0A
+ '0.1',%0A '-0.1',%0A
'-1.1'
|
a4f2dc209dd373185c697d7f7825626bcf3191a5 | Add .package to interface test | test.js | test.js | var doTest = require ('./');
var testsDone = 0;
// Tests
doTest.add ('Module interface', function () {
var test = doTest.test ();
test
.isObject ('fail', 'exports', doTest)
.isFunction ('fail', '.config', doTest.config)
.isFunction ('fail', '.add', doTest.add)
.isFunction ('fail', '.run', doTest.run)
.isFunction ('fail', '.log', doTest.log)
.isFunction ('fail', '.exit', doTest.exit)
.isFunction ('fail', '.onExit', doTest.onExit)
.isFunction ('fail', '.colorStr', doTest.colorStr)
.isFunction ('fail', '.getType', doTest.getType)
.isFunction ('fail', '.test', doTest.test)
.isFunction ('fail', '.test.done', test.done)
.isFunction ('fail', '.test.good', test.good)
.isFunction ('fail', '.test.warn', test.warn)
.isFunction ('fail', '.test.fail', test.fail)
.isFunction ('fail', '.test.error', test.error)
.isFunction ('fail', '.test.info', test.info)
.isFunction ('fail', '.test.exit', test.exit)
.done ();
testsDone++;
});
doTest.add ('.config()', function (test) {
var arg = doTest.config ('first', true);
var obj;
test ()
.isObject ('fail', 'argument return', arg)
.isExactly ('fail', 'argument first', arg && arg.first, true);
obj = doTest.config ({
second: true
});
test ()
.isObject ('fail', 'object return', obj)
.isExactly ('fail', 'object first', obj && obj.first, true)
.isExactly ('fail', 'object second', obj && obj.second, true)
.done ();
testsDone++;
});
doTest.add ('test() shortcut', function (test) {
doTest.test ()
.isFunction ('fail', 'test', test)
.isObject ('fail', 'test() return', test ())
.done ();
testsDone++;
});
doTest.add ('test() .info()', function (test) {
doTest.test ()
.info ('-- Short object:')
.info ({ hello: 'world' })
.info ('-- Long object:')
.info (test ())
.info ('-- Short array:')
.info (['one', 'two'])
.info ('-- Long array:')
.info (process.mainModule.paths)
.done ();
testsDone++;
});
doTest.add ('Methods', function (test, fake) {
var colorTest = doTest.colorStr ('magenta', 'magenta');
var colorMatch = '\u001b[35mmagenta\u001b[0m';
doTest.log ('.log() This is a plain (default) message');
doTest.log ('.log() This is a plain (preset) message');
/* eslint-disable no-undefined */
doTest.test ()
.info ('.length: ' + doTest.length)
.isError ('fail', 'test() .isError', new Error ())
.isObject ('fail', 'test() .isObject', {})
.isArray ('fail', 'test() .isArray', [])
.isString ('fail', 'test() .isString', 'hello')
.isNumber ('fail', 'test() .isNumber', 1)
.isUndefined ('fail', 'test() .isUndefined', fake)
.isNull ('fail', 'test() .isNull', null)
.isNaN ('fail', 'test() .isNaN', NaN)
.isBoolean ('fail', 'test() .isBoolean', true)
.isFunction ('fail', 'test() .isFunction', function () {})
.isDate ('fail', 'test() .isDate', new Date ())
.isExactly ('fail', 'test() .isExactly', ':)', ':)')
.isNot ('fail', 'test() .isNot', 'a', 'b')
.isRegexp ('fail', 'test() .isRegexp', /^\w$/)
.isRegexpMatch ('fail', 'test() .isRegexpMatch', 'a', /^\w$/)
.isCondition ('fail', 'test() .isCondition <', 1, '<', 2)
.isCondition ('fail', 'test() .isCondition >', 2, '>', 1)
.isCondition ('fail', 'test() .isCondition <=', 1, '<=', 2)
.isCondition ('fail', 'test() .isCondition >=', 2, '>=', 2)
.isCondition ('warn', 'test() .isCondition invalid', 1, '', 2)
.isEmpty ('fail', 'test() .isEmpty undefined', undefined)
.isEmpty ('fail', 'test() .isEmpty null', null)
.isEmpty ('fail', 'test() .isEmpty string', '')
.isEmpty ('fail', 'test() .isEmpty object', {})
.isEmpty ('fail', 'test() .isEmpty array', [])
.isEmpty ('fail', 'test() .isEmpty error', new Error ())
.isNotEmpty ('fail', 'test() .isNotEmpty undefined', 1)
.isNotEmpty ('fail', 'test() .isNotEmpty null', 1)
.isNotEmpty ('fail', 'test() .isNotEmpty string', '1')
.isNotEmpty ('fail', 'test() .isNotEmpty object', { hi: 'you' })
.isNotEmpty ('fail', 'test() .isNotEmpty array', ['yay'])
.isNotEmpty ('fail', 'test() .isNotEmpty error', new Error ('test error'))
.info ('Warnings for coverage:')
.isNotEmpty ('warn', 'test() .isNotEmpty undefined', undefined)
.isNotEmpty ('warn', 'test() .isNotEmpty null', null)
.isNotEmpty ('warn', 'test() .isNotEmpty string', '')
.isNotEmpty ('warn', 'test() .isNotEmpty object', {})
.isNotEmpty ('warn', 'test() .isNotEmpty array', [])
.isNotEmpty ('warn', 'test() .isNotEmpty error', new Error ())
.isExactly ('fail', '.getType', doTest.getType ([]), 'array')
.isExactly ('fail', '.colorStr', colorTest, colorMatch)
.isEmpty ('warn', 'output() warn', 'test warning')
.warn ('This is a warn message')
.good ('This is a good message')
.done (function () {
doTest.log ('info', 'test() .done() callback');
});
/* eslint-enable no-undefined */
testsDone++;
});
doTest.add ('All tests done', function (test) {
testsDone++;
test ()
.isExactly ('fail', 'testsDone', testsDone, doTest.length)
.done ();
});
doTest.run (1);
| JavaScript | 0.000001 | @@ -174,24 +174,75 @@
s', doTest)%0A
+ .isObject ('fail', '.package', doTest.package)%0A
.isFunct
|
04080254cb8d8e68f680731ce821d2662ca896fb | update prompt / question | fstimizely.js | fstimizely.js | #! /usr/bin/env node
var UPLOAD = process.argv[2] === 'up';
var Optimizely = require('./lib/optimizely');
var fs = require('fs');
var slug = require('slug');
var git = require('git-promise');
var gitUtil = require('git-promise/util');
require('colors');
/**
* Token API for multiple projects
* cat ~/.fstimizelyrc # {'tokens': {'$name':'$token'}}
* cat ./.fstimizelyrc # {'$name':'$experiment_id'}
*
* note: overarchitected for prep to move to account level sync
*/
var API_TOKEN, EXPERIMENT_ID; // ewww
(function () {
var conf = require('rc')('fstimizely', {});
if (!conf.tokens) throw new Error('.fstimizelyrc requires tokens object');
Object.keys(conf).forEach(function (key) {
if (['_', 'config', 'tokens'].indexOf(key) === -1) {
API_TOKEN = conf.tokens[key];
EXPERIMENT_ID = conf[key];
}
});
if (!API_TOKEN) throw new Error('.fstimizelyrc api_token missing');
if (!EXPERIMENT_ID) throw new Error('.fstimizelyrc experiment_id missing');
})();
var optimizely = new Optimizely(API_TOKEN);
/**
* Avoid losing non-commited changes by failing unless
* you're on a clean git tree
*/
git('status --porcelain', gitUtil.extractStatus)
.then(function (status) {
var err;
['modified', 'added', 'deleted', 'renamed', 'copied'].forEach(function (b) {
if (status.workingTree[b].length) {
err = 'dirty git tree - please stash/commit first';
console.error(err.red);
throw err;
}
});
return true;
}).then(function () { // Yay now we can run!
// globaljs and css
optimizely.getExperiment(EXPERIMENT_ID)
.then(function (experiment) {
writeOrUpload(experiment, 'experiments/' + experiment.id, 'global.js', 'custom_js');
writeOrUpload(experiment, 'experiments/' + experiment.id, 'global.css', 'custom_css');
});
// variation js
optimizely.getVariations(EXPERIMENT_ID)
.then(function (variations) {
variations.forEach(function (variation) {
writeOrUpload(variation, 'variations/' + variation.id,
slug(variation.description).toLowerCase() + '.js', 'js_component');
});
});
});
/*jshint latedef:false*/
/**
* Write or Upload files based on upload/download state
* @param {object} obj object in question
* @param {string} url url endpoint
* @param {string} fileName filename in question
* @param {string} key key on object to check
*/
function writeOrUpload(obj, url, fileName, key) {
fs.readFile(fileName, function (err, data) {
// if in upload mode, confirm then
// modify put {`key`: `fsText`} to `url`
if (UPLOAD) {
if (err) return;
data = data.toString(); // idk
if (isDifferent(fileName, obj[key], data)) {
if (getAnswer('Upload diff to ' + fileName)) { // sync / needs to be nested
var stingy = {};
stingy[key] = data;
optimizely.put(url, stingy).then(function () {
console.log('Uploaded to: https://www.optimizely.com/edit?experiment_id=' + EXPERIMENT_ID);
});
}
}
} else {
// Print diff of obj[key] and fileText & write file
if (err) data = '';
if (isDifferent(fileName, data.toString(), obj[key])) {
fs.writeFile(fileName, obj[key]);
}
}
});
}
/**
* Prints a diff
* @param {string} name name of diff
* @param {string} start base to diff
* @param {string} end base to compare
* @return {Boolean} start != end
*/
function isDifferent(name, start, end) {
var jsdiff = require('diff');
console.log(('\nDIFF: ' + name + ' ->').blue);
var diff = jsdiff.diffLines(start, end);
var lastLine; // force newline print on lastLine
diff.forEach(function (part) {
var color = part.added ? 'green' :
part.removed ? 'red' : 'grey';
process.stderr.write(part.value[color]);
lastLine = part;
});
if (!lastLine.value.match(/\n$/)) console.log('\n');
return start != end; // jshint ignore:line
}
/**
* prompt for an answer
* @param {string} q question to ask [y/N]?
* @return {Boolean} answer
*/
function getAnswer(q) {
var prompt = require('readline-sync').question;
var yesNo = require('yes-no').parse;
var a = prompt(q + '? [y/N]: ');
if (a === '') a = false;
else a = yesNo(a);
return a;
}
| JavaScript | 0.000111 | @@ -3956,24 +3956,25 @@
urn start !=
+=
end; // jsh
@@ -4119,24 +4119,47 @@
Answer(q) %7B%0A
+ console.log('here');%0A
var prompt
@@ -4189,17 +4189,8 @@
nc')
-.question
;%0A
@@ -4226,16 +4226,16 @@
.parse;%0A
-
var a
@@ -4242,16 +4242,25 @@
= prompt
+.question
(q + '?
|
60267a2d2a01b39410f20c8953f6b71430d4d6ed | fix example not using mocks (#445) | packages/data-point/examples/reducer-entity-instance.js | packages/data-point/examples/reducer-entity-instance.js | const assert = require("assert");
const DataPoint = require("../");
const { Model, Request } = DataPoint;
const PersonRequest = Request("PersonRequest", {
url: "https://swapi.co/api/people/{value}"
});
const PersonModel = Model("PersonModel", {
value: {
name: "$name",
birthYear: "$birth_year"
}
});
const dataPoint = DataPoint.create();
dataPoint.resolve([PersonRequest, PersonModel], 1).then(output => {
assert.deepStrictEqual(output, {
name: "Luke Skywalker",
birthYear: "19BBY"
});
});
| JavaScript | 0 | @@ -102,16 +102,97 @@
Point;%0A%0A
+const mocks = require(%22./async-example.mocks%22);%0A%0A// mock request calls%0Amocks();%0A%0A
const Pe
@@ -275,16 +275,17 @@
/%7Bvalue%7D
+/
%22%0A%7D);%0A%0Ac
|
6ddb22900275b3c8d3adf9840dad0be002a99d27 | fix init method | src/core/plugin.js | src/core/plugin.js | 'use strict';
const EventEmittable = require('./eventemittable');
const Unique = require('./unique');
const Promise = require('bluebird');
const ParamValidator = require('./param-validator');
const errorist = require('errorist');
const validator = ParamValidator.validator;
const {DepGraph} = require('dependency-graph');
const each = require('lodash/collection/each');
const customError = require('../util/custom-error');
const PluginError = customError('PluginError');
const Plugin = ParamValidator
.stampName('Plugin')
.compose(Unique)
.static({
PluginError
})
.validate({
init() {
const originalFunc = this.func;
this.func = Promise.method(this.func);
const depGraph = this.depGraph = this.depGraph || new DepGraph();
const name = this.name;
depGraph.addNode(name);
each([].concat(this.dependencies || []), dep => {
try {
depGraph.addDependency(name, dep);
} catch (ignored) {
throw PluginError(`Cannot find dependency "${dep}" needed by ` +
`plugin "${name}"`);
}
});
Object.defineProperty(this, 'originalFunc', {
value: originalFunc,
writable: false,
configurable: true
});
}
}, {
init: [
validator.object({
instance: validator.object({
name: validator.string()
.required()
.label('name')
.description('Plugin name'),
func: validator.func()
.required()
.label('func')
.description('Plugin function'),
dependencies: validator.array()
.items(validator.string())
.single(true)
.label('dependencies')
.description('Plugin dependencies'),
api: validator.object()
.required()
.label('api')
.description('API object which each plugin will have access to')
})
.unknown(true)
.label('context')
.description('Stampit init context')
})
]
})
.methods({
load() {
return this.func(this.api)
.catch(err => {
throw errorist(err);
})
.tap(() => this.emit('loaded', {
name: this.name
}));
}
})
.compose(EventEmittable, Unique);
module.exports = Plugin;
| JavaScript | 0.000096 | @@ -1949,104 +1949,124 @@
.
-unknown(true)%0A .label('context')%0A .description('Stampit init context')%0A %7D
+label('instance')%0A .unknown(true)%0A .description('Stampit instance')%0A %7D)%0A .unknown(true
)%0A
|
2601c94c7a30f2f127daf3d09d876524605a2992 | update script | js/script.js | js/script.js | jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();jQuery('.article-body iframe').remove();jQuery('.article-body script').remove();jQuery('#main').css('overflow', 'hidden'); | JavaScript | 0.000001 | @@ -138,14 +138,20 @@
ody
-script
+.adsbygoogle
').r
|
c07af02a3c872b2ce90da9700754ffd7e2d2c058 | add stop timer logic | js/script.js | js/script.js | // Declare global variables
var mainTimer = document.getElementById("startTimer");
var timerState = document.getElementById("displayTimer");
var breakState = document.getElementById("displayBreak");
var count = parseInt(document.getElementById("displayTimer").innerHTML);
var breakCount = parseInt(document.getElementById("displayBreak").innerHTML);
var alertSound = document.getElementById("alertsound");
var timerAdd = document.getElementById("timerAdd");
var timerSubtract = document.getElementById("timerSubtract");
var breakAdd = document.getElementById("breakAdd");
var breakSubtract = document.getElementById("breakSubtract");
var clickCount = 0;
// Event handler for user clicks on main timer
mainTimer.addEventListener("click", activateTimer);
// Start timer and decrement down
function activateTimer(event) {
if (timerState.style.zIndex == "-1") {
timerState.style.zIndex = "1";
breakState.style.zIndex = "1";
clickCount++;
var counter = setInterval(timer, 1000);
if (clickCount <= 1) {
count *= 60;
}
// Format timer to minutes and seconds
function timer() {
count -= 1;
if (count === 0) {
alertSound.play();
clearInterval(counter);
var breakCounter = setInterval(breakTimer);
}
timerState.innerHTML = count;
if (Math.floor(count / 60) > 10) {
if (count % 60 >= 10) {
timerState.innerHTML = Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + "0" + count % 60;
}
} else {
if (count % 60 >= 10) {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + count % 60;
} else {
timerState.innerHTML =
"0" + Math.floor(count / 60) + ":" + "0" + count % 60;
}
}
// Format break timer to minutes and seconds
function breakTimer() {}
}
} else {
timerState.style.zIndex = "-1";
breakState.style.zIndex = "-1";
}
event.preventDefault();
}
// Event handlers for incrementing idle timer
timerAdd.addEventListener("click", function(event) {
count += 1;
if (count < 10) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
event.preventDefault();
});
// Event handlers for decrementing idle timer
timerSubtract.addEventListener("click", function(event) {
if (count > 1) {
count -= 1;
}
if (count >= 10) {
timerState.innerHTML = timerState.innerHTML = count + ":00";
}
if (count < 10 && count > 0) {
timerState.innerHTML = timerState.innerHTML = "0" + count + ":00";
}
event.preventDefault();
});
// Event handler for incrementing idle break timer
breakAdd.addEventListener("click", function(event) {
breakCount += 1;
breakState.innerHTML = breakCount;
event.preventDefault();
});
// Event handler for decrementing idle break timer
breakSubtract.addEventListener("click", function(event) {
if (breakCount > 0) {
breakCount -= 1;
breakState.innerHTML = breakCount;
}
event.preventDefault();
});
| JavaScript | 0.000001 | @@ -1104,24 +1104,70 @@
n timer() %7B%0A
+ if (timerState.style.zIndex == %221%22) %7B%0A
count
@@ -1168,24 +1168,26 @@
count -= 1;%0A
+
if (co
@@ -1207,16 +1207,18 @@
+
alertSou
@@ -1228,16 +1228,18 @@
play();%0A
+
@@ -1266,24 +1266,26 @@
r);%0A
+
+
var breakCou
@@ -1322,24 +1322,26 @@
;%0A
+
%7D%0A
timerSta
@@ -1328,24 +1328,26 @@
%7D%0A
+
+
timerState.i
@@ -1364,16 +1364,18 @@
count;%0A
+
if
@@ -1403,24 +1403,26 @@
60) %3E 10) %7B%0A
+
if (
@@ -1443,32 +1443,34 @@
10) %7B%0A
+
timerState.inner
@@ -1519,32 +1519,34 @@
t %25 60;%0A
+
%7D else %7B%0A
@@ -1540,32 +1540,34 @@
lse %7B%0A
+
+
timerState.inner
@@ -1577,37 +1577,33 @@
L =%0A
-%220%22 +
+
Math.floor(coun
@@ -1640,26 +1640,30 @@
60;%0A
-%7D%0A
+ %7D%0A
%7D else
@@ -1665,32 +1665,34 @@
else %7B%0A
+
if (count %25 60 %3E
@@ -1701,32 +1701,34 @@
10) %7B%0A
+
timerState.inner
@@ -1738,32 +1738,34 @@
L =%0A
+
+
%220%22 + Math.floor
@@ -1797,32 +1797,34 @@
t %25 60;%0A
+
%7D else %7B%0A
@@ -1808,32 +1808,34 @@
%7D else %7B%0A
+
timerS
@@ -1855,32 +1855,34 @@
L =%0A
+
%220%22 + Math.floor
@@ -1928,24 +1928,26 @@
+
%7D%0A
%7D%0A%0A
@@ -1934,27 +1934,31 @@
%7D%0A
+
+
%7D%0A%0A
+
// For
@@ -1998,24 +1998,26 @@
conds%0A
+
+
function bre
@@ -2033,18 +2033,16 @@
%7B%7D%0A
-%7D%0A
%7D else
@@ -2040,24 +2040,60 @@
%7D else %7B%0A
+ clearInterval(counter);%0A
timerSta
@@ -2112,24 +2112,28 @@
dex = %22-1%22;%0A
+
breakSta
@@ -2156,16 +2156,30 @@
= %22-1%22;%0A
+ %7D%0A %7D%0A
%7D%0A ev
|
846133bc34f008f0d4ecc64e7b0f0080571aaed2 | Fix for occasional instangram api bug | js/script.js | js/script.js | // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller, fixes from Paul Irish and Tino Zijdel
(function() {
"use strict";
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
})();
// Helix
$(function() {
"use strict";
// Prevent vertical bounce on iPad
$(document).on('touchmove', function(event) {
if (!event.originalEvent.elementIsScrollable) {
event.preventDefault();
}
});
function HelixNode() {
// Create node element
this.$el = $('<div class="node"></div>');
// Create image element and append to node
this.image = $('<img draggable="false">').hide().appendTo(this.$el);
// Firefox fix: prevents mousemove events being eaten by image dragging
this.image.on('mousedown', function(event) {
event.preventDefault();
});
// Fade in image after it's loaded
this.image.load(function() {
$(this).fadeIn();
});
}
HelixNode.prototype.setImage = function(url) {
this.image.attr('src', url);
};
var main = $('#main');
// Firefox fix: -moz-perspective-origin doesn't like the default browser value of 50% 50%
// so we set it explicitly in pixels
main.css({'-moz-perspective-origin': main.width() / 2 + 'px ' + main.height() / 2 + 'px'});
// The number of nodes and waves is dependent on the width of the browser window
var WIDTH = main.width(),
HEIGHT = main.height(),
ARMS = 2,
NODES_PER_ARM = Math.floor(WIDTH / 55),
HELIX_Y = HEIGHT / 2,
HELIX_SIZE = 110,
CAMERA_ZOOM = 145,
HELIX_WAVES = Math.round(WIDTH / 350),
X_STEP = WIDTH / NODES_PER_ARM;
var nodes = [],
prevMouseX = NaN,
momentumX = 0,
isMouseDown = false;
// Create and attach node elements for each arm
// The nodes for both arms are stored sequentially in the same array
// We use modulo to find the node's index for each arm
for (var i = 0; i < NODES_PER_ARM * ARMS; i++) {
var node = new HelixNode();
node.x = (i % NODES_PER_ARM) * X_STEP;
nodes.push(node);
main.append(node.$el);
}
// Handle mousedown and touchdown for flinging the helix left/right
main.on('mousedown touchstart', function(event) {
isMouseDown = true;
// Check for touches in the case of mobile safari
if (event.originalEvent.touches) {
prevMouseX = event.originalEvent.touches[0].pageX;
} else {
prevMouseX = event.clientX;
}
});
main.on('mousemove touchmove', function(event) {
if (isMouseDown) {
// Add momentum based on how far the mouse was dragged since the last frame
var diffX;
if (event.originalEvent.touches) {
diffX = event.originalEvent.touches[0].pageX - prevMouseX;
prevMouseX = event.originalEvent.touches[0].pageX;
} else {
diffX = event.clientX - prevMouseX;
prevMouseX = event.clientX;
}
momentumX += diffX * 0.01;
}
});
// Handle mouseup both inside and outside the browser by using window
$(window).on('mouseup touchend', function(event) {
isMouseDown = false;
});
function renderFrame() {
// Apply friction
momentumX *= 0.97;
for (var i = 0; i < nodes.length; i++) {
var arm = Math.floor(i / NODES_PER_ARM);
// Rotate the second arm opposite the first in 3D space
var offset = arm * Math.PI;
var node = nodes[i];
node.x += momentumX + 0.5;
// Recycle nodes
if (node.x > WIDTH) {
node.x = 0 + (node.x % WIDTH);
} else if (node.x < 0) {
node.x = WIDTH + (node.x % WIDTH);
}
// Calculate node position
var x = node.x;
var pos = x / WIDTH * Math.PI * HELIX_WAVES; // Position along the wave
var y = Math.sin(pos + offset) * HELIX_SIZE + HELIX_Y;
var z = Math.cos(pos - offset) * HELIX_SIZE + CAMERA_ZOOM;
var rx = -pos;
var rz = (arm === 0) ? -45 : -135; // Rotate nodes correctly for each arm
var opacity = Math.cos(pos - offset) + 1.3; // Fade nodes further away
node.$el.css({
transform: 'translate3d('+x+'px,'+y+'px,'+z+'px) ' + 'rotateX('+rx+'rad) ' + 'rotateZ('+rz+'deg)',
opacity: opacity
});
}
window.requestAnimationFrame(renderFrame);
}
// Start helix
window.requestAnimationFrame(renderFrame);
// Load list of Instagram images
$.ajax({
url: 'https://api.instagram.com/v1/media/popular?client_id=8639987a855746bd851bac3613887866',
dataType: 'jsonp',
success: function(data) {
// Prepare flat array of image urls
var images = [];
for (var i = 0; i < data.data.length; i++) {
images.push(data.data[i].images.thumbnail.url);
}
// Set image on each helix node, wrap if necessary
for (i = 0; i < nodes.length; i++) {
nodes[i].setImage(images[i % images.length]);
}
}
});
});
| JavaScript | 0 | @@ -5222,24 +5222,113 @@
gth; i++) %7B%0A
+%09%09%09%09// A bug in the api occasionally means the url is returned on the thumbnail property%0A
%09%09%09%09images.p
@@ -5364,16 +5364,49 @@
nail.url
+ %7C%7C data.data%5Bi%5D.images.thumbnail
);%0A%09%09%09%7D%0A
|
d4c2050662bcaf878d4e12bda96beb2eb3584125 | Update componentsDirective | angular/directives/componentsDirective.js | angular/directives/componentsDirective.js | (function() {
'use strict';
/**
* @ngdoc directive
* @name app
*
* @description
* _Please update the description and restriction._
*
* @restrict A
* */
angular.module('components.directives').directive('componentsDirective', function() {
return {
restrict: 'A',
link : function(scope, elem, attr) {
}
};
});
})(); | JavaScript | 0 | @@ -114,16 +114,9 @@
* _
-Please u
+U
pdat
@@ -264,16 +264,17 @@
ctive',
+%5B
function
@@ -405,16 +405,17 @@
%7D;%0A %7D
+%5D
);%0A%7D)();
|
1b42aa05260069c1965f016dc94840cc8c3226e7 | fix whoami | scripts/eastereggs.js | scripts/eastereggs.js | module.exports = function(robot){
var thankYouResponses = [
"You're welcome!",
"No problem."
];
robot.hear(/(thanks|thank you) bocbot/i, function(res){
var index = Math.floor(Math.random() * thankYouResponses.length);
res.reply(thankYouResponses[index]);
});
robot.hear(/I like pie/i, function(res){
robot.send('I like pie too');
});
robot.respond(/open (.*) door/i, function(res){
var doorType = res.match[1];
if (doorType == 'pod bay')
res.reply("I'm afraid I can't let you do that.");
else
res.reply('Opening ' + doorType + ' doors.');
});
robot.respond(/(you are|you're)(.*) slow/i, function(res){
setTimeout(function(){
res.reply('Who you callin\' slow?');
}, 1000 * 15);
});
robot.respond(/(have|drink|consume)(.*) beer/i, function(res){
var beersHad = robot.brain.get('totalBeersHad') || 0;
if (beersHad > 4){
var lastBeerFrom = robot.brain.get('lastBeerFrom');
res.reply("I think I've had too many. " + lastBeerFrom + " got me too drunk. I need to sleep it off first.");
}
else{
res.reply("Sure thing! _chugs beer_");
robot.brain.set('totalBeersHad', beersHad + 1);
robot.brain.set('lastBeerFrom', res.message.user.name);
}
});
robot.respond(/sleep it off/i, function(res){
robot.brain.set('totalBeersHad', 0);
res.reply('zzzzz');
});
robot.respond(/who am i/, function(res){
res.sendPrivate(res.message.user.name);
});
} | JavaScript | 0.000015 | @@ -1367,23 +1367,64 @@
%7B%0A%09%09
-res.sendPrivate
+if (robot.auth.isAdmin(res.message.user))%0A%09%09%09res.respond
(res
|
166e2e7881707c45f5ea7022ea1dd61665093848 | Update script.js | js/script.js | js/script.js | (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var width = 512;
var height = 288;
var blockSize = 16;
document.getElementById("startbtn").onclick = paintscreen;
//paint a block
function paintblock(x, y) {
for(var i = 0; i < blockSize; i++) {
for(var j = 0; j< blockSize; j++) {
if(i == 0 || i == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(i*x, j*y, 1, 1);
}
if(j == 0 || j == blockSize -1){
c.fillStyle = "#000000";
c.fillRect(i*x, j*y, 1, 1);
}
}
}
}
//paint the screen
function paintscreen() {
for(var i = 0; i< 32; i++) {
for(var j = 0; j < 18; j++) {
paintblock(i*blockSize, j*blockSize);
}
}
}
}
})(window, document, undefined);
| JavaScript | 0.000002 | @@ -662,32 +662,32 @@
c.fillRect(
-i*x, j*y
+x+i, y+j
, 1, 1);%0A
@@ -846,16 +846,16 @@
ect(
-i*x, j*y
+x+i, y+j
, 1,
|
9222123ab11b5b92f8b10ac74a7149b659b2f8cc | Update app/assets/javascripts/ckeditor/config.js | app/assets/javascripts/ckeditor/config.js | app/assets/javascripts/ckeditor/config.js | /*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
/* Filebrowser routes */
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
// Rails CSRF token
config.filebrowserParams = function(){
var csrf_token, csrf_param, meta,
metas = document.getElementsByTagName('meta'),
params = new Object();
for ( var i = 0 ; i < metas.length ; i++ ){
meta = metas[i];
switch(meta.name) {
case "csrf-token":
csrf_token = meta.content;
break;
case "csrf-param":
csrf_param = meta.content;
break;
default:
continue;
}
}
if (csrf_param !== undefined && csrf_token !== undefined) {
params[csrf_param] = csrf_token;
}
return params;
};
config.addQueryString = function( url, params ){
var queryString = [];
if ( !params ) {
return url;
} else {
for ( var i in params )
queryString.push( i + "=" + encodeURIComponent( params[ i ] ) );
}
return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" );
};
// Integrate Rails CSRF token into file upload dialogs (link, image, attachment and flash)
CKEDITOR.on( 'dialogDefinition', function( ev ){
// Take the dialog name and its definition from the event data.
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var content, upload;
if (CKEDITOR.tools.indexOf(['link', 'image', 'attachment', 'flash'], dialogName) > -1) {
content = (dialogDefinition.getContents('Upload') || dialogDefinition.getContents('upload'));
upload = (content == null ? null : content.get('upload'));
if (upload && upload.filebrowser['params'] == null) {
upload.filebrowser['params'] = config.filebrowserParams();
upload.action = config.addQueryString(upload.action, upload.filebrowser['params']);
}
}
});
};
| JavaScript | 0.000106 | @@ -3195,16 +3195,38 @@
pload &&
+ upload.filebrowser &&
upload.
@@ -3249,21 +3249,27 @@
ams'%5D ==
- null
+= undefined
) %7B%0D%0A
|
6b8befeff80e1ea8ae3cd7401b40a6e1a8703bb1 | Update script.js | js/script.js | js/script.js | var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
(function(window, document, undefined) {
window.onload = init;
function init() {
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var myTimer;
// set the dynamic outside the loop
var dynamic = 10;
//loop function
function loop() {
// change dynamic
dynamic = dynamic * 1.1;
x = dynamic;
y = dynamic * 1.2;
// stop the the animation if it runs out-of-canvas
if (x > canvas.width || y > canvas.height) {
//c.clearRect(0, 0, canvas.width, canvas.height);
clearInterval(myTimer);
}
// clear the canvas for this loop's animation
//c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.arc(x, y, 10, 0, Math.PI * 2, false);
c.fill();
}
$("#startbtn").click(function(){ dynamic=10; myTimer=setInterval(loop,20); });
}
})(window, document, undefined);
| JavaScript | 0.000002 | @@ -583,16 +583,18 @@
+//
dynamic
@@ -662,15 +662,96 @@
amic
- * 1.2;
+;%0A %0A //if we've reached the end, change direction%0A if(x
%0A
|
614dc5f34e7dde8034e0882f63939c0d49fc13a2 | Update script.js | js/script.js | js/script.js | (function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var cwidth = 960;
var cheight = 540;
document.getElementById("paintbtn").onclick = paint;
function reset(){
c.clearRect ( 0 , 0 , canvas.width, canvas.height );
c.beginPath();
}
function createRoom(x, y, pw, ph){
var randw = Math.floor((Math.random() * ((pw/2) - 2 + 1) + 2) );
var randh = Math.floor((Math.random() * ((ph/2) - 2 + 1) + 2) );
//alert(randw + ", " + randh);
return [randw, randh];
}
function paint(){
reset();
var widthSelect = document.getElementById("width");
var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;
var heightSelect = document.getElementById("height");
var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
//alert(pathWidth + ", " + pathHeight);
for(var i = 0; i< pathWidth; i++){
for(var j = 0; j< pathHeight; j++){
c.beginPath();
c.lineWidth = 1;
c.rect(i*30+0.5, j*30+0.5, 30, 30);
c.stroke();
}
}
for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
var randRoom = Math.floor((Math.random() * 19));
if(randRoom < 1){
roomDim = createRoom(i,j,pathWidth,pathHeight);
c.beginPath();
c.lineWidth = 3;
c.rect(i*30 + 0.5, j*30+ 0.5, roomDim[0]*30, roomDim[1]*30);
c.stroke();
}
}
}
}
}
})(window, document, undefined);
| JavaScript | 0.000002 | @@ -1707,17 +1707,16 @@
dom() *
-1
9));%0A
|
ee8efc2d327da8d4b10e94ab274273225bda038a | Support browsers without `console.log` | js/search.js | js/search.js | function Search (url) {
this.reset();
this.url = url;
this.MAXIMUM_ACTIVE_CONNECTIONS = 10;
this.QUEUE_DELAY = 100;
}
Search.prototype.reset = function () {
this.discovered = [];
this.activeConnections = 0;
this.searchQueue = [];
this.nextSearchQueue = [];
this.chains = [];
}
Search.prototype.checkUser = function (user) {
return $.ajax({
url: this.url + user + ".json",
contentType: "application/json",
type: "GET"
});
}
Search.prototype.add = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
// Push the user into the queue so the followers can be found for it
this.searchQueue.push([user, chain]);
}
Search.prototype.addNext = function (user, chain) {
chain = chain ? chain.slice() : [];
this.register(user, chain);
this.nextSearchQueue.push([user, chain]);
}
Search.prototype.register = function (user, chain) {
// Check if the user has already been searched
if (this.hasSearched(user)) {
return;
}
chain.push(user);
// Add the new chain into the existing list of chains
this.chains.push(chain);
this.discovered.push(user);
}
Search.prototype.hasSearched = function (user) {
return (this.discovered.indexOf(user) >= 0);
}
Search.prototype.queueFinished = function () {
// Placeholder method that should be overriden by subclasses
}
/*
Move all users who are in the next search queue to the current search queue
and reset the next search queue.
*/
Search.prototype.shiftQueue = function () {
this.searchQueue = this.nextSearchQueue;
this.nextSearchQueue = [];
}
Search.prototype.processQueue = function () {
// Hold a reference to `this` so we can hold the reference in the timeout
var self = this;
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// If all of the connections are in use, wait a bit until trying to
// process the queue again
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
return;
}
// Fire the finished signal only when there is nothing left in the queue and
// all connections have finished
if (self.searchQueue.length == 0 && self.activeConnections == 0) {
self.queueFinished();
return;
}
// Process the queue until it is empty
while (self.searchQueue.length > 0) {
console.log("Processing queue...");
// Check to see if all of the connections are in use
if (self.activeConnections >= self.MAXIMUM_ACTIVE_CONNECTIONS) {
// Stop trying to process the queue
break;
}
// Pull the first item off the queue
var queueItem = self.searchQueue.splice(0, 1);
// If there is nothing left on the queue, just continue
if (queueItem.length == 0) {
continue;
}
// Process the item from the queue
self.processQueueItem(queueItem[0]);
}
// Once the queue empties, fire it once more to call `queueFinished`
window.setTimeout(function () {
self.processQueue();
}, self.QUEUE_DELAY);
};
Search.prototype.processQueueItem = function (queueItem) {
var self = this;
var user = queueItem[0];
var chain = queueItem[1];
self.activeConnections += 1;
var $request = this.checkUser(user);
$request.then(function (user) {
var users = self.getNextUsers(user);
users.forEach(function (u) {
self.addNext(u, chain);
});
self.activeConnections -= 1;
});
$request.fail(function () {
self.activeConnections -= 1;
});
}
| JavaScript | 0 | @@ -2319,24 +2319,140 @@
ngth %3E 0) %7B%0A
+ // Keep pushing to the console to make sure it didn't stall%0A if (console != null && console.log != null) %7B%0A
console.
@@ -2478,16 +2478,22 @@
ue...%22);
+%0A %7D
%0A%0A //
|
dca094b389a6ae0c3a2d1074ddd4e91349facc23 | create the DummySerial | js/serial.js | js/serial.js | var GameboyJS;
(function (GameboyJS) {
"use strict";
// Handler for the Serial port of the Gameboy
//
// It is designed for debug purposes as some tests output data on the serial port
//
// Will regularly output the received byte (converted to string) in the console logs
// This handler always push the value 0xFF as an input
var ConsoleSerial = {
current: '',
timeout: null,
out: function(data) {
ConsoleSerial.current += String.fromCharCode(data);
if (data == 10) {
ConsoleSerial.print();
} else {
clearTimeout(ConsoleSerial.timeout);
ConsoleSerial.timeout = setTimeout(ConsoleSerial.print, 500);
}
},
in: function(){
return 0xFF;
},
print: function() {
clearTimeout(ConsoleSerial.timeout);
console.log('serial: '+ConsoleSerial.current);
ConsoleSerial.current = '';
}
};
GameboyJS.ConsoleSerial = ConsoleSerial;
}(GameboyJS || (GameboyJS = {})));
| JavaScript | 0.000496 | @@ -57,16 +57,17 @@
Handler
+s
for the
@@ -98,19 +98,62 @@
boy%0A
-//
%0A//
-It is
+The ConsoleSerial is an output-only serial port%0A//
des
@@ -189,16 +189,20 @@
ome test
+ rom
s output
@@ -749,16 +749,17 @@
nction()
+
%7B%0A
@@ -949,16 +949,16 @@
%7D%0A%7D;%0A
-
GameboyJ
@@ -989,16 +989,205 @@
eSerial;
+%0A%0A// A DummySerial outputs nothing and always inputs 0xFF%0Avar DummySerial = %7B%0A out: function() %7B%7D,%0A in: function() %7B%0A return 0xFF;%0A %7D%0A%7D;%0AGameboyJS.DummySerial = DummySerial;
%0A%7D(Gameb
|
5e670a108da092f048697b054aef099ee2e6f42a | Update generate-docs script | scripts/generate-docs.js | scripts/generate-docs.js | #!/usr/bin/env node
'use strict';
(function () {
var fs = require('fs');
var jsdom = require('jsdom');
var docs = require('../docs/docs');
// Jsdom document
var document = jsdom.jsdom(
'<!DOCTYPE html>' +
'<html>' +
'<head>' +
'<meta charset="utf-8">' +
'<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">' +
'<title>Canvasimo</title>' +
'<link rel="stylesheet" href="docs/styles.css" media="screen" title="no title" charset="utf-8">' +
'</head>' +
'<body>' +
'<div id="container" class="container">' +
'<div id="doc-container"></div>' +
'</div>' +
'</body>' +
'</html>'
);
var window = document.defaultView;
var groupNodes = [];
var container = document.getElementById('doc-container');
function insertAfter (newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function createSlug (text) {
return (text || '').toLowerCase().replace(/^\s+/, '').replace(/\s+$/, '').replace(/[\s_]/gi, '-');
}
function createLinkedHeader (type, content) {
var slug = createSlug(content);
var header = document.createElement(type);
header.setAttribute('id', slug);
var link = document.createElement('a');
link.setAttribute('href', '#' + slug);
link.textContent = content;
header.appendChild(link);
return header;
}
function createArguments (args, snippet) {
if (!args || !args.length) {
return;
}
for (var i = 0; i < args.length; i += 1) {
var arg = args[i];
var name = document.createElement('span');
name.setAttribute('class', 'code-argument');
name.textContent = arg.name;
snippet.appendChild(name);
if (arg.type) {
var type = document.createElement('span');
type.setAttribute('class', 'code-type');
type.textContent = ' <' + arg.type + '>';
snippet.appendChild(type);
}
if (arg.optional) {
var optional = document.createElement('span');
optional.setAttribute('class', 'code-optional');
optional.textContent = ' (Optional)';
snippet.appendChild(optional);
}
if (i < args.length - 1) {
var comma = document.createElement('span');
comma.textContent = ', ';
snippet.appendChild(comma);
}
}
}
function createReturns (returns, snippet) {
if (!returns) {
return;
}
var comment = document.createElement('span');
comment.textContent = '\nReturns ';
snippet.appendChild(comment);
var name = document.createElement('span');
name.setAttribute('class', 'code-return');
name.textContent = returns.name;
snippet.appendChild(name);
if (returns.type) {
var type = document.createElement('span');
type.setAttribute('class', 'code-type');
type.textContent = ' <' + returns.type + '>';
snippet.appendChild(type);
}
}
function createSnippet (method) {
var snippet = document.createElement('span');
var instance = document.createElement('span');
instance.setAttribute('class', 'code-object');
instance.textContent = 'canvas';
snippet.appendChild(instance);
var dot = document.createElement('span');
dot.textContent = '.';
snippet.appendChild(dot);
var call = document.createElement('span');
call.setAttribute('class', 'code-property');
call.textContent = method.name;
snippet.appendChild(call);
var openParen = document.createElement('span');
openParen.textContent = '(';
snippet.appendChild(openParen);
createArguments(method.arguments, snippet);
var closeParen = document.createElement('span');
closeParen.textContent = ');';
snippet.appendChild(closeParen);
createReturns(method.returns, snippet);
return snippet;
}
function documentMethod (method) {
var methodNode = document.createElement('div');
methodNode.setAttribute('class', 'method');
var methodName = createLinkedHeader('h3', method.name);
methodNode.appendChild(methodName);
if (method.alias) {
var aliasNode = document.createElement('p');
aliasNode.setAttribute('class', 'alias');
var aliasWord = document.createElement('span');
aliasWord.setAttribute('class', 'alias-word');
aliasWord.textContent = 'Alias: ';
aliasNode.appendChild(aliasWord);
var aliasMethod = document.createElement('strong');
aliasMethod.setAttribute('class', 'alias-method');
aliasMethod.textContent = method.alias;
aliasNode.appendChild(aliasMethod);
methodName.appendChild(aliasNode);
}
var methodDescription = document.createElement('p');
methodDescription.textContent = method.description;
methodNode.appendChild(methodDescription);
var snippet = document.createElement('pre');
snippet.appendChild(createSnippet(method));
methodNode.appendChild(snippet);
return methodNode;
}
function createGroup (group, index) {
var groupNode = document.createElement('div');
groupNode.setAttribute('class', 'group');
var groupName = createLinkedHeader('h2', group.name);
groupName.setAttribute('class', 'group-header');
groupNode.appendChild(groupName);
for (var i = 0; i < group.methods.length; i += 1) {
groupNode.appendChild(documentMethod(group.methods[i], i));
}
if (index === 0) {
container.insertBefore(groupNode, container.childNodes[0]);
} else {
var hr = document.createElement('hr');
insertAfter(hr, groupNodes[groupNodes.length - 1]);
insertAfter(groupNode, hr);
}
groupNodes.push(groupNode);
}
function createDocumentation () {
for (var i = 0; i < docs.length; i += 1) {
createGroup(docs[i], i);
}
}
createDocumentation();
fs.writeFile('index.html', '<!DOCTYPE html>' + document.documentElement.outerHTML);
console.log('Docs generated!');
})();
| JavaScript | 0 | @@ -448,21 +448,16 @@
%22 href=%22
-docs/
styles.c
@@ -5841,39 +5841,11 @@
%7D%0A
+%0A
-%7D%0A%0A createDocumentation();%0A%0A
fs
@@ -5855,17 +5855,29 @@
iteFile(
-'
+%0A 'docs/
index.ht
@@ -5880,16 +5880,22 @@
x.html',
+%0A
'%3C!DOCT
@@ -5945,43 +5945,199 @@
HTML
-);%0A%0A console.log('Docs generated!'
+,%0A function (error) %7B%0A if (error) %7B%0A console.error(error);%0A %7D else %7B%0A console.log('Docs generated!');%0A %7D%0A %7D%0A );%0A %7D%0A%0A createDocumentation(
);%0A%0A
|
9495a3b19811899337da8f1ceabea434c3685c8f | Update social.js | js/social.js | js/social.js | var social = {
facebook: {
share: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
},
count: function(url) {
var result;
$.get("https://graph.facebook.com/",{id: url},function(data, status){
result = data.share;
});
return result;
}
}
}
| JavaScript | 0.000001 | @@ -175,16 +175,24 @@
%0A%09%09%09%0A%09%09%09
+var s =
$.get(%22h
|
1ed5717d54476c8f599ffea682c2e53ce6f93102 | Update social.js | js/social.js | js/social.js | var social = {
facebook: {
share: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
},
count: function(url, callback) {
$.get("https://graph.facebook.com/",{id: url},function(data, status){
callback(data.share);
});
}
},
reddit: {
process: function(domain, callback) {
$.get("https://api.reddit.com/domain/" + domain,function(data, status){
var results = data.data.children;
var array = new Array();
for(var i = 0; i < results.length; i++) {
var url = results[i].data.url;
var score = results[i].data.score;
var old = array.find(function(v){return v.url === url});
if(typeof old === "undefined") {
var value = {
url: url,
score: score,
count: 1
};
array.push(value);
} else {
old.score = old.score + score;
old.count = old.count + 1;
}
}
callback({
items: array,
count: array.reduce(function(total,current){return total + current.count;},0),
score: array.reduce(function(total,current){return total + current.score;},0),
find: function(url) {
return this.items.find(function(item){return item.url === url})
}
});
});
}
}
}
function intToString(integer) {
if(isNaN(integer) || integer <= 0) {
return "";
} else if(integer < 1000) {
return integer;
} else if(integer < 1000000) {
return Math.round(integer / 1000) + "k";
} else {
return Math.round(integer / 1000000) + "m";
}
}
| JavaScript | 0.000001 | @@ -13,99 +13,106 @@
%7B%0A%09
-facebook: %7B%0A%09%09share: function(url) %7B%0A%09%09%09FB.ui(%7B%0A%09%09%09%09method: 'share',%0A%09%09%09%09href: url%0A%09%09 %09
+linkedin: %7B%0A%09%09process: function(url, callback) %7B%0A%09%09%09$.get(%22https://graph.facebook.com/%22,%7Bid: url
%7D,
-
func
@@ -120,34 +120,86 @@
ion(
-response)%7B%7D);%0A%09%09%7D,%0A%09%09count
+data, status)%7B%0A%09%09%09%09callback(data.count);%0A%09%09%09%7D);%0A%09%09%7D%0A%09%7D,%0A%09facebook: %7B%0A%09%09process
: fu
@@ -254,34 +254,51 @@
facebook.com/%22,%7B
-id
+format: %22json%22, url
: url%7D,function(
|
4ed80aec12ad52cb2f435a38d4d1edd76280c22f | add inline jsdoc to msp-manager | fabric-client/lib/msp/msp-manager.js | fabric-client/lib/msp/msp-manager.js | /**
* Copyright 2017 IBM All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var util = require('util');
var path = require('path');
var grpc = require('grpc');
var MSP = require('./msp.js');
var utils = require('../utils.js');
var idModule = require('./identity.js');
var SigningIdentity = idModule.SigningIdentity;
var Signer = idModule.Signer;
var mspProto = grpc.load(path.join(__dirname, '../protos/msp/mspconfig.proto')).msp;
var identityProto = grpc.load(path.join(__dirname, '../protos/identity.proto')).msp;
var MSPManager = class {
constructor() {
this._msps = {};
}
loadMSPs(mspConfigs) {
var self = this;
if (!mspConfigs || !Array.isArray(mspConfigs))
throw new Error('"mspConfigs" argument must be an array');
mspConfigs.forEach((config) => {
if (typeof config.getType() !== 'number' || config.getType() !== 0)
throw new Error(util.format('MSP Configuration object type not supported: %s', config.getType()));
if (!config.getConfig || !config.getConfig())
throw new Error('MSP Configuration object missing the payload in the "Config" property');
var fabricConfig = mspProto.FabricMSPConfig.decode(config.getConfig());
if (!fabricConfig.getName())
throw new Error('MSP Configuration does not have a name');
// with this method we are only dealing with verifying MSPs, not local MSPs. Local MSPs are instantiated
// from user enrollment materials (see User class). For verifying MSPs the root certificates are always
// required
if (!fabricConfig.getRootCerts())
throw new Error('MSP Configuration does not have any root certificates required for validating signing certificates');
// TODO: for now using application-scope defaults but crypto parameters like key size, hash family
// and digital signature algorithm should be from the config itself
var cs = utils.getCryptoSuite();
var newMSP = new MSP({
rootCerts: fabricConfig.getRootCerts(),
admins: fabricConfig.getAdmins(),
id: fabricConfig.getName(),
cryptoSuite: cs
});
self._msps[fabricConfig.getName()] = newMSP;
});
}
getMSPs() {
return this._msps;
}
/**
* DeserializeIdentity deserializes an identity
* @param {byte[]} serializedIdentity A protobuf-based serialization of an object with
* two fields: mspid and idBytes for certificate PEM bytes
* @returns {Promise} Promise for an {@link Identity} instance
*/
deserializeIdentity(serializedIdentity) {
var sid = identityProto.SerializedIdentity.decode(serializedIdentity);
var mspid = sid.getMspid();
var msp = this._msps[mspid];
if (!msp)
throw new Error(util.format('Failed to locate an MSP instance matching the requested id "%s" in the deserialized identity', mspid));
return msp.deserializeIdentity(serializedIdentity);
}
};
module.exports = MSPManager; | JavaScript | 0 | @@ -1069,72 +1069,859 @@
p;%0A%0A
-var MSPManager = class %7B%0A%09constructor() %7B%0A%09%09this._msps = %7B%7D;%0A%09%7D%0A
+/**%0A * MSPManager is an interface defining a manager of one or more MSPs. This essentially acts%0A * as a mediator to MSP calls and routes MSP related calls to the appropriate MSP. This object%0A * is immutable, it is initialized once and never changed.%0A *%0A * @class%0A */%0Avar MSPManager = class %7B%0A%09constructor() %7B%0A%09%09this._msps = %7B%7D;%0A%09%7D%0A%0A%09/**%0A%09 * Instantiates MSPs for validating identities (like the endorsor in the ProposalResponse). The%0A%09 * MSPs loaded via this method require the CA certificate representing the Certificate%0A%09 * Authority that signed the identities to be validated. They also optionally contain the%0A%09 * certificates for the administrators of the organization that the CA certs represent.%0A%09 *%0A%09 * @param %7Bprotos/msp/mspconfig.proto%7D mspConfigs An array of MSPConfig objects as defined by the%0A%09 * protobuf protos/msp/mspconfig.proto%0A%09 */
%0A%09lo
@@ -3425,16 +3425,104 @@
%7D);%0A%09%7D%0A%0A
+%09/**%0A%09 * Returns the validating MSPs. Note that this does NOT return the local MSP%0A%09 */%0A
%09getMSPs
|
3c28ceeaa9c53466ac404d33c1972e6764208786 | Change refresh interval to 15 seconds | js/tasseo.js | js/tasseo.js | // add our containers
for (var i=0; i<metrics.length; i++) {
$('#main').append('<div id="graph" class="graph' + i + '"><div id="overlay-name" class="overlay-name' + i + '"></div><div id="overlay-number" class="overlay-number' + i + '"></div></div>');
}
var graphs = []; // rickshaw objects
var datum = []; // metric data
var urls = []; // graphite urls
var aliases = []; // alias strings
// build our structures
for (var j=0; j<metrics.length; j++) {
var period = metrics[j].period || 45;
urls[j] = ganglia_url + '/graph.php?cs=-' + encodeURI(period) + '%20min&c=' + encodeURI(metrics[j].clustername) + '&h=' + encodeURI(metrics[j].hostname)
+ '&m=' + encodeURI(metrics[j].metricname) + '&json=1';
aliases[j] = metrics[j].hostname + " " + metrics[j].metricname
datum[j] = [{ x:0, y:0 }];
graphs[j] = new Rickshaw.Graph({
element: document.querySelector('.graph' + j),
width: 350,
height: 90,
interpolation: 'step-after',
series: [{
name: aliases[j],
color: '#afdab1',
data: datum[j]
}]
});
graphs[j].render();
}
// set our last known value at invocation
Rickshaw.Graph.prototype.lastKnownValue = 0;
// refresh the graph
function refreshData() {
for (var k=0; k<graphs.length; k++) {
getData(function(n, values) {
for (var x=0; x<values.length; x++) {
datum[n][x] = values[x];
}
// check our thresholds and update color
var lastValue = datum[n][datum[n].length - 1].y;
var warning = metrics[n].warning;
var critical = metrics[n].critical;
if (critical > warning) {
if (lastValue > critical) {
graphs[n].series[0].color = '#d59295';
} else if (lastValue > warning) {
graphs[n].series[0].color = '#f5cb56';
}
} else {
if (lastValue < critical) {
graphs[n].series[0].color = '#d59295';
} else if (lastValue < warning) {
graphs[n].series[0].color = '#f5cb56';
}
}
}, k);
}
for (var m=0; m<graphs.length; m++) {
// update our graph
graphs[m].update();
if (datum[m][datum[m].length - 1] !== undefined) {
var lastValue = datum[m][datum[m].length - 1].y;
var lastValueDisplay;
if ((typeof lastValue == 'number') && lastValue < 2.0) {
lastValueDisplay = Math.round(lastValue*1000)/1000;
} else {
lastValueDisplay = parseInt(lastValue)
}
$('.overlay-name' + m).text(aliases[m]);
$('.overlay-number' + m).text(lastValueDisplay);
if (metrics[m].unit) {
$('.overlay-number' + m).append('<span class="unit">' + metrics[m].unit + '</span>');
}
} else {
$('.overlay-name' + m).text(aliases[m])
$('.overlay-number' + m).html('<span class="error">NF</span>');
}
}
}
// set our theme
var myTheme = (typeof theme == 'undefined') ? 'default' : theme;
// initial load screen
refreshData();
for (var g=0; g<graphs.length; g++) {
if (myTheme === "dark") {
$('.overlay-number' + g).html('<img src="img/spin-night.gif" />');
} else {
$('.overlay-number' + g).html('<img src="img/spin.gif" />');
}
}
// define our refresh and start interval
var refreshInterval = (typeof refresh == 'undefined') ? 2000 : refresh;
setInterval(refreshData, refreshInterval);
// pull data from graphite
function getData(cb, n) {
var myDatum = [];
$.ajax({
error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
url: urls[n]
}).done(function(d) {
if (d.length > 0) {
myDatum[0] = {
x: d[0].datapoints[0][1],
y: d[0].datapoints[0][0] || graphs[n].lastKnownValue || 0
};
for (var m=1; m<d[0].datapoints.length; m++) {
myDatum[m] = {
x: d[0].datapoints[m][1],
y: d[0].datapoints[m][0] || graphs[n].lastKnownValue
};
if (typeof d[0].datapoints[m][0] === "number") {
graphs[n].lastKnownValue = d[0].datapoints[m][0];
}
}
cb(n, myDatum);
}
});
}
// night mode toggle
function toggleNightMode(opacity) {
$('body').toggleClass('night');
$('div#title h1').toggleClass('night');
$('div#graph svg').css('opacity', opacity);
$('div#overlay-name').toggleClass('night');
$('div#overlay-number').toggleClass('night');
}
// activate night mode from config
if (myTheme === "dark") {
toggleNightMode(0.8);
}
// active night mode by click
$('li.toggle-night a').toggle(function() {
toggleNightMode(0.8);
}, function() {
toggleNightMode(1.0);
});
// toggle number display
$('li.toggle-nonum a').click(function() { $('div#overlay-number').toggleClass('nonum'); });
| JavaScript | 0.00001 | @@ -3235,17 +3235,18 @@
ned') ?
-2
+15
000 : re
|
856780f40f382efb558d161d2e1fc45934689146 | fix object parsing | game/world.js | game/world.js | var Player = require('./player');
var World = module.exports = function World(level, players) {
//Mixin level definitions
for (var key in level) {
this[key] = level[key];
}
this.init();
this.width = this.map_definition.width;
this.height = this.map_definition.height;
this.map = new Array(this.height);
this.tileset = {};
this.players = new Array(this.player_definition.length);
for (var i = 0, imax = this.player_definition.length; i < imax; i += 1) {
this.players[i] = new Player(this.player_definition[i]);
}
for (var i = 0, imax = this.map_definition.height; i < imax; i += 1) {
this.map[i] = new Array(this.map_definition.width);
for (var j = 0, jmax = this.map_definition.width; j < jmax; j += 1) {
this.map[i][j] = new this.map_definition.tileDefinition[i][j]();
this.tileset[this.map[i][j].type] = {
traversable: this.map_definition.tileDefinition[i][j].prototype.traversable
};
}
}
for (var i = 0, imax = this.map_definition.objectDefinition.length; i < imax; i += 1) {
var object_definition = this.map_definition.objectDefinition[i];
this.map[object.x][object.y].object = new object_definition();
}
}
| JavaScript | 0.000067 | @@ -1227,18 +1227,40 @@
ject
-.x%5D%5Bobject
+_definition.x%5D%5Bobject_definition
.y%5D.
@@ -1289,16 +1289,23 @@
finition
+.object
(); %0A
|
255dadb1c03ea3076ba45e6198dac4dfe2839755 | Fix anvil jss suite. | tests/anvil/configSet/Resources/suites/jss.js | tests/anvil/configSet/Resources/suites/jss.js | /*
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
module.exports = new function() {
var finish;
var valueOf;
this.init = function(testUtils) {
finish = testUtils.finish;
valueOf = testUtils.valueOf;
}
this.name = "jss";
this.tests = [
{name: "platform_jss_dirs"}
]
this.platform_jss_dirs = function(testRun) {
var test = Ti.UI.createView({ id: "test" });
valueOf(testRun, test).shouldNotBeNull();
if (Ti.Platform.name == "android") {
valueOf(testRun, test.backgroundColor).shouldBe("red");
} else {
valueOf(testRun, test.backgroundColor).shouldBe("blue");
}
finish(testRun);
}
}
| JavaScript | 0 | @@ -539,16 +539,20 @@
eView(%7B
+%0A%09%09%09
id: %22tes
@@ -557,12 +557,45 @@
est%22
- %7D);
+,%0A%09%09%09backgroundColor: %22blue%22%0A%09%09%7D);%0A%09%09
%0A%09%09v
|
d7dc4dcb3c8daae16e3b625add8d8a4ee96062aa | Allow random to link directly to an image. | keydeerme.js | keydeerme.js | Images = new Mongo.Collection("images");
if (Meteor.isServer) {
Images._ensureIndex( {url: 1}, { unique: true });
Images._ensureIndex( {random: 1} );
}
var PREFER_ORIG = true
function maxResUrl(image) {
url = image.url
if (PREFER_ORIG && _.contains(image.resolutions, null)) {
return url + ".jpg";
}
// May not always be true, but assume default is best
var max = null;
var max_res = null;
_.each(image.resolutions, function(resStr) {
if (resStr) {
res = parseInt(resStr.match(/-[0-9]*/)[0].replace('-', ''));
if (!max || max < res) {
max = res;
max_res = resStr;
}
res = parseInt(resStr.match(/x[0-9]*/)[0].replace('-', ''));
if (!max || max < res) {
max = res;
max_res = resStr;
}
}
});
// We may need to check to see how small max_res is
// and if it is too small use the default if available
if (!max_res) {
return url + ".jpg";
}
return url + max_res;
}
function randomImageIndexed() {
var rand = Math.random();
canidate1 = Images.findOne( {random : { $gte : rand }} );
canidate2 = Images.findOne( {random : { $lte : rand }} );
if (!canidate1 && !canidate2) {
return "";
} else if (!canidate1) {
return maxResUrl(canidate2);
} else if (!canidate2) {
return maxResUrl(canidate1);
}
dif1 = Math.abs(canidate1.random - rand);
dif2 = Math.abs(canidate2.random - rand);
if (dif1 < dif2) {
Images.update({_id:canidate1._id}, {$set: {random: Math.random()}});
return maxResUrl(canidate1);
} else {
Images.update({_id:canidate2._id}, {$set: {random: Math.random()}});
return maxResUrl(canidate2);
}
}
// This is the only way to do it on the client without indexes
// Should compare the two methods
randomImage = function() {
var skip = Math.floor(Images.find().count()*Math.random());
return maxResUrl(Images.findOne({}, {skip: skip, limit:1}));
}
Meteor.methods({
randomImageMethod: function () {
return randomImageIndexed();
}
});
if (Meteor.isServer) {
HTTP.methods({
'api/random': function(data) {
this.setContentType('text/json');
this.addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
this.addHeader("Pragma", "no-cache"); // HTTP 1.0.
this.addHeader("Expires", 0); // Proxies.
return '{ "url":"'+ randomImageIndexed() +'"}';
}
});
}
if (Meteor.isClient) {
Meteor.startup(function() {
// Could save one round trip by loading the background in the first round
// in a hidden field then moving it to the body background
Meteor.call("randomImageMethod", function(error,result) {
if(error) {
return Meteor.settings.default_image;
} else {
$('body').css("background-image", "url("+result+")");
}
});
});
// counter starts at 0
Session.setDefault("counter", 0);
Template.moredeer.helpers({
counter: function () {
return Session.get("counter");
}
});
Template.moredeer.events({
'click button': function () {
/* this is significantly slower
Meteor.call("randomImageMethod", function(error,result) {
if(error){
$('body').css("background-image", "url( "+randomImage()+")");
} else {
$('body').css("background-image", "url("+result+")");
}
});
*/
$('body').css("background-image", "url( "+randomImage()+")");
// increment the counter when button is clicked
Session.set("counter", Session.get("counter") + 1);
}
});
}
| JavaScript | 0 | @@ -2379,16 +2379,392 @@
+'%22%7D';%0A
+%09%7D,%0A%0A%09'api/random.jpg': function(data) %7B%0A%09 this.setContentType('text/html');%0A%09 this.addHeader(%22Cache-Control%22, %22no-cache, no-store, must-revalidate%22); // HTTP 1.1.%0A%09 this.addHeader(%22Pragma%22, %22no-cache%22); // HTTP 1.0.%0A%09 this.addHeader(%22Expires%22, 0); // Proxies.%0A%0A%09 this.addHeader(%22Location%22, randomImageIndexed());%0A%09 this.setStatusCode(303)%0A%0A%0A%09 return %22%22;%0A
%09%7D%0A %7D
|
386b47b0b505ca9445a5d4597110aa8f226e5a77 | Remove CM_FormField_Integer.getValue in favor of correct value sync. | library/CM/FormField/Integer.js | library/CM/FormField/Integer.js | /**
* @class CM_FormField_Integer
* @extends CM_FormField_Abstract
*/
var CM_FormField_Integer = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Integer',
_$noUiHandle: null,
ready: function() {
var field = this;
var $input = this.$('input');
var $slider = this.$('.noUiSlider');
var $sliderValue = this.$('.noUiSlider-value');
$slider.noUiSlider({
range: {min: field.getOption('min'), max: field.getOption('max')},
start: $input.val(),
step: field.getOption('step'),
handles: 1,
behaviour: 'tap'
});
$slider.on('slide set', function(e, val) {
val = parseInt(val);
$input.val(val);
$sliderValue.html(val);
field._onChange();
});
this._$noUiHandle = $slider.find('.noUi-handle');
this._$noUiHandle.attr('tabindex', '0');
$input.watch('disabled', function(propName, oldVal, newVal) {
if (false === newVal) {
$slider.removeAttr('disabled');
field._$noUiHandle.attr('tabindex', '0');
} else {
$slider.attr('disabled', 'disabled');
field._$noUiHandle.attr('tabindex', '-1');
}
});
this.bindJquery($(window), 'keydown', this._onKeyDown);
this.on('destruct', function() {
$input.unwatch('disabled');
});
},
/**
* @param {Number} value
*/
setValue: function(value) {
this.$('.noUiSlider').val(value);
this._onChange();
},
/**
* @returns {Number}
*/
getValue: function() {
return parseInt(this.$('.noUiSlider').val());
},
_onChange: function() {
this.trigger('change');
},
_onKeyDown: function(event) {
if (this._$noUiHandle.is(':focus')) {
if (event.which === cm.keyCode.LEFT || event.which === cm.keyCode.DOWN) {
this.setValue(this.getValue() - this.getOption('step'));
event.preventDefault();
}
if (event.which === cm.keyCode.RIGHT || event.which === cm.keyCode.UP) {
this.setValue(this.getValue() + this.getOption('step'));
event.preventDefault();
}
}
}
});
| JavaScript | 0 | @@ -1427,124 +1427,8 @@
%7D,%0A%0A
- /**%0A * @returns %7BNumber%7D%0A */%0A getValue: function() %7B%0A return parseInt(this.$('.noUiSlider').val());%0A %7D,%0A%0A
_o
|
dd0ef7f927a5183b450b4f6e6b4b38a5339b886a | complete has user media method | scripts/src/UserMedia.js | scripts/src/UserMedia.js | window.define(['src/NavigatorWrapper'], function(NavigatorWrapper) {
"use strict";
var UserMedia = function(navigator) {
if(typeof navigator === "undefined") {
this.navigator = new NavigatorWrapper();
}
else {
this.navigator = navigator;
}
};
UserMedia.prototype.hasGetUserMedia = function() {
// Note: Opera is un prefixed.
return
};
UserMedia.prototype.startCamera = function() {
// Not showing vendor prefixes.
navigator.webkitGetUserMedia({video: true, audio: true}, function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
// Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
// See crbug.com/110938.
video.onloadedmetadata = function(e) {
console.log('Ready to go. Do some stuff. ', e);
};
}, function(e) {
console.log('Reeeejected!', e);
});
};
return UserMedia;
});
| JavaScript | 0.000398 | @@ -372,53 +372,146 @@
-// Note: Opera is un prefixed.%0A return
+try %7B%0A this.navigator.getUserMedia();%0A return true;%0A %7D%0A catch(e) %7B%0A return false;%0A %7D
%0A
|
8ec32ca69f8759bf2e64724cf7ef7aad9744c87b | Clear php log on each npm start | scripts/webpack-serve.js | scripts/webpack-serve.js | const fs = require('fs-extra')
const path = require('path')
const browserSync = require('browser-sync')
const webpack = require('webpack')
const webpackConfig = require('../webpack.config.dev')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const php = require('@pqml/node-php-server')
const Tail = require('tail').Tail
const user = require('../main.config.js')
const sh = require('kool-shell')()
.use(require('kool-shell/plugins/log'))
.use(require('kool-shell/plugins/exit'))
const LOGPATH = path.join(process.cwd(), 'php-error.log')
const bs = browserSync.create()
const useProxy = !!user.devServer.proxy
let isWebpackInit, isPhpInit
let compiler
let hotMiddleware, devMiddleware, proxyAddr, phpServer
phpInit()
function phpInit () {
sh.log()
sh.step(1, 3, useProxy
? 'PHP has to run from your proxy, ' + user.devServer.proxy
: 'Starting a php server...')
// if a proxy is set we don't need to create a built-in php server
if (useProxy) {
proxyAddr = user.devServer.proxy
isPhpInit = true
return webpackInit()
}
let args = [
'-d', 'upload_max_filesize=100M',
'-d', 'post_max_size=500M',
'-d', 'short_open_tag=On'
]
if (user.devServer.logPhpErrors) {
args.push('-d', 'error_log="' + LOGPATH + '"')
}
phpServer = php({
bin: user.devServer.phpBinary || 'php',
host: 'localhost',
root: user.paths.www,
verbose: false,
promptBinary: true,
args
})
phpServer.on('start', ({host, port}) => {
if (isPhpInit) return
// php server can't be reach through localhost, we have to use [::1]
sh.log('PHP Server started on ' + host + ':' + port + '\n')
if (host === 'localhost') {
sh.warn('\nNode can\'t reach PHP built-in server through localhost.\nProxying [::1]:' + port + ' instead.')
host = '[::1]'
}
proxyAddr = host + ':' + port
isPhpInit = true
webpackInit()
})
phpServer.start()
}
function webpackInit () {
sh.log()
sh.step(2, 3, 'Running the webpack compiler...')
compiler = webpack(webpackConfig)
hotMiddleware = webpackHotMiddleware(compiler)
devMiddleware = webpackDevMiddleware(compiler, {
publicPath: user.paths.basepath,
stats: {
colors: true,
hash: false,
timings: false,
chunks: false,
chunkModules: false,
modules: false
}
})
compiler.plugin('done', () => {
// init the browserSync server once a first build is ready
if (isWebpackInit) return
isWebpackInit = true
process.nextTick(browserSyncInit)
})
}
function browserSyncInit () {
sh.log()
sh.step(3, 3, 'Starting the browser-sync server...')
const middlewares = [devMiddleware, hotMiddleware]
// add a custom event for change in the www/content folder
// to enable livereload on the site but disable it on panel to avoid reload
// when editing the content.
bs.use({
plugin () {},
hooks: {
'client:js': fs.readFileSync(
path.join(__dirname, 'utils', 'browsersync-update-content.js'),
'utf-8'
)
}
})
bs.init({
port: user.devServer.port || 8080,
proxy: {
target: proxyAddr,
middleware: middlewares,
proxyReq: [(proxyReq, req, res) => {
proxyReq.setHeader('X-Forwarded-For', 'webpack')
proxyReq.setHeader('X-Forwarded-Host', req.headers.host)
}]
},
open: false,
reloadOnRestart: true,
notify: false,
files: [path.join(user.paths.www, '**/*')],
watchOptions: {
ignoreInitial: true,
ignored: [
path.join(user.paths.www, '**/*.log'),
path.join(user.paths.www, 'content', '**/*'),
path.join(user.paths.www, 'site', 'cache', '**/*'),
path.join(user.paths.www, 'site', 'accounts', '**/*'),
path.join(user.paths.www, 'thumbs', '**/*')
]
}
}, (error, instance) => {
if (error) throw error
// custom event for change in the www/content folder
bs.watch(path.join(user.paths.www, 'content', '**/*')).on('change', (file) => {
instance.io.sockets.emit('kirby:contentupdate', { file: file })
})
ready()
})
}
function ready () {
process.nextTick(() => {
sh.log()
sh.success('kirby-webpack server is up and running\n')
if (user.devServer.logPhpErrors) logPhpError()
})
}
function logPhpError () {
fs.ensureFile(LOGPATH)
.then(() => {
const tail = new Tail(LOGPATH, {
useWatchFile: true,
fsWatchOptions: { interval: 300 }
})
tail.on('line', (data) => {
if (/^\[[a-zA-Z0-9: -]+\] .+/g.test(data)) {
data = data.toString('utf8').split(']')
const date = sh.colors.gray(data.shift() + ']')
data = date + data.join(']')
}
sh.log(sh.colors.red('[PHP]') + data)
})
tail.on('error', err => sh.error(err))
})
.catch(err => {
sh.error(err)
})
}
| JavaScript | 0 | @@ -4386,16 +4386,86 @@
r () %7B%0A
+ Promise.resolve()%0A .then(() =%3E fs.remove(LOGPATH))%0A .then(() =%3E
fs.ensu
@@ -4479,16 +4479,17 @@
LOGPATH)
+)
%0A .th
|
780473fccf5293da6dec4707707f4c472aba3243 | allow GH deps | tests/unit/package/dependency-version-test.js | tests/unit/package/dependency-version-test.js | 'use strict';
var assert = require('../../helpers/assert');
var semver = require('semver');
function assertVersionLock(deps) {
deps = deps || {};
Object.keys(deps).forEach(function(name) {
if (name !== 'ember-cli' && semver.gtr('1.0.0', deps[name])) {
// only valid if the version is fixed
assert(semver.valid(deps[name]), '"' + name + '" has a valid version');
}
});
}
describe('dependencies', function() {
var pkg;
describe('in package.json', function() {
before(function() {
pkg = require('../../../package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
describe('in blueprints/app/files/package.json', function() {
before(function() {
pkg = require('../../../blueprints/app/files/package.json');
});
it('are locked down for pre-1.0 versions', function() {
assertVersionLock(pkg.dependencies);
assertVersionLock(pkg.devDependencies);
});
});
});
| JavaScript | 0.000001 | @@ -114,16 +114,17 @@
ionLock(
+_
deps) %7B%0A
@@ -129,15 +129,20 @@
%7B%0A
+var
deps =
+_
deps
@@ -226,16 +226,60 @@
-cli' &&
+%0A semver.valid(deps%5Bname%5D) &&%0A
semver.
|
579b672c9377595b33f8f33dba57ac14f6e9295d | Build search conditions correctly | content/typicalReplyButtons.js | content/typicalReplyButtons.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var TypicalReplyButtons = {
get utils() {
delete this.utils;
let { TypicalReply } = Components.utils.import('resource://typical-reply-modules/TypicalReply.jsm', {});
return this.utils = TypicalReply;
},
get virtualFolderHelper() {
delete this.virtualFolderHelper;
let { VirtualFolderHelper } = Components.utils.import('resource:///modules/virtualFolderWrapper.js', {});
return this.virtualFolderHelper = VirtualFolderHelper;
},
onCommand: function(aEvent) {
var target = aEvent.target;
var type = target.getAttribute('data-type');
var definition = this.utils.getDefinition(type);
if (definition.alwaysQuote)
this.utils.quote = true;
else
this.utils.quote = target.getAttribute('data-quote') == 'true';
this.utils.type = type;
if (definition.recipients == this.utils.RECIPIENTS_ALL)
MsgReplyToAllMessage(aEvent);
else
MsgReplySender(aEvent);
},
get container() {
return document.getElementById('typicalReply-buttons-container');
},
get actionsButton() {
return document.getElementById('typicalReply-actions-button');
},
get menupopup() {
return document.getElementById('typicalReply-menupopup');
},
buildUI: function() {
var buttons = document.createDocumentFragment();
this.utils.definitions.forEach(function(aDefinition) {
if (aDefinition.separate)
buttons.appendChild(this.buildActionButton(aDefinition));
}, this);
this.container.insertBefore(buttons, this.actionsButton);
var menupopupChildren = document.createDocumentFragment();
this.utils.definitions.forEach(function(aDefinition, aIndex) {
if (aDefinition.separate)
return;
if (aIndex > 0)
menupopupChildren.appendChild(document.createElement('menuseparator'));
menupopupChildren.appendChild(this.buildActionItems(aDefinition));
}, this);
this.menupopup.appendChild(menupopupChildren);
if (!this.menupopup.hasChildNodes())
this.actionsButton.setAttribute('hidden', true);
},
buildActionButton: function(aDefinition) {
var button = document.createElement('toolbarbutton');
if (aDefinition.icon) {
button.setAttribute('class', 'toolbarbutton-1 msgHeaderView-button');
button.setAttribute('image', aDefinition.icon);
} else {
button.setAttribute('class', 'toolbarbutton-1 msgHeaderView-button hdrReplyButton');
}
button.setAttribute('label', aDefinition.label);
button.setAttribute('data-type', aDefinition.type);
button.setAttribute('oncommand', 'TypicalReplyButtons.onCommand(event);');
if (aDefinition.alwaysQuote) {
button.setAttribute('data-quote', 'true');
}
else {
button.setAttribute('type', 'menu-button');
let menupopup = document.createElement('menupopup');
this.buildActionItems(aDefinition, menupopup);
button.appendChild(menupopup);
}
return button;
},
buildActionItems: function(aDefinition) {
var fragment = document.createDocumentFragment();
var item = document.createElement('menuitem');
if (aDefinition.icon) {
item.setAttribute('class', 'menuitem-iconic');
item.setAttribute('image', aDefinition.icon);
}
item.setAttribute('label', aDefinition.label);
item.setAttribute('accesskey', aDefinition.accesskey);
item.setAttribute('data-type', aDefinition.type);
if (aDefinition.alwaysQuote) {
item.setAttribute('data-quote', 'true');
fragment.appendChild(item);
}
else {
fragment.appendChild(item);
let withQuote = item.cloneNode(true);
withQuote.setAttribute('label', aDefinition.labelQuote);
withQuote.setAttribute('data-quote', 'true');
fragment.appendChild(withQuote);
}
return fragment;
},
observe: function(aSubject, aTopic, aData) {
Services.obs.removeObserver(this, 'mail-tabs-session-restored');
// This must be done after mail-tabs-session-restored.
// Otherwise, non-ASCII search conditions are not saved correctly.
this.buildSearchFolders();
},
buildSearchFolders: function() {
this.utils.allAccounts.forEach(function(aAccount) {
this.utils.definitions.forEach(function(aDefinition) {
if (!aDefinition.searchFolder)
return;
try {
if (aAccount.incomingServer)
this.buildSearchFolderForAccount(aDefinition, aAccount);
}
catch(e) {
Components.utils.reportError(e);
}
}, this);
}, this);
},
buildSearchFolderForAccount: function(aDefinition, aAccount) {
if (!aDefinition.subjectPrefix && !aDefinition.subject)
return;
var rootFolder = aAccount.incomingServer.rootMsgFolder;
if (!rootFolder)
return;
var inbox = rootFolder.getFolderWithFlags(Components.interfaces.nsMsgFolderFlags.Inbox);
if (!inbox)
return;
var name = 'typicalReply-' + aDefinition.type;
var isCreation = false;
var isModified = false;
var searchFolder;
try {
searchFolder = rootFolder.getChildNamed(name);
} catch(e) {
// folder not found!
}
if (!searchFolder) {
isCreation = true;
isModified = true;
searchFolder = rootFolder.addSubfolder(name);
searchFolder.setFlag(Components.interfaces.nsMsgFolderFlags.Virtual);
}
// We always have to set prettyName because it is not saved.
searchFolder.prettyName = aDefinition.label;
var wrapper = this.virtualFolderHelper.wrapVirtualFolder(searchFolder);
var conditions = this.buildSearchCondition();
if (wrapper.searchString != conditions) {
wrapper.searchString = conditions;
isModified = true;
}
if (isCreation) {
wrapper.searchFolders = rootFolder.URI + '|' + inbox.URI;
wrapper.onlineSearch = false;
}
if (!isModified)
return;
wrapper.cleanUpMessageDatabase();
if (isCreation) {
searchFolder.msgDatabase.Close(true);
rootFolder.NotifyItemAdded(searchFolder);
}
MailServices.accounts.saveVirtualFolders();
},
buildSearchCondition: function(aDefinition) {
if (aDefinition.subjectPrefix)
return 'AND (subject,begins with,' + this.UnicodeToUTF8(aDefinition.subjectPrefix) + ')';
return 'AND (subject,is,' + this.UnicodeToUTF8(aDefinition.subject) + ')';
},
UnicodeToUTF8: function(aString) {
return unescape(encodeURIComponent(aString));
}
};
window.addEventListener('DOMContentLoaded', function TypicalReplyButtonsSetup() {
window.removeEventListener('DOMContentLoaded', TypicalReplyButtonsSetup, false);
TypicalReplyButtons.buildUI();
var toolbar = document.getElementById('header-view-toolbar');
var matcher = /\b(hdrReplyToSenderButton,hdrSmartReplyButton|hdrReplyToSenderButton|hdrSmartReplyButton|hdrForwardButton)\b/;
var defaultset = toolbar.getAttribute('defaultset');
if (matcher.test(defaultset))
toolbar.setAttribute('defaultset', defaultset.replace(matcher, '$1,typicalReply-buttons-container'));
else
toolbar.setAttribute('defaultset', defaultset + ',typicalReply-buttons-container');
Services.obs.addObserver(TypicalReplyButtons, 'mail-tabs-session-restored', false);
}, false);
| JavaScript | 0.000009 | @@ -5774,16 +5774,27 @@
ndition(
+aDefinition
);%0A i
|
420ca6d21c2072a0f10e05a1cf5d2fc8e961e4c6 | Create login functionality in Ally framework | plugins/gui-core/gui-resources/scripts/js/views/auth.js | plugins/gui-core/gui-resources/scripts/js/views/auth.js | define
([
'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
var AuthLogin = function(username, password, logintoken){
=======
var AuthDetails = function(username){
var authDetails = new $.rest('Superdesk/User');
authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
var user = users.UserList[0];
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.Name);
localStorage.setItem('superdesk.login.email', user.EMail);
});
return $(authDetails);
},
AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
authLogin = new $.rest('Authentication');
authLogin.resetData().insert({
UserName: username,
LoginToken: logintoken,
HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
}).done(function(user){
localStorage.setItem('superdesk.login.session', user.Session);
<<<<<<< HEAD
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
=======
//localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
/* authDetails = AuthDetails(username);
$(authDetails).on('failed', function(){
$(authLogin).trigger('failed', 'authDetails');
});
*/
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
});
return $(authLogin);
},
AuthToken = function(username, password) {
var authToken = new $.rest('Authentication');
authToken.resetData().select({ userName: username }).done(
function(data){
authLogin = AuthLogin(username, password, data.Token);
authLogin.on('failed', function(){
$(authToken).trigger('failed', 'authToken');
}).on('success', function(){
$(authToken).trigger('success');
});
}
);
return $(authToken);
},
AuthApp =
{
success: $.noop,
require: function()
{
if(this.showed) return;
var self = this; // rest
self.showed = true;
$.tmpl('auth', null, function(e, o)
{
var dialog = $(o).eq(0).dialog
({
draggable: false,
resizable: false,
modal: true,
width: "40.1709%",
buttons:
[
{ text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
{ text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
]
}),
form = dialog.find('form');
form.off('submit.superdesk')//
.on('submit.superdesk', function(event)
{
var username = $(this).find('#username'), password=$(this).find('#password');
AuthToken(username.val(), password.val()).on('failed',function(evt, type){
username.val('');
password.val('')
}).on('success', function(){
AuthApp.success && AuthApp.success.apply();
$(dialog).dialog('close');
self.showed = false;
});
event.preventDefault();
});
});
}
};
return AuthApp;
}); | JavaScript | 0 | @@ -1220,29 +1220,16 @@
ssion);%0A
-%3C%3C%3C%3C%3C%3C%3C HEAD%0A
%09%09%09local
@@ -1445,437 +1445,8 @@
');%0A
-=======%0A%09%09%09//localStorage.setItem('superdesk.login.id', user.Id);%0A%09%09%09localStorage.setItem('superdesk.login.name', user.UserName);%0A%09%09%09localStorage.setItem('superdesk.login.email', user.EMail);%09%09%09%0A%09%09%09$(authLogin).trigger('success');%0A/*%09%09%09authDetails = AuthDetails(username);%0A%09%09%09$(authDetails).on('failed', function()%7B%0A%09%09%09%09$(authLogin).trigger('failed', 'authDetails');%0A%09%09%09%7D);%0A*/%09%09%09%0A%3E%3E%3E%3E%3E%3E%3E 718d8c014dc7f1c47606de731769286a6bcebb81%0A
%09%09%7D)
|
50e2c2435e662105664985fa24684d66f409a124 | fix tests | test/Context.test.js | test/Context.test.js | 'use strict';
const expect = require('chai').expect;
const Context = require('../lib/Context');
const Method = require('../lib/Method');
describe('class Context', function() {
let context, method;
let noop = function() {};
beforeEach(function() {
method = new Method('test', {
params: [
{ name: 'username', type: 'string' },
{ name: 'age', type: 'number' },
{ name: 'randomDate', type: 'date' }
]
}, noop);
context = new Context({}, {}, method, {});
});
describe('constructor(req, res, method, options)', function() {
it('should raise an error if req is invalid', function() {
expect(function() {
new Context();
}).to.throw(Error).have.property('message', 'req is invalid');
});
it('should raise an error if res is invalid', function() {
expect(function() {
new Context({});
}).to.throw(Error).have.property('message', 'res is invalid');
});
it('should raise an error if method is invalid', function() {
expect(function() {
new Context({}, {});
}).to.throw(Error).have.property('message', 'method must be an instance of Method');
});
[
['request', function() { return { context }; }],
['req', function() { return { context }; }],
['response', function() { return { context }; }],
['res', function() { return { context }; }],
['options', {}],
['_method', function() { return method; }],
['methodName', 'test'],
['fullPath', '/'],
['argsBuilt', false],
['args', {}],
['_done', false],
['state', {}]
].forEach(function(prop) {
it(`should have property '${prop[0]}' and corresponding value`, function() {
let value = typeof prop[1] === 'function' ? prop[1]() : prop[1];
expect(context).to.have.property(prop[0]).deep.eq(value);
});
});
it('should parse arrayItemDelimiters options as regexp', function() {
let context = new Context({}, {}, method, { arrayItemDelimiters: [',', ' '] });
expect(context).to.have.nested.property('options.arrayItemDelimiters').eq(/,| /g);
});
});
describe('buildArgs()', function() {
it('should build args by method params config', function() {
let date = new Date('1998-01-01');
context.args = { name: 'Felix', username: 'lyfeyaj', age: 27, randomDate: date };
expect(context.buildArgs()).to.deep.eq({ username: 'lyfeyaj', age: 27, randomDate: date });
});
it('should convert args to specific type', function() {
context.args = { name: 'Felix', username: 'lyfeyaj', age: '27', randomDate: '1998-01-01' };
expect(context.buildArgs()).to.deep.eq({ username: 'lyfeyaj', age: 27, randomDate: new Date('1998-01-01') });
});
it('should build and convert inner params', function() {
let method = new Method('test', {
params: [
{ name: 'username', type: 'string' },
{ name: 'age', type: 'number' },
{ name: 'randomDate', type: 'date' },
{
name: 'profile',
type: 'object',
params: [
{ name: 'gender', type: 'number' },
{ name: 'hobbies', type: ['string'] },
{ name: 'tags', type: ['string'] }
]
}
]
}, noop);
let context = new Context({}, {}, method, { arrayItemDelimiters: ',' });
context.args = {
name: 'Felix',
username: 'lyfeyaj',
age: '27',
randomDate: '1998-01-01',
profile: {
gender: '0',
hobbies: 'pingpong',
tags: 'programmer,writer'
}
};
expect(context.buildArgs()).to.deep.eq(
{
username: 'lyfeyaj',
age: 27,
randomDate: new Date('1998-01-01'),
profile: {
gender: 0,
hobbies: ['pingpong'],
tags: ['programmer', 'writer']
}
}
);
});
it('should split string into array by options.arrayItemDelimiters', function() {
let method = new Method('test', {
params: [
{ name: 'hobbies', type: ['string'] }
]
}, noop);
let context = new Context({}, {}, method, { arrayItemDelimiters: ',' });
context.args = { hobbies: 'pingpong,table tennis,swimming,badminton' };
expect(context.buildArgs()).to.deep.eq({ hobbies: ['pingpong', 'table tennis', 'swimming', 'badminton'] });
});
});
describe('param(name)', function() {
it('should return param by name', function() {
context.args = { name: 'Felix' };
expect(context.param('name')).eq('Felix');
});
it('should support deep key query', function() {
context.args = { profile: { name: 'Felix' } };
expect(context.param('profile.name')).eq('Felix');
});
});
describe('throw()', function() {
it('should throw error on http status code', function() {
expect(function() {
context.throw(404);
}).to.throw(Error).have.property('message', 'Not Found');
});
});
describe('isFinished()', function() {
it('should throw error for not implement', function() {
expect(function() {
context.isFinished();
}).to.throw(Error).have.property('message', 'Not Implement');
});
});
describe('done()', function() {
it('should throw error for not implement', function() {
expect(function() {
context.done();
}).to.throw(Error).have.property('message', 'Not Implement');
});
});
});
| JavaScript | 0.000001 | @@ -2124,18 +2124,24 @@
iters').
-eq
+to.match
(/,%7C /g)
|
52806beb826b63d43d1637ebf32e1da64ccb6357 | Use global state for testTemplates | src/app/components/TestGenerator.js | src/app/components/TestGenerator.js | import 'codemirror/mode/javascript/javascript';
import React, { Component, PropTypes } from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Button from './Button';
import AddButton from 'react-icons/lib/md/add';
import EditButton from 'react-icons/lib/md/edit';
import TestGenerator from 'redux-devtools-test-generator';
import mochaTemplate from 'redux-devtools-test-generator/lib/redux/mocha/template';
import tapeTemplate from 'redux-devtools-test-generator/lib/redux/tape/template';
import TestForm from './TestForm';
import { getFromStorage, saveToStorage } from '../utils/localStorage';
import styles from '../styles';
export default class TestGen extends Component {
constructor(props) {
super(props);
let testTemplates = props.testTemplates || getFromStorage('test-templates');
let selected = props.selectedTemplate || getFromStorage('test-templates-sel') || 0;
if (typeof testTemplates === 'string') {
testTemplates = JSON.parse(testTemplates);
}
if (!testTemplates || testTemplates.length === 0) {
testTemplates = this.getDefaultTemplates();
}
if (typeof selected === 'string') {
selected = Number(selected);
}
this.state = { testTemplates, selected, dialogStatus: 0 };
}
onSelect = (event, index, value) => {
this.setState({ selected: saveToStorage('test-templates-sel', value) });
};
getDefaultTemplates() {
return [
{ name: 'Mocha template', ...mochaTemplate },
{ name: 'Tape template', ...tapeTemplate }
];
}
editTemplate = () => {
this.setState({ dialogStatus: 1 });
};
addTemplate = () => {
this.setState({ dialogStatus: 2 });
};
handleSave = (template) => {
let testTemplates = [...this.state.testTemplates];
let selected = this.state.selected;
if (this.state.dialogStatus === 1) {
testTemplates[this.state.selected] = template;
} else {
testTemplates.push(template);
selected = testTemplates.length - 1;
saveToStorage('test-templates-sel', selected);
}
saveToStorage('test-templates', testTemplates);
this.setState({ testTemplates, selected, dialogStatus: 0 });
};
handleRemove = () => {
// Todo: add snackbar with undo
const selected = 0;
let testTemplates = [...this.state.testTemplates];
testTemplates.splice(this.state.selected, 1);
if (testTemplates.length === 0) testTemplates = this.getDefaultTemplates();
saveToStorage('test-templates-sel', selected);
saveToStorage('test-templates', testTemplates);
this.setState({ testTemplates, selected, dialogStatus: 0 });
};
handleCloseDialog = () => {
this.setState({ dialogStatus: 0 });
};
render() {
const { dialogStatus, selected, testTemplates } = this.state;
const template = testTemplates[selected];
const { assertion, wrap } = template;
return (
<TestGenerator
assertion={assertion} wrap={wrap}
theme="night" useCodemirror={this.props.useCodemirror}
header={
<div style={{ height: '2.5em', display: 'flex' }}>
<SelectField
style={styles.select}
labelStyle={styles.selectLabel}
iconStyle={styles.selectIcon}
onChange={this.onSelect}
value={selected}
>
{testTemplates.map((item, i) =>
<MenuItem key={i} value={i} primaryText={item.name} />
)}
</SelectField>
<Button Icon={EditButton} onClick={this.editTemplate} />
<Button Icon={AddButton} onClick={this.addTemplate} />
<TestForm { ...{
template, dialogStatus,
onSave: this.handleSave,
onRemove: this.handleRemove,
onClose: this.handleCloseDialog
} }
/>
</div>
}
{...this.props}
/>
);
}
}
TestGen.propTypes = {
testTemplates: PropTypes.oneOfType([
PropTypes.array,
PropTypes.string
]),
selectedTemplate: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
]),
useCodemirror: PropTypes.bool
};
| JavaScript | 0 | @@ -683,16 +683,50 @@
yles';%0A%0A
+let testTemplates;%0Alet selected;%0A%0A
export d
@@ -807,27 +807,51 @@
props);%0A
-let
+if (!testTemplates) %7B%0A
testTemplat
@@ -912,27 +912,25 @@
ates');%0A
-let
+
selected =
@@ -994,24 +994,30 @@
sel') %7C%7C 0;%0A
+ %7D%0A
if (type
@@ -1409,32 +1409,16 @@
=%3E %7B%0A
- this.setState(%7B
selecte
@@ -1418,17 +1418,18 @@
selected
-:
+ =
saveToS
@@ -1463,16 +1463,46 @@
, value)
+;%0A this.setState(%7B selected
%7D);%0A %7D
@@ -1828,28 +1828,24 @@
e) =%3E %7B%0A
-let
testTemplate
@@ -1883,20 +1883,16 @@
s%5D;%0A
-let
selected
@@ -2350,22 +2350,16 @@
ndo%0A
-const
selected
@@ -2368,20 +2368,16 @@
0;%0A
-let
testTemp
@@ -2804,24 +2804,24 @@
render() %7B%0A
-
const %7B
@@ -2869,24 +2869,47 @@
this.state;
+ // eslint-disable-line
%0A const t
|
528324e00953a8689778aa1811529a39528e584c | Clean up redundant Promise.resolve() in ImagePreview.js | front_end/components/ImagePreview.js | front_end/components/ImagePreview.js | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../common/common.js';
import * as i18n from '../i18n/i18n.js';
import * as Platform from '../platform/platform.js';
import * as SDK from '../sdk/sdk.js';
import * as UI from '../ui/ui.js';
export const UIStrings = {
/**
*@description Description in Image Preview
*@example {500} PH1
*@example {300} PH2
*@example {200} PH3
*@example {100} PH4
*/
sSPxIntrinsicSSPx: '{PH1} × {PH2} px (intrinsic: {PH3} × {PH4} px)',
/**
*@description Description in Image Preview
*@example {500} PH1
*@example {500} PH2
*/
sSPx: '{PH1} × {PH2} px',
/**
*@description Alt text description of an image's source
*/
unknownSource: 'unknown source',
/**
*@description Text to indicate the source of an image
*@example {example.com} PH1
*/
imageFromS: 'Image from {PH1}',
};
const str_ = i18n.i18n.registerUIStrings('components/ImagePreview.js', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
/** @typedef {{
* renderedWidth: number,
* renderedHeight: number,
* currentSrc: (string|undefined)
* }}
*/
// @ts-ignore typedef
export let PrecomputedFeatures;
export class ImagePreview {
/**
* @param {!SDK.SDKModel.Target} target
* @param {string} originalImageURL
* @param {boolean} showDimensions
* @param {!{precomputedFeatures: (!PrecomputedFeatures|undefined), imageAltText: (string|undefined)}=} options
* @return {!Promise<?Element>}
*/
static build(
target, originalImageURL, showDimensions, options = {precomputedFeatures: undefined, imageAltText: undefined}) {
const {precomputedFeatures, imageAltText} = options;
const resourceTreeModel = target.model(SDK.ResourceTreeModel.ResourceTreeModel);
if (!resourceTreeModel) {
return Promise.resolve(/** @type {?Element} */ (null));
}
let resource = resourceTreeModel.resourceForURL(originalImageURL);
let imageURL = originalImageURL;
if (!isImageResource(resource) && precomputedFeatures && precomputedFeatures.currentSrc) {
imageURL = precomputedFeatures.currentSrc;
resource = resourceTreeModel.resourceForURL(imageURL);
}
if (!resource || !isImageResource(resource)) {
return Promise.resolve(/** @type {?Element} */ (null));
}
/** @type {function(*):void} */
let fulfill;
const promise = new Promise(x => {
fulfill = x;
});
const imageElement = /** @type{!HTMLImageElement} */ (document.createElement('img'));
imageElement.addEventListener('load', buildContent, false);
imageElement.addEventListener('error', () => fulfill(null), false);
if (imageAltText) {
imageElement.alt = imageAltText;
}
resource.populateImageSource(imageElement);
return promise;
/**
* @param {?SDK.Resource.Resource} resource
* @return {boolean}
*/
function isImageResource(resource) {
return !!resource && resource.resourceType() === Common.ResourceType.resourceTypes.Image;
}
function buildContent() {
const container = document.createElement('table');
UI.Utils.appendStyle(container, 'components/imagePreview.css', {enableLegacyPatching: false});
container.className = 'image-preview-container';
const intrinsicWidth = imageElement.naturalWidth;
const intrinsicHeight = imageElement.naturalHeight;
const renderedWidth = precomputedFeatures ? precomputedFeatures.renderedWidth : intrinsicWidth;
const renderedHeight = precomputedFeatures ? precomputedFeatures.renderedHeight : intrinsicHeight;
let description;
if (showDimensions) {
if (renderedHeight !== intrinsicHeight || renderedWidth !== intrinsicWidth) {
description = i18nString(
UIStrings.sSPxIntrinsicSSPx,
{PH1: renderedWidth, PH2: renderedHeight, PH3: intrinsicWidth, PH4: intrinsicHeight});
} else {
description = i18nString(UIStrings.sSPx, {PH1: renderedWidth, PH2: renderedHeight});
}
}
container.createChild('tr').createChild('td', 'image-container').appendChild(imageElement);
if (description) {
container.createChild('tr').createChild('td').createChild('span', 'description').textContent = description;
}
if (imageURL !== originalImageURL) {
container.createChild('tr').createChild('td').createChild('span', 'description').textContent =
Platform.StringUtilities.sprintf('currentSrc: %s', imageURL.trimMiddle(100));
}
fulfill(container);
}
}
/**
* @param {!SDK.DOMModel.DOMNode} node
* @return {!Promise<!PrecomputedFeatures|undefined>}
*/
static async loadDimensionsForNode(node) {
if (!node.nodeName() || node.nodeName().toLowerCase() !== 'img') {
return;
}
const object = await node.resolveToObject('');
if (!object) {
return;
}
const featuresObject = object.callFunctionJSON(features, undefined);
object.release();
return featuresObject;
/**
* @return {!PrecomputedFeatures}
* @this {!HTMLImageElement}
*/
function features() {
return {renderedWidth: this.width, renderedHeight: this.height, currentSrc: this.currentSrc};
}
}
/**
* @param {string} url
* @return {string}
*/
static defaultAltTextForImageURL(url) {
const parsedImageURL = new Common.ParsedURL.ParsedURL(url);
const imageSourceText = parsedImageURL.isValid ? parsedImageURL.displayName : i18nString(UIStrings.unknownSource);
return i18nString(UIStrings.imageFromS, {PH1: imageSourceText});
}
}
| JavaScript | 0.000013 | @@ -1622,15 +1622,21 @@
tic
+async
build(%0A
-
@@ -1935,32 +1935,16 @@
return
-Promise.resolve(
/** @typ
@@ -1957,33 +1957,32 @@
ement%7D */ (null)
-)
;%0A %7D%0A let
@@ -2360,24 +2360,8 @@
urn
-Promise.resolve(
/**
@@ -2386,17 +2386,16 @@
/ (null)
-)
;%0A %7D%0A
|
b8f3d96e5a9eff76834b4cb95238218eb42c6a4c | use explicit cookie name for cookieconsent | sirepo/package_data/static/js/sirepo-common.js | sirepo/package_data/static/js/sirepo-common.js | 'use strict';
// Common code shared between the landing page app and the various sirepo apps
window.cookieconsent.initialise({
//TODO(pjm): set cookie domain?
content: {
//TODO(pjm): update with links to terms of service when available
message: 'This site uses cookies to deliver our services. By using our site, you acknowledge that you accept our use of cookies.',
dismiss: 'I accept',
link: null,
},
palette: {
popup: {
background: "#000",
},
button: {
background: "#286090",
},
},
});
| JavaScript | 0.000001 | @@ -438,24 +438,79 @@
ull,%0A %7D,%0A
+ cookie: %7B%0A name: 'sr_cookieconsent',%0A %7D,%0A
palette:
|
c9340fce163c1d4c07dd5ce9d066818768bb76f3 | Fix style violation. | frontend/js/components/atoms/Card.js | frontend/js/components/atoms/Card.js | import React, { PropTypes, Component } from 'react';
class Card extends Component {
constructor(props) {
super(props);
}
render() {
return (
<section
className={`${this.props.className} card`}
onClick={this.props.onClick}>
{
(!!this.props.title || !!this.props.onClose) &&
<div className="card-title">
<h2>{this.props.title}</h2>
{this.props.onClose &&
<Icon onClick={this.props.onClose}>close</Icon>
}
</div>
}
<div className="card-body">
{ this.props.children }
</div>
<div className="card-actions">
{this.props.actions}
</div>
</section>
);
}
}
Card.propTypes = {
style: PropTypes.object,
children: PropTypes.any,
className: PropTypes.string,
onClick: PropTypes.func,
title: PropTypes.string,
onClose: PropTypes.func
};
export default Card;
| JavaScript | 0 | @@ -45,16 +45,52 @@
'react';
+%0Aimport Icon from './../atoms/Icon';
%0A%0Aclass
@@ -1135,32 +1135,60 @@
opTypes.string,%0A
+ actions: PropTypes.any,%0A
onClose: Pro
|
07b88fb9792c25d4c70651488c14f5a6249e1331 | Remove unnecessary Em.run wrapping | test/app/app_test.js | test/app/app_test.js | module("Application", {
setup: function () {
Ember.run(function () {MY_APP.reset();});
}
});
test("Parameters", function () {
ok(MY_APP.rootElement === "#MY_APP", "rootElement");
ok(Ember.$.support.cors, "Cross-origin resource sharing support");
});
| JavaScript | 0.000008 | @@ -45,31 +45,8 @@
%7B%0A%09%09
-Ember.run(function () %7B
MY_A
@@ -56,19 +56,16 @@
reset();
-%7D);
%0A%09%7D%0A%7D);%0A
|
01ae2f9b8f48b29b8478138d2af15acc2d0cfa9e | Update Cell.js | src/entity/Cell.js | src/entity/Cell.js | function Cell(gameServer, owner, position, size) {
this.gameServer = gameServer;
this.owner = owner; // playerTracker that owns this cell
this.tickOfBirth = 0;
this.color = { r: 0, g: 0, b: 0 };
this.position = { x: 0, y: 0 };
this._sizeSquared = 0;
this._size = 0;
this._mass = 0;
this.cellType = -1; // 0 = Player Cell, 1 = Food, 2 = Virus, 3 = Ejected Mass
this.isSpiked = false; // If true, then this cell has spikes around it
this.isAgitated = false;// If true, then this cell has waves on it's outline
this.killedBy = null; // Cell that ate this cell
this.isMoving = false; // Indicate that cell is in boosted mode
this.boostDistance = 0;
this.boostDirection = { x: 1, y: 0, angle: Math.PI / 2 };
if (this.gameServer) {
this.tickOfBirth = this.gameServer.tickCounter;
this.nodeId = this.getNextNodeId();
if (size) this.setSize(size);
if (position) this.position = position;
}
}
module.exports = Cell;
// Fields not defined by the constructor are considered private and need a getter/setter to access from a different class
Cell.prototype.getNextNodeId = function () {
if (this.gameServer.lastNodeId > 2147483647) {
this.gameServer.lastNodeId = 1;
}
return this.gameServer.lastNodeId++ >> 0;
};
Cell.prototype.setColor = function (color) {
this.color.r = color.r;
this.color.g = color.g;
this.color.b = color.b;
};
Cell.prototype.setSize = function (size) {
this._size = size;
this._sizeSquared = size * size;
this._mass = this._sizeSquared / 100;
if (this.owner)
this.owner.isMassChanged = true;
};
// by default cell cannot eat anyone
Cell.prototype.canEat = function (cell) {
return false;
};
// Returns cell age in ticks for specified game tick
Cell.prototype.getAge = function () {
if (this.tickOfBirth == null) return 0; // age cant be less than 0
return Math.max(0, this.gameServer.tickCounter - this.tickOfBirth);
};
// Called to eat prey cell
Cell.prototype.onEat = function (prey) {
if (!this.gameServer.config.playerBotGrow) {
if (this._mass >= 625 && prey._mass <= 17 && prey.cellType != 3)
prey._sizeSquared = 0; // Can't grow from cells under 17 mass
}
this.setSize(Math.sqrt(this._sizeSquared + prey._sizeSquared));
};
Cell.prototype.setBoost = function (distance, angle) {
this.boostDistance = distance;
this.boostDirection = {
x: Math.sin(angle),
y: Math.cos(angle),
angle: angle
};
this.isMoving = true;
if (!this.owner) {
var index = this.gameServer.movingNodes.indexOf(this);
if (index < 0)
this.gameServer.movingNodes.push(this);
}
};
Cell.prototype.checkBorder = function (border) {
this.position.x = Math.max(this.position.x, border.minx + this._size / 2);
this.position.y = Math.max(this.position.y, border.miny + this._size / 2);
this.position.x = Math.min(this.position.x, border.maxx - this._size / 2);
this.position.y = Math.min(this.position.y, border.maxy - this._size / 2);
};
Cell.prototype.onEaten = function (hunter) { };
Cell.prototype.onAdd = function (gameServer) { };
Cell.prototype.onRemove = function (gameServer) { };
| JavaScript | 0 | @@ -913,22 +913,35 @@
is.g
-etNextNodeId()
+ameServer.lastNodeId++ %3E%3E 0
;%0D%0A
@@ -1194,207 +1194,8 @@
%0D%0A%0D%0A
-Cell.prototype.getNextNodeId = function () %7B%0D%0A if (this.gameServer.lastNodeId %3E 2147483647) %7B%0D%0A this.gameServer.lastNodeId = 1;%0D%0A %7D%0D%0A return this.gameServer.lastNodeId++ %3E%3E 0;%0D%0A%7D;%0D%0A%0D%0A
Cell
@@ -2089,12 +2089,12 @@
ype
-!= 3
+== 0
)%0D%0A
@@ -2146,20 +2146,22 @@
ow from
-cell
+player
s under
|
9211bb282e64d552267a601f29d1d1447a5fd7e2 | delete toBeFalsy, add toBeNull and toBeCloseTo methods | src/expectation.js | src/expectation.js | define(['is-equal', 'get-type', 'condition'],
function (isEqual, getType, condition) {
"use strict";
function Expectation (context, thing, opts) {
opts = opts || {};
var not = opts.not || false,
passed = null,
message = function () {
var n,
text = [passed ? "PASSED: " : "FAILED: ",
"expected ", getType(thing), ' ', condition(thing).text, ' '];
for (n = 0; n < arguments.length; n++) {
text.push(arguments[n]);
}
return context.out(text.join(''), {
"color": "#000",
"background": passed ? 'rgba(44, 226, 44, 0.4)' : 'rgba(226, 44, 44, 0.4)',
"test": true
});
};
this.toEqual = function (otherThing) {
var result = isEqual(thing, otherThing);
passed = not ? !result : result;
message(not ? "not " : "", 'to equal ', getType(otherThing), ' ', condition(otherThing).text);
if (getType(thing) === getType(otherThing)
&& typeof thing === "object"
&& !passed) {
context.diff(thing, otherThing);
}
};
this.toBeTruthy = function () {
passed = not ? !thing : !!thing;
message(not ? "not " : "", 'to be truthy');
};
this.toBeFalsy = function () {
passed = not ? !!thing : !thing;
message(not ? "not " : "", 'to be falsy');
};
this.toBeDefined = function () {
passed = not ? thing === void 0 : thing !== void 0;
message(not ? "not " : "", 'to be defined');
};
return this;
}
return Expectation;
});
| JavaScript | 0 | @@ -992,35 +992,35 @@
ssage(not ?
-%22
+'
not
-%22 : %22%22
+' : ''
, 'to equal
@@ -1302,14 +1302,15 @@
toBe
-Truthy
+CloseTo
= f
@@ -1310,32 +1310,43 @@
eTo = function (
+num, margin
) %7B%0A
@@ -1358,30 +1358,97 @@
d =
-not ? !thing : !!thing
+thing %3C num + margin %7C%7C thing %3E num - margin;%0A passed = not ? !passed : passed
;%0A
@@ -1467,35 +1467,35 @@
ssage(not ?
-%22
+'
not
-%22 : %22%22
+' : ''
, 'to be tru
@@ -1495,15 +1495,51 @@
be
-truthy'
+close to ', num, ' by a margin of ', margin
);%0A
@@ -1569,12 +1569,13 @@
toBe
-Fals
+Truth
y =
@@ -1615,17 +1615,16 @@
= not ?
-!
!thing :
@@ -1624,16 +1624,17 @@
thing :
+!
!thing;%0A
@@ -1655,35 +1655,35 @@
ssage(not ?
-%22
+'
not
-%22 : %22%22
+' : ''
, 'to be fal
@@ -1679,20 +1679,21 @@
'to be
-fals
+truth
y');%0A
@@ -1835,19 +1835,19 @@
t ?
-%22
+'
not
-%22 : %22%22
+' : ''
, 't
@@ -1864,32 +1864,195 @@
ed');%0A %7D;
+%0A this.toBeNull = function () %7B%0A passed = not ? thing !== null : thing === null;%0A message(not ? 'not ' : '', 'to be null');%0A %7D;
%0A%0A return
|
18a2b4ee7bc9398c9208470c33406c4f584e1e76 | Add small delay on experiment return log | src/experiments.js | src/experiments.js | /* @flow */
import { info, track, immediateFlush } from 'beaver-logger/client';
import { FPTI } from './config';
import { getReturnToken, getSessionState, getDomainSetting, eventEmitter } from './lib';
export let onAuthorizeListener = eventEmitter();
function log(experiment : string, treatment : string, token : ?string, state : string) {
getSessionState(session => {
let event = `experiment_group_${ experiment }_${ treatment }_${ state }`;
let loggedEvents = session.loggedExperimentEvents = session.loggedExperimentEvents || [];
let duplicate = loggedEvents.indexOf(event) !== -1;
if (duplicate) {
info(`duplicate_${ event }`);
} else {
info(event);
loggedEvents.push(event);
track({
[ FPTI.KEY.STATE ]: FPTI.STATE.CHECKOUT,
[ FPTI.KEY.TRANSITION ]: state,
[ FPTI.KEY.EXPERIMENT_NAME ]: experiment,
[ FPTI.KEY.TREATMENT_NAME ]: treatment,
[ FPTI.KEY.TOKEN ]: token,
[ FPTI.KEY.CONTEXT_ID ]: token,
[ FPTI.KEY.CONTEXT_TYPE ]: token ? FPTI.CONTEXT_TYPE.EC_TOKEN : FPTI.CONTEXT_TYPE.UID
});
immediateFlush();
}
});
}
export function logExperimentTreatment(experiment : string, treatment : string, token : ?string) {
let exp;
let state;
if (experiment === 'walmart_paypal_incontext' || experiment === 'walmart_paypal_incontext_redirect') {
exp = 'walmart_paypal_incontext';
state = 'redirect';
} else if (experiment === 'walmart_paypal_incontext_click') {
exp = 'walmart_paypal_incontext';
state = 'click';
} else {
exp = experiment;
state = 'start';
}
getSessionState(session => {
session.externalExperiment = exp;
session.externalExperimentTreatment = treatment;
if (token) {
session.externalExperimentToken = token;
}
});
log(exp, treatment, token, state);
}
function logReturn(token : string) {
let {
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
} = getSessionState(session => session);
if (externalExperiment && externalExperimentTreatment && externalExperimentToken === token) {
log(externalExperiment, externalExperimentTreatment, token, `complete`);
} else {
info(`experiment_mismatch`, {
token,
externalExperiment,
externalExperimentTreatment,
externalExperimentToken
});
}
}
if (getDomainSetting('log_authorize')) {
onAuthorizeListener.once(({ paymentToken }) => {
logReturn(paymentToken);
});
let returnToken = getReturnToken();
if (returnToken) {
logReturn(returnToken);
}
}
| JavaScript | 0.000001 | @@ -2758,24 +2758,55 @@
ken %7D) =%3E %7B%0A
+ setTimeout(() =%3E %7B%0A
logR
@@ -2822,24 +2822,39 @@
mentToken);%0A
+ %7D, 1);%0A
%7D);%0A%0A
@@ -2926,29 +2926,124 @@
-logReturn(returnToken
+setTimeout(() =%3E %7B%0A if (returnToken) %7B%0A logReturn(returnToken);%0A %7D%0A %7D, 1
);%0A
|
535aa6c1b4a7dc04dc7ca69a6fa5a9499b5bfd50 | Add Expression._hasVariable to check if an expression has a variable | src/expressions.js | src/expressions.js | var Fraction = require('./fractions');
var Term = require('./terms');
var isInt = require('./helper').isInt;
var UserException = require('./exceptions').UserException;
// The constant of the expression is maintained on the Expression object itself.
// Anything else is held in an array of Term objects.
var Expression = function(variable) {
this.constant = new Fraction(0, 1);
this.terms = (variable ? [new Term(variable)] : []);
};
Expression.prototype.copy = function() {
var copy = new Expression('');
copy.constant = this.constant.copy();
var terms = [];
this.terms.forEach(function(t) {terms.push(t.copy());} );
copy.terms = terms;
return copy;
};
Expression.prototype.add = function(a) {
var copy = this.copy();
if (a instanceof Term) {
var exp = new Expression(a.variable).multiply(a.coefficient);
return copy.add(exp);
} else if (a instanceof Expression) {
copy.constant = copy.constant.add(a.constant);
var newTerms = a.copy().terms;
for (i = 0; i < copy.terms.length; i++) {
var thisTerm = copy.terms[i];
for (j = 0; j < newTerms.length; j++) {
var thatTerm = newTerms[j];
if (thisTerm.hasTheSameVariableAs(thatTerm)) {
thisTerm.coefficient = thisTerm.coefficient.add(thatTerm.coefficient);
newTerms.splice(j, 1);
}
}
}
copy.terms = copy.terms.concat(newTerms);
} else if (isInt(a) || a instanceof Fraction) {
copy.constant = copy.constant.add(a);
} else {
throw new UserException("NonIntegerArgument");
}
return copy;
};
Expression.prototype.subtract = function(a) {
var copy = this.copy();
var inverse;
if (a instanceof Term) {
var exp = new Expression(a.variable).multiply(a.coefficient).multiply(-1);
return copy.add(exp);
} else if (a instanceof Expression) {
var newTerms = [];
for (i = 0; i < a.terms.length; i++) {
var t = a.terms[i].copy();
t.coefficient = t.coefficient.multiply(-1);
newTerms.push(t);
}
inverse = a.copy();
inverse.constant = inverse.constant.multiply(-1);
inverse.terms = newTerms;
} else if (isInt(a)) {
inverse = -a;
} else if (a instanceof Fraction) {
inverse = a.multiply(-1);
} else {
throw new UserException("NonIntegerArgument");
}
return copy.add(inverse);
};
Expression.prototype.multiply = function(a) {
if (a instanceof Fraction || isInt(a)) {
var copy = this.copy();
copy.constant = copy.constant.multiply(a);
for (i = 0; i < copy.terms.length; i++) {
copy.terms[i].coefficient = copy.terms[i].coefficient.multiply(a);
}
return copy;
} else {
throw new UserException("NonIntegerArgument");
}
};
Expression.prototype.divide = function(a) {
if (a instanceof Fraction || isInt(a)) {
if (a == 0) {
return;
}
var copy = this.copy();
copy.constant = copy.constant.divide(a);
for (i = 0; i < copy.terms.length; i++) {
copy.terms[i].coefficient = copy.terms[i].coefficient.divide(a);
}
return copy;
} else {
throw new UserException("NonIntegerArgument");
}
};
Expression.prototype.evaluateAt = function(values) {
var copy = this.copy();
var vars = Object.keys(values);
for (i = 0; i < copy.terms.length; i++) {
for (j = 0; j < vars.length; j++) {
if (copy.terms[i].variable == vars[j]) {
copy.constant = copy.constant.add(copy.terms[i].coefficient.multiply(values[vars[j]]));
copy.terms.splice(i, 1);
}
}
}
if (copy.terms.length == 0) {
return copy.constant;
}
return copy;
};
Expression.prototype.print = function() {
if (this.terms.length == 0) {
return this.constant.print();
}
var firstTermCoefficient = this.terms[0].coefficient.reduce();
var str = (firstTermCoefficient.numer < 0 ? "-": "") + this.terms[0].print();
for (i = 1; i < this.terms.length; i++) {
var coefficient = this.terms[i].coefficient.reduce();
str += (coefficient.numer < 0 ? " - " : " + ") + this.terms[i].print();
}
var constant = this.constant.reduce();
if (constant.numer) {
str += (constant.numer < 0 ? " - " : " + ") + constant.abs().print();
}
return str;
};
Expression.prototype.tex = function() {
if (this.terms.length == 0) {
return this.constant.tex();
}
var firstTermCoefficient = this.terms[0].coefficient.reduce();
var str = (firstTermCoefficient.numer < 0 ? "-": "") + this.terms[0].tex();
for (i = 1; i < this.terms.length; i++) {
var coefficient = this.terms[i].coefficient.reduce();
str += (coefficient.numer < 0 ? " - " : " + ") + this.terms[i].tex();
}
var constant = this.constant.reduce();
if (constant.numer) {
str += (constant.numer < 0 ? " - " : " + ") + constant.abs().tex();
}
return str;
};
module.exports = Expression; | JavaScript | 0.000012 | @@ -5213,16 +5213,233 @@
tr;%0A%7D;%0A%0A
+Expression.prototype._hasVariable = function(variable) %7B%0A for (i = 0; i %3C this.terms.length; i++) %7B%0A if (variable == this.terms%5Bi%5D.variable) %7B%0A return true;%0A %7D%0A %7D%0A%0A return false;%0A%7D;%0A%0A
module.e
|
fcab90f27c6588b3c3d6c6b1eb4fa1589e499974 | test cases for vanilla usage of stringify; #1 | test/comment-json.js | test/comment-json.js | 'use strict';
var expect = require('chai').expect;
var comment_json = require('../'); | JavaScript | 0.000015 | @@ -53,16 +53,8 @@
var
-comment_
json
@@ -69,10 +69,957 @@
re('../'
+);%0A%0Adescribe(%22vanilla usage of %60json.stringify()%60%22, function()%7B%0A var subjects = %5B%0A 'abc',%0A 1,%0A true,%0A false,%0A null,%0A undefined,%0A %5B%5D,%0A %7B%7D,%0A %5B'abc', 1, %7Ba: 1, b: undefined%7D%5D,%0A %5Bundefined, 1, 'abc'%5D,%0A %7B%0A a: undefined,%0A b: false,%0A c: %5B1, '1'%5D%0A %7D%0A %5D;%0A%0A var replacers = %5B%0A null,%0A function (key, value) %7B%0A if (typeof value === 'string') %7B%0A return undefined;%0A %7D%0A%0A return value;%0A %7D%0A %5D;%0A%0A var spaces = %5B%0A 1,%0A 2,%0A ' ',%0A '1'%0A %5D;%0A %0A subjects.forEach(function (subject) %7B%0A replacers.forEach(function (replacer) %7B%0A spaces.forEach(function (space) %7B%0A var desc = %5Bsubject, replacer, space%5D.map(function (s) %7B%0A return JSON.stringify(s);%0A %7D).join(', ');%0A%0A it(desc, function()%7B%0A expect(json.stringify(subject, replacer, space)).to.equal(JSON.stringify(subject, replacer, space));%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%7D
);
|
22ca2419a125125101b1966b6c9c6d96fbec760f | Update ArmQuadrapus.js | game/js/gameentities/ArmQuadrapus.js | game/js/gameentities/ArmQuadrapus.js | "use strict";
var QuadrapusArm = function(world, Bullet, options, audio) {
this.world = world;
this.color = options.color || "#800080";
this.Bullet = Bullet;
this.audio = audio;
this.spriteName = options.spriteName || null;
this.type = "boss";
this.active = true;
this.width = options.width;
this.height = 13;
this.x = options.x;
this.y = options.y;
this.side = options.side;
this.section = options.section;
this.lives = 7;
this.hitboxMetrics = {
x: 0,
y: 0,
width: 90,
height: 13
};
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.update = function() {
this.updateHitbox();
};
QuadrapusArm.prototype.shotArc = function(start, end, step) {
if (start < end) {
for (var i = start; i < end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 5,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
} else {
for (var i = start; i > end; i += step) {
this.world.bullets.push(
new this.Bullet(this.world, {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2),
width: 20,
height: 20,
hitboxMetrics: {
x: 0,
y: 0,
width: 20,
height: 20
},
angle: i,
speed: 5,
acceleration: 0.1,
owner: this.type
}, this.audio
));
}
}
};
QuadrapusArm.prototype.draw = function() {
if (this.spriteName === null) {
this.world.drawRectangle(this.color, this.x, this.y, this.width, this.height);
} else {
this.world.drawSprite(this.spriteName, this.x, this.y, this.width, this.height);
}
};
QuadrapusArm.prototype.updateHitbox = function() {
this.hitbox = {
x: this.x + this.hitboxMetrics.x,
y: this.y + this.hitboxMetrics.y,
width: this.hitboxMetrics.width,
height: this.hitboxMetrics.height
};
};
QuadrapusArm.prototype.explode = function(source) {
if (source === "bullet") {
this.lives--;
}
if (this.lives < 1) {
this.active = false;
}
};
| JavaScript | 0 | @@ -1148,33 +1148,33 @@
i,%0A%09%09%09%09%09speed:
-5
+2
,%0A%09%09%09%09%09accelerat
@@ -1573,9 +1573,9 @@
ed:
-5
+2
,%0A%09%09
|
7fa27abeb433327ae608ef4b4dd5781247b36d11 | Clear timer on component destruction | app/ui/app/app-ui-widget-constraintset.js | app/ui/app/app-ui-widget-constraintset.js | /*
** ComponentJS -- Component System for JavaScript <http://componentjs.com>
** Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
** This Source Code Form is subject to the terms of the Mozilla Public
** License, v. 2.0. If a copy of the MPL was not distributed with this
** file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* global ace: true */
cs.ns('app.ui.widget.constraintset')
app.ui.widget.constraintset = cs.clazz({
mixin: [ cs.marker.controller ],
dynamics: {
editor: null,
timer: null
},
protos: {
create: function () {
var self = this
cs(self).create('model/view',
app.ui.widget.constraintset.model,
app.ui.widget.constraintset.view
)
/* calculate the savable content on demand */
cs(self).register({
name: 'getContent', spool: 'created',
func: function () {
return cs(self, 'model').value('data:constraintset')
}
})
cs(self, 'model').observe({
name: 'data:constraintset', spool: '..:created',
touch: true,
func: function (ev, content) {
if (self.timer !== null) {
/* global clearTimeout: true */
clearTimeout(self.timer)
}
/* global setTimeout: true */
self.timer = setTimeout(function () {
cs(self).publish('setChanged', content)
}, 1000)
}
})
cs(self).register({
name: 'setContent', spool: 'created',
func: function (content) {
cs(self, 'model').value('data:constraintset', content, true)
}
})
cs(self).register({
name: 'displaySyntacticError', spool: 'created',
func: function (errors) {
cs(self, 'model').value('state:syntactic-errors', errors)
}
})
cs(self).register({
name: 'displaySemanticError', spool: 'created',
func: function (errors) {
cs(self, 'model').value('state:semantic-errors', errors)
}
})
}
}
})
app.ui.widget.constraintset.model = cs.clazz({
mixin: [ cs.marker.model ],
protos: {
create: function () {
/* presentation model for items */
cs(this).model({
'data:constraintset' : { value: '', valid: 'string', store: true },
'data:savable' : { value: '', valid: 'string' },
'state:domain' : { value: '', valid: 'string' },
'state:semantic-errors' : { value: [], valid: 'any' },
'state:syntactic-errors' : { value: [], valid: 'any' }
})
}
}
})
app.ui.widget.constraintset.view = cs.clazz({
mixin: [ cs.marker.view ],
protos: {
show: function () {
var self = this
var id = 'id_' + Date.now()
var content = $.markup('constraint-set-content', { id: id })
cs(self).plug({
object: content,
spool: 'visible'
})
var suspend = false
self.editor = ace.edit(id)
self.editor.getSession().setMode('ace/mode/cjsc')
self.editor.on('change', function (ev, editor) {
if (suspend)
return;
suspend = true
cs(self).value('data:constraintset', editor.getValue())
suspend = false
})
cs(self).observe({
name: 'data:constraintset', spool: 'visible',
touch: true,
func: function (ev, nVal) {
if (suspend)
return;
suspend = true
self.editor.setValue(nVal)
self.editor.clearSelection()
suspend = false
}
})
cs(self).observe({
name: 'state:syntactic-errors', spool: 'visible',
touch: true,
func: function (ev, errors) {
if (errors.length === 0)
self.editor.getSession().setAnnotations([])
else {
errors = _.map(errors, function (error) {
return {
row: error.line - 1,
column: error.column,
text: error.message,
type: error.type
}
})
self.editor.getSession().setAnnotations(errors)
}
self.editor.focus()
}
})
cs(self).observe({
name: 'state:semantic-errors', spool: 'visible',
touch: true,
func: function (ev, errors) {
if (errors.length === 0)
self.editor.getSession().setAnnotations([])
else {
var linesAry = self.editor.getSession().getValue().split('\n')
errors = _.map(errors, function (error) {
return {
row: _.findIndex(linesAry, function (line) { return line.indexOf(error.constraint.id) !== -1 }),
column: error.column,
text: error.message,
type: error.type
}
})
self.editor.getSession().setAnnotations(errors)
}
self.editor.focus()
}
})
}
}
}) | JavaScript | 0 | @@ -2475,32 +2475,114 @@
%7D)%0D%0A
+ %7D,%0D%0A destroy: function () %7B%0D%0A clearTimeout(this.timer)%0D%0A
%7D%0D%0A %7D
|
378a32f905aa64f9ecf2d588c2aabd078f25cbd4 | Fix charts not showing in printed compendium | src/main/web/js/app/print-compendium.js | src/main/web/js/app/print-compendium.js | $(function() {
if ($('body').hasClass('compendium_landing_page')) {
$('.js-print-chapters').click(function (e) {
addLoadingOverlay();
$('.chapter').each(function (index) {
// Synchronously adds div with id to get around Ajax working asynchronously
$('main').append("<div id='compendium-print" + index + "'></div>");
var url = $(this).attr('href');
// Set what content from each page we want to retrieve for printing
var childIntro = ('.page-intro');
var childContent = ('.page-content');
$.get(url, function (data) {
$(data).find(childIntro).addClass('print--break-before').appendTo('#compendium-print' + index);
$(data).find(childContent).appendTo('#compendium-print' + index);
});
e.preventDefault();
});
$(document).ajaxStop(function () {
window.print();
location.reload();
});
});
}
});
| JavaScript | 0 | @@ -3,16 +3,17 @@
function
+
() %7B%0A
@@ -115,24 +115,56 @@
ction (e) %7B%0A
+ e.preventDefault();%0A
@@ -201,21 +201,108 @@
-$('.chapter')
+var $chapters = $('.chapter'),%0A chapterLength = $chapters.length;%0A%0A $chapters
.eac
@@ -757,64 +757,451 @@
-$.get(url, function (data) %7B%0A $(data)
+// Get chapter content%0A $.get(url, function (response) %7B%0A // Remove noscript tags around images, they break the charts when requested%0A var html = response.replace(/%3C%5C/noscript%3E/g, '').replace(/%3Cnoscript%3E/g, '');%0A%0A // Add in print page breaks before each chapter and add to compendium landing page%0A var $response = $(html);%0A $response
.fin
@@ -1310,14 +1310,16 @@
$
-(data)
+response
.fin
@@ -1375,73 +1375,430 @@
dex)
-;%0A %7D);%0A%0A%0A e.preventDefault();%0A
+.imagesLoaded().then(function() %7B%0A chaptersComplete(index);%0A %7D);%0A %7D);%0A %7D);%0A%0A // Tally number of chapters complete and print window when done%0A function chaptersComplete(index) %7B%0A if (index+1 == chapterLength) %7B%0A window.print();%0A location.reload();%0A %7D
%0A
+ %7D%0A
@@ -1818,33 +1818,178 @@
- $(document).ajaxStop(
+// Function to wait until all images are loaded in the DOM - stackoverflow.com/questions/4774746/jquery-ajax-wait-until-all-images-are-loaded%0A $.fn.imagesLoaded =
func
@@ -1994,24 +1994,25 @@
nction () %7B%0A
+%0A
@@ -2011,35 +2011,280 @@
- window.print
+// get all the images (excluding those with no src attribute)%0A var $imgs = this.find('img%5Bsrc!=%22%22%5D');%0A // if there's no images, just return an already resolved promise%0A if (!$imgs.length) %7Breturn $.Deferred().resolve().promise
();
+%7D%0A
%0A
@@ -2292,57 +2292,676 @@
- location.reload();%0A %7D);%0A %7D)
+// for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)%0A var dfds = %5B%5D;%0A $imgs.each(function()%7B%0A%0A var dfd = $.Deferred();%0A dfds.push(dfd);%0A var img = new Image();%0A img.onload = function()%7Bdfd.resolve();%7D%0A img.onerror = function()%7Bdfd.resolve();%7D%0A img.src = this.src;%0A%0A %7D);%0A%0A // return a master promise object which will resolve when all the deferred objects have resolved%0A // IE - when all the images are loaded%0A return $.when.apply($,dfds);%0A%0A %7D
;%0A
@@ -2967,9 +2967,8 @@
%7D%0A%7D);
-%0A
|
30984b994111903bb7f41557e9a2eeed58ccd0d2 | remove some useless code. | src/client/containers/notes/list.js | src/client/containers/notes/list.js | import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import {visibleNotesSelector} from '../../selectors/notes';
import {notesActions} from '../../actions/notes';
import {personsActions} from '../../actions/persons';
import {companiesActions} from '../../actions/companies';
import {missionsActions} from '../../actions/missions';
import {Content} from '../../components/layout';
import {AvatarView, Sort, FilterPreferred, Filter, Refresh, NewLabel, UpdatedLabel} from '../../components/widgets';
import {Header, HeaderLeft, HeaderRight, Title, TitleIcon} from '../../components/widgets';
import {AddButton} from '../../components/notes/widgets';
import {ItemNote} from '../notes';
import routes from '../../routes';
import Masonry from 'react-masonry-component';
const sortMenu = [
{key: 'createdAt', label: 'Sort by creation date'},
{key: 'updatedAt', label: 'Sort by updated date'},
];
class NotesList extends Component {
state = {}
componentWillMount = () => {
this.props.dispatch(notesActions.load())
this.props.dispatch(personsActions.load())
this.props.dispatch(companiesActions.load())
this.props.dispatch(missionsActions.load())
}
handleSort = (mode) => {
this.props.dispatch(notesActions.sort(mode))
}
handleResetFilter = () => {
this.props.dispatch(notesActions.filter(''))
}
handleRefresh = () => {
this.props.dispatch(notesActions.load({forceReload: true}))
}
handleSearchFilter = (filter) => {
this.props.dispatch(notesActions.filter(filter))
// Masonry hack for reloading layout on search
this.masonry.layout()
}
render() {
const {notes, persons, companies, missions, filter, sortCond} = this.props
if (!notes || !persons || !companies || !missions) return <div />
const listNotes = (notes, persons, companies, missions) => {
return (
notes.map((note) => {
return <ItemNote
key={note.get('_id')}
note={note}
persons={persons}
companies={companies}
missions={missions} />
}).toSetSeq()
)
}
const options = {
transitionDuration: 0,
gutter: 10,
}
return (
<Content>
<Header>
<HeaderLeft>
<TitleIcon icon={routes.notes.list.iconName} />
<Title title='Notes' />
</HeaderLeft>
<HeaderRight>
<Filter filter={filter} onReset={this.handleResetFilter} onChange={this.handleSearchFilter}/>
<Sort sortMenu={sortMenu} sortCond={sortCond} onClick={this.handleSort}/>
<Refresh onClick={this.handleRefresh} />
</HeaderRight>
</Header>
<Masonry
ref={function(c) {if (c != null) this.masonry = c.masonry;}.bind(this)}
options={options}>
{listNotes(notes, persons, companies, missions)}
</Masonry>
<AddButton title="Add a note" />
</Content>
)
}
}
export default connect(visibleNotesSelector)(NotesList)
| JavaScript | 0.000011 | @@ -1,12 +1,34 @@
+import R from 'ramda'%0A
import React
@@ -1308,92 +1308,8 @@
%7D%0A%0A
- handleResetFilter = () =%3E %7B%0A this.props.dispatch(notesActions.filter(''))%0A %7D%0A%0A
ha
@@ -1495,86 +1495,65 @@
)%0A
- // Masonry hack for reloading layout on search%0A this.masonry.layout()%0A %7D
+%7D%0A handleResetFilter = () =%3E this.handleSearchFilter('')
%0A%0A
@@ -1563,17 +1563,16 @@
der() %7B%0A
-%0A
cons
@@ -2157,25 +2157,24 @@
: 10,%0A %7D%0A
-%0A
return (
@@ -2682,100 +2682,8 @@
onry
-%0A ref=%7Bfunction(c) %7Bif (c != null) this.masonry = c.masonry;%7D.bind(this)%7D%0A
opt
|
212518a4196dacc9e663475874ae7731e871cfb6 | Update passwordToggler.js | passwordToggler.js | passwordToggler.js | function PasswordToggler($strSelector, callBack){
this.strPrefix = "";
this.strSelector = $strSelector;
this.strHandler = "click";
this.strIconShow = "fa fa-eye";
this.strIconHide = "fa fa-eye-slash";
this.strTextShow = "Show password";
this.strTextHide = "Hide password";
this.strBtnClass = "btn btn-default";
}
PasswordToggler.prototype = {
blnCreated : false,
objSelector: null,
objIcon: null,
objButton: null,
init: function(){
var $objSelector = this.setSelector();
//Bail early if selector is undefined or null
if(typeof $objSelector != "undefined" || $objSelector == null){
//Bail early if selector not of type password
if($objSelector.type !== "password"){
//console.log("Error: selector is not of type password");
return false;
}else{
if (this.blnCreated === true) {
return this;
}else{
//console.time('htmlApi');
this.htmlApi();
//console.timeEnd("htmlApiEnd");
//console.time('createMarkup');
this.createMarkup();
//console.timeEnd("createMarkupEnd");
}
}
}
//console.log('Error: selector is undefined || null');
return false;
//console.log(PasswordToggler.prototype.blnCreated, this.blnCreated);
},
htmlApi: function(){
//Cache the selector
var objSelector = this.setSelector();
if (typeof (objSelector) != "undefined" || objSelector != null) {
//Supporting some HTML API
this.strPrefix = objSelector.hasAttribute("data-prefix") ? objSelector.getAttribute("data-prefix") : this.strPrefix;
this.strHandler = objSelector.hasAttribute("data-handler") ? objSelector.getAttribute("data-handler") : this.strHandler;
this.strIconShow = objSelector.hasAttribute("data-icon-show") ? objSelector.getAttribute("data-icon-show") : this.strIconShow;
this.strIconHide = objSelector.hasAttribute("data-icon-hide") ? objSelector.getAttribute("data-icon-hide") : this.strIconHide;
this.strTextShow = objSelector.hasAttribute("data-text-show") ? objSelector.getAttribute("data-text-show") : this.strTextShow;
this.strTextHide = objSelector.hasAttribute("data-text-hide") ? objSelector.getAttribute("data-text-hide") : this.strTextHide;
this.strBtnClass = objSelector.hasAttribute("data-button-class") ? objSelector.getAttribute("data-button-class") : this.strBtnClass;
}
return this;
},
createMarkup: function() {
//reference the selector
var $objSelector = this.setSelector();
//console.log($objSelector,'asdasd');
//Create aditional markup
var objElement = document.createElement("div");
var objElementChild = document.createElement("span");
var objButton = document.createElement("button");
var objIcon = document.createElement("i");
if (typeof objElement != "undefined" && $objSelector != null) {
//Populate the object
this.objSelector = $objSelector;
//Insert into DOM
this.objSelector.parentNode.insertBefore(objElement, this.objSelector);
objElement.appendChild(this.objSelector);
objElement.appendChild(objElementChild);
objElementChild.appendChild(objButton);
objButton.appendChild(objIcon);
//Apply some styles
objElement.setAttribute("class", this.strPrefix+"input-group");
objElementChild.setAttribute("class", this.strPrefix+"input-group-btn");
objButton.setAttribute("type", "button");
objButton.setAttribute("id", this.strPrefix+"button_"+this.strSelector);
objButton.setAttribute("class", this.strBtnClass);
objButton.setAttribute("title", this.strTextShow);
objIcon.setAttribute("class", this.strIconShow);
objIcon.setAttribute("aria-hidden", "true");
//We have created the layout if we got here
this.blnCreated = true;
//populate the object
this.objIcon = objIcon;
this.objButton = objButton;
//adding eventListener
//console.time('addListener');
this.addListener(this.objSelector, this.strHandler);
//console.timeEnd('addListenerEnd');
}
//console.log(this, $objSelector, objElement, this.objButton, this.objIcon);
return this;
},
setSelector: function() {
return document.getElementById(this.strSelector);
},
togglePassword: function($element, $blnActive) {
try{
if ($element.type === "password") {
$element.type = "text";
this.objIcon.setAttribute("class", this.strIconHide);
this.objButton.setAttribute("title", this.strTextHide);
$blnActive = true;
} else {
$element.type = "password";
this.objIcon.setAttribute("class", this.strIconShow);
this.objButton.setAttribute("title", this.strTextShow);
$blnActive = false;
}
}catch(e){
Console.log(e.message);
}
return false;
},
addListener: function($element, $strListener) {
var self = this;
var objSelector = document.getElementById(this.strPrefix+"button_"+this.strSelector);
if(this.blnCreated === true){
//console.time('addEventListener');
//If the browser supports EventLIstener use it, else fall to attach event (IE)
if (objSelector.addEventListener) {
//console.log(objSelector.addEventListener);
objSelector.addEventListener(
$strListener, function(){
//console.time('togglePassword');
self.togglePassword($element);
//console.timeEnd('togglePasswordEnd');
});
}else{
objSelector.attachEvent($strListener, function(){
//console.time('togglePassword');
self.togglePassword($element);
//console.timeEnd('togglePasswordEnd');
});
}
return false;
//console.timeEnd('addEventListenerEnd');
}
}
};
| JavaScript | 0 | @@ -1,14 +1,15 @@
+
function
@@ -749,17 +749,17 @@
elector
-=
+!
= null)%7B
@@ -5798,17 +5798,73 @@
-C
+ new PasswordToggler.exception(e.message)%0A //c
onsole.l
@@ -7029,7 +7029,175 @@
-%7D;
+ %0A %7D;%0A PasswordToggler.prototype.exception = function(message) %7B%0A this.message = message;%0A this.name = %22PasswordTogglerException%22;%0A %7D
%0A
|
c52eafcd58cc7d5126ead2dddb835964aa505c8d | add live reloading to customers | src/components/HomePage/HomePage.js | src/components/HomePage/HomePage.js | import React, { PropTypes, Component } from 'react';
import styles from './HomePage.scss';
import withStyles from '../../decorators/withStyles';
import IdleScreen from '../IdleScreen';
import Passenger from '../Passenger';
import Firebase from 'firebase';
import $ from 'jquery';
@withStyles(styles)
class HomePage extends Component {
static propTypes = {
};
constructor(props){
super(props);
var self = this;
self.state = {
customers: {},
passenger: null
}
var newItems = false;
self.firebaseCustomerRef = new Firebase('https://jagertrain.firebaseio.com/customers');
self.firebaseCustomerRef.once("value", (dataSnapshot)=> {
var customers = dataSnapshot.val();
dataSnapshot.forEach(function(childSnapshot) {
var passenger = childSnapshot.val();
var img = new Image();
img.src = '/passengers/' + passenger.forename.toLowerCase() + '_' + passenger.surname.toLowerCase() + '.png';
});
self.setState({
customers: customers
});
});
self.firebaseTransactionsRef = new Firebase('https://jagertrain.firebaseio.com/transactions');
self.firebaseTransactionsRef.on("child_added", (transaction)=> {
if (!newItems) return;
var passenger = this.state.customers[transaction.val().customer];
if (typeof passenger === "undefined") {
console.log('id not recognised');
return;
}
let audio = new Audio(`/sounds/clip_${Math.floor((Math.random() * 7) + 1)}.ogg`);
audio.play();
var $IdleScreem = $('.IdleScreen').addClass("spin-out");
passenger.imageUrl = '/passengers/' + passenger.forename.toLowerCase() + '-' + passenger.surname.toLowerCase() + '.png';
setTimeout(function(){
self.setState({
passenger: passenger
});
setTimeout(function(){
var $Passenger = $('.Passenger');
$Passenger.fadeOut(1000, function() {
self.setState({
passenger: null
});
});
}, 5000);
}, 2000);
});
this.firebaseTransactionsRef.once('value', (dataSnapshot) => {
newItems = true;
});
self.firebaseSoundPlaysRef = new Firebase('https://jagertrain.firebaseio.com/soundplays');
self.firebaseSoundPlaysRef.on('child_changed', (soundPlay) => {
var id = soundPlay.val();
let audio = new Audio(`/sounds/clip_${id}.ogg`);
audio.play();
});
}
static contextTypes = {
onSetTitle: PropTypes.func.isRequired,
};
render() {
const title = 'Riskdisk Jagertrain 2015';
this.context.onSetTitle(title);
if (this.state.passenger) {
return (
<div className="HomePage">
<div className="HomePage-container">
<Passenger passenger={this.state.passenger} />
</div>
</div>
);
}
else {
return (
<div className="IdleScreen-wrapper">
<IdleScreen />
<h2>All Aboard!!! #RDJT</h2>
</div>
)
}
}
}
export default HomePage;
| JavaScript | 0 | @@ -1038,32 +1038,719 @@
%7D);%0A %7D);%0A%0A
+ self.firebaseCustomerRef.on(%22child_added%22, (customer)=%3E %7B%0A if (self.state.customers%5Bcustomer.key()%5D) return null;%0A%0A let customerVal = customer.val();%0A customerVal.key = customer.key;%0A self.state.customers%5BcustomerVal.key%5D = customerVal;%0A self.setState(%7B%0A customers: self.state.customers%0A %7D);%0A %7D);%0A%0A self.firebaseCustomerRef.on(%22child_changed%22, (customer)=%3E %7B%0A if (!self.state.customers%5Bcustomer.key()%5D) return null;%0A%0A let customerVal = customer.val();%0A customerVal.key = customer.key;%0A self.state.customers%5BcustomerVal.key%5D = customerVal;%0A self.setState(%7B%0A customers: self.state.customers%0A %7D);%0A %7D);%0A%0A
self.firebas
|
4f17de7379a358ecaaca5108e0174d1035680bbd | fix test | test/fixtures/tag.js | test/fixtures/tag.js | module.exports = `
acyort.builder.register(['archives', 'archives'])
acyort.builder.extension = 'swig'
`
| JavaScript | 0.000002 | @@ -19,23 +19,24 @@
%0Aacyort.
-builder
+template
.registe
@@ -74,15 +74,16 @@
ort.
-builder
+template
.ext
|
1f548b577dc073c7b10de99cb5b7d8cf4464dafe | Remove proximity test | test/geocode.test.js | test/geocode.test.js | var fs = require('fs');
var util = require('util');
var Carmen = require('..');
var UPDATE = process.env.UPDATE;
var test = require('tape');
test('geocode', function(t) {
var geocoder = new Carmen({
country: Carmen.auto(__dirname + '/fixtures/01-ne.country.s3'),
province: Carmen.auto(__dirname + '/fixtures/02-ne.province.s3')
});
t.test ('phrasematch 0.5 relev', function(q) {
geocoder.geocode('czech', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-phraserelev.json', JSON.stringify(res, null, 4));
q.deepEqual(res, require(__dirname + '/fixtures/geocode-phraserelev.json'));
q.end();
});
});
t.test ('forward', function(q) {
geocoder.geocode('georgia', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-forward.json', JSON.stringify(res, null, 4));
q.deepEqual(res, require(__dirname + '/fixtures/geocode-forward.json'));
q.end();
});
});
t.test ('forward + by id', function(q) {
geocoder.geocode('country.38', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/search-ident.json', JSON.stringify(res, null, 4));
q.deepEqual(res, require(__dirname + '/fixtures/search-ident.json'));
q.end();
});
});
t.test ('forward + geocoder_tokens', function(q) {
geocoder.geocode('n korea', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-forward-tokens.json', JSON.stringify(res, null, 4));
q.deepEqual(res, require(__dirname + '/fixtures/geocode-forward-tokens.json'));
q.end();
});
});
t.test ('proximity geocoding', function(q) {
geocoder.geocode('saint john', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-without-proximity.json', JSON.stringify(res, null, 4));
q.equal(res.features[0].place_name, require(__dirname + '/fixtures/geocode-without-proximity.json').features[0].place_name, res);
geocoder.geocode('saint john', { proximity: [13.177876,-59.504401]}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-with-proximity.json', JSON.stringify(res, null, 4));
q.equal(res.features[0].place_name, require(__dirname + '/fixtures/geocode-with-proximity.json').features[0].place_name, res);
q.end();
});
});
});
t.test ('string proximity geocoding', function(q) {
geocoder.geocode('n korea', { proximity: "13.177876"}, function(err, res) {
q.ifError(!err);
q.end();
});
});
t.test ('invalid proximity length', function(q) {
geocoder.geocode('saint john', { proximity: [98.177876]}, function(err, res) {
q.ifError(!err);
q.end();
});
});
t.test ('invalid proximity lat', function(q) {
geocoder.geocode('n korea', { proximity: [98.177876,-59.504401]}, function(err, res) {
q.ifError(!err);
q.end();
});
});
t.test ('invalid proximity lon', function(q) {
geocoder.geocode('new york', { proximity: [58.177876,-200.504401]}, function(err, res) {
q.ifError(!err);
q.end();
});
});
t.test ('text in proximity field', function(q) {
geocoder.geocode('usa', { proximity: ["58d.177876","-200.5044s01"]}, function(err, res) {
q.ifError(!err);
q.end();
});
});
t.test ('reverse', function(q) {
geocoder.geocode('0, 40', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-reverse.json', JSON.stringify(res, null, 4));
q.deepEqual(require(__dirname + '/fixtures/geocode-reverse.json'), res);
q.end();
});
});
t.test ('noresults', function(q) {
geocoder.geocode('asdfasdf', {}, function(err, res) {
q.ifError(err);
if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-noresults.json', JSON.stringify(res, null, 4));
q.deepEqual(require(__dirname + '/fixtures/geocode-noresults.json'), res);
q.end();
});
});
t.end();
});
| JavaScript | 0.000002 | @@ -1893,886 +1893,8 @@
%7D);%0A
- t.test ('proximity geocoding', function(q) %7B%0A geocoder.geocode('saint john', %7B%7D, function(err, res) %7B%0A q.ifError(err);%0A if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-without-proximity.json', JSON.stringify(res, null, 4));%0A q.equal(res.features%5B0%5D.place_name, require(__dirname + '/fixtures/geocode-without-proximity.json').features%5B0%5D.place_name, res);%0A geocoder.geocode('saint john', %7B proximity: %5B13.177876,-59.504401%5D%7D, function(err, res) %7B%0A q.ifError(err);%0A if (UPDATE) fs.writeFileSync(__dirname + '/fixtures/geocode-with-proximity.json', JSON.stringify(res, null, 4));%0A q.equal(res.features%5B0%5D.place_name, require(__dirname + '/fixtures/geocode-with-proximity.json').features%5B0%5D.place_name, res);%0A q.end();%0A %7D);%0A %7D);%0A %7D);%0A
|
906cfa81f2509da651e3f40c4a2580be3535b733 | comment cleanup | src/components/NumericInput.spec.js | src/components/NumericInput.spec.js | // the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */
import React from 'react';
import { shallow } from 'enzyme';
import chai from 'chai';
import NumericInput from './NumericInput';
const expect = chai.expect;
/* *****************************************************************************
in terms of basic markup, the NumericInput component
should be a div.form-group
should include an input[type="text"]
should include an input.form-control
should include a label with the appropriate text if a label is specified
should include a placeholder if a placeholder is specified
*/
describe('in terms of basic markup, the NumericInput component', () => {
it('should be a div.form-group', () => {
const component = shallow(<NumericInput />);
expect(component.is('div.form-group')).to.equal(true);
});
it('should include an input[type="text"]', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input[type="text"]').length).to.equal(1);
});
it('should include an input.form-control', () => {
const component = shallow(<NumericInput />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input.form-control').length).to.equal(1);
});
it('should include a label with the appropriate text if a label is specified', () => {
const label = 'some label';
const component = shallow(<NumericInput label={label} />);
expect(component.find('Label').length).to.equal(1);
expect(component.find('Label').props().label).to.equal(label);
});
it('should include a placeholder if a placeholder is specified', () => {
const placeholder = 'a number goes here';
const component = shallow(<NumericInput placeholder={placeholder} />);
expect(component.find('input').length).to.equal(1);
expect(component.find('input').props().placeholder).to.equal(placeholder);
});
});
| JavaScript | 0 | @@ -770,16 +770,320 @@
ecified%0A
+ should include a label with the the required flag if a label is specified & required is set%0A should not include a label with the the required flag if a label is specified & required is not set%0A should not include a label with the the required flag if a label is not specified & required is set%0A
*/%0Adescr
|
edbf526aeca5f2f38dbe1c042bb1d1cabe72db24 | Remove indirect Symbol polyfill requirement | src/components/ObserverContainer.js | src/components/ObserverContainer.js | // based on @researchgate/react-intersection-observer
import { parseRootMargin, shallowCompareOptions } from '../lib/utils'
export function getPooled(options = {}) {
const root = options.root || null
const rootMargin = parseRootMargin(options.rootMargin)
const threshold = Array.isArray(options.threshold)
? options.threshold
: [options.threshold != null ? options.threshold : 0]
for (const observer of storage.keys()) {
const unmatched = [
[root, observer.root],
[rootMargin, observer.rootMargin],
[threshold, observer.thresholds],
].some(option => shallowCompareOptions(...option))
if (!unmatched) {
return observer
}
}
return null
}
export const storage = new Map()
export default class ObserverContainer {
static create(callback, options) {
return getPooled(options) || new IntersectionObserver(callback, options)
}
static findElement(entry, observer) {
const elements = storage.get(observer)
if (elements) {
for (const element of elements.values()) {
if (element.target === entry.target) {
return element
}
}
}
return null
}
static observe(element) {
let targets
if (storage.has(element.observer)) {
targets = storage.get(element.observer)
} else {
targets = new Set()
storage.set(element.observer, targets)
}
targets.add(element)
element.observer.observe(element.target)
}
static unobserve(element) {
if (storage.has(element.observer)) {
const targets = storage.get(element.observer)
if (targets.delete(element)) {
if (targets.size > 0) {
element.observer.unobserve(element.target)
} else {
element.observer.disconnect()
storage.delete(element.observer)
}
}
}
}
static clear() {
storage.clear()
}
static count() {
return storage.size
}
}
| JavaScript | 0 | @@ -403,29 +403,24 @@
d : 0%5D%0A%0A
-for (
const observ
@@ -421,19 +421,19 @@
observer
- of
+s =
storage
@@ -439,16 +439,103 @@
e.keys()
+%0A%0A for (let observer = observers.next(); !observer.done; observer = observers.next()
) %7B%0A
@@ -555,18 +555,16 @@
atched =
- %5B
%0A
@@ -572,44 +572,94 @@
-%5Broot, observer.root%5D,%0A %5B
+shallowCompareOptions(root, observer.value.root) %7C%7C%0A shallowCompareOptions(
root
@@ -675,16 +675,22 @@
bserver.
+value.
rootMarg
@@ -691,18 +691,20 @@
otMargin
-%5D,
+) %7C%7C
%0A
@@ -708,17 +708,38 @@
-%5B
+shallowCompareOptions(
threshol
@@ -750,16 +750,22 @@
bserver.
+value.
threshol
@@ -769,69 +769,8 @@
hold
-s%5D,%0A %5D.some(option =%3E shallowCompareOptions(...option)
)%0A%0A
@@ -821,16 +821,22 @@
observer
+.value
%0A
@@ -1118,25 +1118,33 @@
const
-e
+observerE
lements = st
@@ -1155,32 +1155,33 @@
e.get(observer)%0A
+%0A
if (elem
@@ -1172,25 +1172,33 @@
if (
-e
+observerE
lements) %7B%0A
@@ -1208,21 +1208,16 @@
-for (
const el
@@ -1225,13 +1225,21 @@
ment
- of e
+s = observerE
leme
@@ -1250,16 +1250,106 @@
values()
+%0A%0A for (let element = elements.next(); !element.done; element = elements.next()
) %7B%0A
@@ -1368,24 +1368,30 @@
if (element.
+value.
target === e
@@ -1439,16 +1439,22 @@
element
+.value
%0A
|
b1befcf2041910f2651e3f0e435d7c172457ccb9 | Fix string concatenation for showProgress | src/components/Tooltip/Container.js | src/components/Tooltip/Container.js | import React from 'react';
import PropTypes from 'prop-types';
import CloseBtn from './CloseBtn';
const JoyrideTooltipContainer = ({
continuous,
backProps,
closeProps,
primaryProps,
skipProps,
index,
isLastStep,
setTooltipRef,
size,
step,
}) => {
const { content, hideBackButton, locale, showProgress, showSkipButton, title, styles } = step;
const { back, close, last, next, skip } = locale;
const output = {
primary: close,
};
if (continuous) {
if (isLastStep) {
output.primary = last;
}
else {
output.primary = next;
}
if (showProgress) {
output.primary += ` (${index + 1}/${size})`;
}
}
if (showSkipButton && !isLastStep) {
output.skip = (
<button
style={styles.buttonSkip}
type="button"
{...skipProps}
>
{skip}
</button>
);
}
if (!hideBackButton && index > 0) {
output.back = (
<button
style={styles.buttonBack}
type="button"
{...backProps}
>
{back}
</button>
);
}
output.close = (<CloseBtn {...closeProps} styles={styles.buttonClose} />);
return (
<div
key="JoyrideTooltip"
ref={setTooltipRef}
style={styles.tooltip}
>
<div style={styles.tooltipContainer}>
{output.close}
{title && (<h4 style={styles.tooltipTitle}>{title}</h4>)}
{!!content && (
<div style={styles.tooltipContent}>
{content}
</div>
)}
</div>
<div style={styles.tooltipFooter}>
{output.skip}
{output.back}
<button
style={styles.buttonNext}
type="button"
{...primaryProps}
>
{output.primary}
</button>
</div>
</div>
);
};
JoyrideTooltipContainer.propTypes = {
backProps: PropTypes.object.isRequired,
closeProps: PropTypes.object.isRequired,
continuous: PropTypes.bool.isRequired,
index: PropTypes.number.isRequired,
isLastStep: PropTypes.bool.isRequired,
primaryProps: PropTypes.object.isRequired,
setTooltipRef: PropTypes.func.isRequired,
size: PropTypes.number.isRequired,
skipProps: PropTypes.object.isRequired,
step: PropTypes.object.isRequired,
};
export default JoyrideTooltipContainer;
| JavaScript | 0.000875 | @@ -484,106 +484,50 @@
-if (isLastStep) %7B%0A output.primary = last;%0A %7D%0A else %7B%0A output.primary = next;%0A %7D
+output.primary = isLastStep ? last : next;
%0A%0A
@@ -573,15 +573,34 @@
ary
-+
=
-%60
+%3Cspan%3E%7Boutput.primary%7D
(
-$
%7Bind
@@ -611,17 +611,22 @@
1%7D/
-$
%7Bsize%7D)
-%60
+%3C/span%3E
;%0A
|
5ba27204d584301e716122c84bfe55f18fb45f19 | clean some commented code | src/components/Utils/FirebaseApi.js | src/components/Utils/FirebaseApi.js | import storage from 'key-storage';
import INITIAL_STATE from '../../INITIAL_STATE';
import fbConfig from '../../fbConfig';
import firebase from 'firebase';
firebase.initializeApp(fbConfig);
var DB = firebase.database();
class FirebaseApi {
constructor() {
}
getTodos(status_filter = [], priorities_filter = []) {
return DB.ref('todos').once('value').then((snapshot) => {
return snapshot.val();
});
}
useFilters(todos, status_filter = [], priorities_filter = []) {
/*todos = todos.filter((obj, i) => {
return status_filter.indexOf(parseInt(obj.status)) != -1 || priorities_filter.indexOf(parseInt(obj.priority)) != -1;
});*/
return todos;
}
getTodo(id) {
return DB.ref(`todos/${id}/`).once('value').then((snapshot) => {
return snapshot.val();
});
}
createTodo(todo) {
let newTodo = DB.ref('todos').push();
let newId = newTodo.getKey();
todo.id = newId;
newTodo.set(todo);
return newId;
}
deleteTodo(id) {
return DB.ref(`todos/${id}`).remove();
}
updateTodo(id, todo) {
return DB.ref(`todos/${id}`).update(todo);
}
getKey(key) {
return storage.gey(key);
}
setKey(key, val) {
storage.set(key, val);
return;
}
deleteKey(key) {
storage.remove(key);
return;
}
}
export default new FirebaseApi();
| JavaScript | 0.000001 | @@ -240,32 +240,8 @@
%7B%0A%0A
- constructor() %7B%0A%0A %7D%0A%0A
ge
@@ -401,271 +401,8 @@
%7D%0A%0A
- useFilters(todos, status_filter = %5B%5D, priorities_filter = %5B%5D) %7B%0A /*todos = todos.filter((obj, i) =%3E %7B%0A return status_filter.indexOf(parseInt(obj.status)) != -1 %7C%7C priorities_filter.indexOf(parseInt(obj.priority)) != -1;%0A %7D);*/%0A return todos;%0A %7D%0A%0A
ge
|
a8537e6386e0906db044d1f00a2b82ec59c13570 | use fixed position for global backdrops. | src/components/backdrop/backdrop.js | src/components/backdrop/backdrop.js | /*
* @ngdoc module
* @name material.components.backdrop
* @description Backdrop
*/
/**
* @ngdoc directive
* @name mdBackdrop
* @module material.components.backdrop
*
* @restrict E
*
* @description
* `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet.
* Apply class `opaque` to make the backdrop use the theme backdrop color.
*
*/
angular
.module('material.components.backdrop', ['material.core'])
.directive('mdBackdrop', function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) {
var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container.";
return {
restrict: 'E',
link: postLink
};
function postLink(scope, element, attrs) {
// If body scrolling has been disabled using mdUtil.disableBodyScroll(),
// adjust the 'backdrop' height to account for the fixed 'body' top offset
var body = $window.getComputedStyle($document[0].body);
if (body.position == 'fixed') {
var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10));
element.css({
height: hViewport + 'px'
});
}
// backdrop may be outside the $rootElement, tell ngAnimate to animate regardless
if ($animate.pin) $animate.pin(element, $rootElement);
$$rAF(function () {
// Often $animate.enter() is used to append the backDrop element
// so let's wait until $animate is done...
var parent = element.parent()[0];
if (parent) {
var styles = $window.getComputedStyle(parent);
if (styles.position == 'static') {
// backdrop uses position:absolute and will not work properly with parent position:static (default)
$log.warn(ERROR_CSS_POSITION);
}
}
$mdTheming.inherit(element, element.parent());
});
}
});
| JavaScript | 0 | @@ -1595,24 +1595,130 @@
(parent) %7B%0A
+%0A if ( parent.nodeName == 'BODY' ) %7B%0A element.css(%7Bposition : 'fixed'%7D);%0A %7D%0A%0A
va
|
5cc7e868dfb3ad719b0113e0eae5d1b5b6a07200 | Update HomePage.js | src/modules/core/components/HomePage.js | src/modules/core/components/HomePage.js | import React from "react";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
import injectSheet from "react-jss";
import { Grid, Row, Col } from "react-bootstrap/lib";
import {
FeaturedArticle,
RecommendedArticles,
LatestArticlesRibbon,
LeftColumn,
RightColumn,
} from "../../articles/components/summaries";
import { SectionFeature, SectionColumn } from "../../sections/components";
const HomePageQuery = gql`
query HomePageQuery {
featuredArticle {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
title
media_type
attachment_url
medium_attachment_url
thumb_attachment_url
}
section {
name
permalink
}
}
columnArticles {
title
slug
preview
created_at
contributors {
first_name
last_name
slug
}
media {
attachment_url
}
section {
name
permalink
}
}
}
`;
const styles = {
HomePage: {
margin: "23px 0px 13px",
},
recommendedArticles: {
padding: 0,
},
primaryComponents: {
borderRight: "solid 1px #ddd",
marginBottom: "19px",
paddingRight: "14px",
},
"@media (max-width: 991px)": {
primaryComponents: {
borderRight: "none",
paddingRight: 0,
},
},
"@media (max-width: 767px)": {
skinnyCol: {
padding: "0 !important",
},
},
adbanner: {
fontFamily: "Circular Std",
marginTop: "0%",
margin: "auto",
},
"@media screen and (min-width: 769px)": {
adbanner: {
display: "none",
},
},
};
const HomePage = ({ classes, data }) => {
if (data.loading) {
return null;
}
const { featuredArticle, columnArticles } = data;
const firstColumnSectionSlugs = ["opinions", "features", "humor"];
const secondColumnSectionSlugs = [
"staff-editorials",
"ae",
"sports-at-stuyvesant",
];
return (
<div>
<Grid fluid>
<Row>
<center>
<div className={classes.adbanner}>
<h1 className="col-md-12 container-fluid">
Check out the promotions on the bottom of the page!
</h1>
</div>
</center>
<Col
xs={12}
sm={12}
md={9}
lg={9}
className={classes.primaryComponents}
>
<FeaturedArticle article={featuredArticle} />
<SectionFeature slug={"sing!"} />
</Col>
<Col
xsHidden
smHidden
md={3}
lg={3}
className={classes.recommendedArticles}
>
<RecommendedArticles />
</Col>
</Row>
<Row>
<Col xsHidden sm={12} md={12} lg={12}>
<LatestArticlesRibbon className={classes.latestArticlesRibbon} />
</Col>
</Row>
<Row>
<LeftColumn articles={columnArticles.slice(0, 3)} />
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={firstColumnSectionSlugs} />
</Col>
<Col xs={12} sm={3} md={3} lg={3} className={classes.skinnyCol}>
<SectionColumn slugs={secondColumnSectionSlugs} />
</Col>
<RightColumn articles={columnArticles.slice(3)} />
</Row>
</Grid>
</div>
);
};
export default graphql(HomePageQuery)(injectSheet(styles)(HomePage));
| JavaScript | 0 | @@ -2578,13 +2578,12 @@
g=%7B%22
-sing!
+news
%22%7D /
|
18d70ee9f03026a0435d85dbd299f3d9e7cae3fd | test exit code of info command | test/info-command.js | test/info-command.js | const assert = require('assert')
const path = require('path')
const z1 = require('..')
const { works } = require('./lib/command')
const {
TIMEOUT,
KILL_TIMEOUT
} = require('./lib/config')
describe('info command', function () {
this.timeout(TIMEOUT)
describe('option', function () {
before(async function () {
await z1.start('test-app/basic', [], {
workers: 1
})
})
after(async function () {
await z1.stop('basic', {
timeout: KILL_TIMEOUT
})
})
/**
* Test if the given option outputs the expected result
* @param {string} optionName
* @param {string} expectedResult
*/
function checkOption(optionName, expectedResult) {
describe(optionName, function () {
it('should output the directory of the app', async function () {
const result = await works('z1 info basic ' + optionName)
assert.strictEqual(result.out, expectedResult + '\n')
})
})
}
checkOption('--available', '1')
checkOption('--dir', path.resolve('test-app/basic'))
checkOption('--killed', '0')
checkOption('--name', 'basic')
checkOption('--pending', '0')
checkOption('--ports', '8080')
checkOption('--revive-count', '0')
})
})
| JavaScript | 0.000001 | @@ -255,45 +255,8 @@
T)%0A%0A
- describe('option', function () %7B%0A
be
@@ -276,34 +276,32 @@
nction () %7B%0A
-
await z1.start('
@@ -329,18 +329,16 @@
%7B%0A
-
workers:
@@ -344,31 +344,25 @@
: 1%0A
-
%7D)%0A
-
-
%7D)%0A%0A
-
after(
@@ -385,18 +385,16 @@
) %7B%0A
-
-
await z1
@@ -406,26 +406,24 @@
('basic', %7B%0A
-
timeou
@@ -446,20 +446,152 @@
+%7D)%0A
%7D)%0A
+%0A
- %7D)%0A
+it('should not exit with an exit code', async function () %7B%0A await works('z1 info basic')%0A %7D)%0A%0A describe('option', function () %7B
%0A
@@ -840,25 +840,25 @@
%0A it(
-'
+%60
should outpu
@@ -867,17 +867,21 @@
the
-directory
+$%7BoptionName%7D
of
@@ -887,17 +887,17 @@
the app
-'
+%60
, async
@@ -939,33 +939,33 @@
t = await works(
-'
+%60
z1 info basic '
@@ -966,12 +966,12 @@
sic
-' +
+--$%7B
opti
@@ -976,16 +976,18 @@
tionName
+%7D%60
)%0A
@@ -1088,18 +1088,16 @@
Option('
---
availabl
@@ -1122,18 +1122,16 @@
Option('
---
dir', pa
@@ -1177,18 +1177,16 @@
Option('
---
killed',
@@ -1208,18 +1208,16 @@
Option('
---
name', '
@@ -1241,18 +1241,16 @@
Option('
---
pending'
@@ -1273,18 +1273,16 @@
Option('
---
ports',
@@ -1306,18 +1306,16 @@
Option('
---
revive-c
|
dec236142e9a5d25ee10f1dcc26bf126a9af26bc | Fix test regression | test/linters/less.js | test/linters/less.js | var expect = require('unexpected'),
Path = require('path'),
fs = require('fs'),
less = require('../../lib/linters/less');
/*global describe, it*/
function loadTestCase(lessFileName, cb) {
var lessPath = Path.resolve(__dirname, 'less', lessFileName);
fs.readFile(lessPath, 'utf-8', function (err, lessStr) {
if (err) {
return cb(err);
}
less(lessPath, lessStr, {}, cb);
});
}
describe('less', function () {
it('should produce an error when a missing file is referenced in an @import', function (done) {
loadTestCase('importedFileNotFound.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', '"notFound.less" wasn\'t found.');
done(err);
});
});
it('should produce an error when a file has a syntax error', function (done) {
loadTestCase('syntaxError.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an imported file has a syntax error', function (done) {
loadTestCase('syntaxErrorInImportedFile.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'missing opening `{`.');
expect(results[0].filename, 'to equal', Path.resolve(__dirname, 'less', 'syntaxError.less'));
done(err);
});
});
it('should produce an error when an undefined variable is referenced', function (done) {
loadTestCase('undefinedVariableReferenced.less', function (err, results) {
expect(results, 'to be an array');
expect(results, 'to have length', 1);
expect(results[0].message, 'to equal', 'variable @foo is undefined.');
done(err);
});
});
});
| JavaScript | 0.000018 | @@ -787,17 +787,18 @@
qual', '
-%22
+%5C'
notFound
@@ -806,9 +806,10 @@
less
-%22
+%5C'
was
|
13fbe91c30cdef4b10ee86c79aaadd7487623b5c | Test fix | test/mocha/base10.js | test/mocha/base10.js | var assert = require('assert');
var base = require('./../../index.js');
describe('base10', function (){
describe('js', function (){
var base10 = base[10].js;
describe('base2', function (){
it('returns {string}1111 when arg1={int}15', function (){
assert.equal(base10[2](15), '1111');
});
it('returns {string}1111 when arg1={string}15', function (){
assert.equal(base10[2]('15'), '1111');
});
it('returns {string}1111110100010 when arg1={int}15', function (){
assert.equal(base10[2](8098), '1111110100010');
});
it('returns {string}1111110100010 when arg1={string}8098', function (){
assert.equal(base10[2]('8098'), '1111110100010');
});
});
describe('base16', function (){
it('returns {string}500f86 when arg1={int}5246854', function (){
assert.equal(base10[16](5246854), '500f86');
});
it('returns {string}500f86 when arg1={string}5246854', function (){
assert.equal(base10[16]('5246854'), '500f86');
});
it('returns {string}499602d2 when arg1={int}1234567890', function (){
assert.equal(base10[16](1234567890), '499602d2');
});
it('returns {string}499602d2 when arg1={string}1234567890', function (){
assert.equal(base10[16]('1234567890'), '499602d2');
});
});
});
describe('cpp', function (){
var base10 = base[10].cpp;
describe('base2', function (){
it('returns {string}1111 when arg1={int}15', function (){
assert.equal(base10[2](15), '1111');
});
it('returns {string}1111 when arg1={string}15', function (){
assert.equal(base10[2]('15'), '1111');
});
it('returns {string}1111110100010 when arg1={int}15', function (){
assert.equal(base10[2](8098), '1111110100010');
});
it('returns {string}1111110100010 when arg1={string}8098', function (){
assert.equal(base10[2]('8098'), '1111110100010');
});
});
/*
describe('base16', function (){
it('returns {string}500f86 when arg1={int}5246854', function (){
assert.equal(base10[16](5246854), '500f86');
});
it('returns {string}500f86 when arg1={string}5246854', function (){
assert.equal(base10[16]('5246854'), '500f86');
});
it('returns {string}499602d2 when arg1={int}1234567890', function (){
assert.equal(base10[16](1234567890), '499602d2');
});
it('returns {string}499602d2 when arg1={string}1234567890', function (){
assert.equal(base10[16]('1234567890'), '499602d2');
});
});
*/
});
});
| JavaScript | 0.000001 | @@ -1985,24 +1985,29 @@
%7D);%0A %7D);%0A
+ %0A
/*%0A d
|
112e38a232389471c602bc6499605cda1472b6ff | Add a test case | test/mongodb.test.js | test/mongodb.test.js | // This test written in mocha+should.js
var should = require('./init.js');
var User, Post, db;
describe('mongodb', function(){
before(function() {
db = getDataSource();
User = db.define('User', {
name: { type: String, index: true },
email: { type: String, index: true },
age: Number,
});
Post = db.define('Post', {
title: { type: String, length: 255, index: true },
content: { type: String }
});
User.hasMany(Post);
Post.belongsTo(User);
});
beforeEach(function(done) {
User.destroyAll(function() {
Post.destroyAll(function() {
done();
});
});
});
it('hasMany should support additional conditions', function (done) {
User.create(function (e, u) {
u.posts.create({}, function (e, p) {
u.posts({where: {_id: p.id}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
done();
});
});
});
});
it('should allow to find by id string', function (done) {
Post.create(function (err, post) {
Post.find(post.id.toString(), function (err, post) {
should.not.exist(err);
should.exist(post);
done();
});
});
});
it('find should return an object with an id, which is instanceof ObjectId', function (done) {
Post.create(function (err, post) {
Post.findById(post.id, function (err, post) {
should.not.exist(err);
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return object with an id, which is instanceof ObjectID', function (done) {
var post = new Post({title: 'a', content: 'AAA'})
post.save(function (err, post) {
Post.all({where: {title: 'a'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'a');
post.should.have.property('content', 'AAA');
post.id.should.be.an.instanceOf(db.ObjectID);
post._id.should.be.an.instanceOf(db.ObjectID);
done();
});
});
});
it('all should return honor filter.fields', function (done) {
var post = new Post({title: 'b', content: 'BBB'})
post.save(function (err, post) {
Post.all({fields: ['title'], where: {title: 'b'}}, function (err, posts) {
should.not.exist(err);
posts.should.have.lengthOf(1);
post = posts[0];
post.should.have.property('title', 'b');
post.should.not.have.property('content');
done();
});
});
});
after(function(done){
User.destroyAll(function(){
Post.destroyAll(done);
});
});
});
| JavaScript | 0.99959 | @@ -84,16 +84,23 @@
r, Post,
+ Post1,
db;%0A%0Ade
@@ -522,32 +522,225 @@
%7D%0A %7D);%0A%0A
+ Post1 = db.define('Post1', %7B%0A id: %7Btype: String, id: true%7D,%0A title: %7B type: String, length: 255, index: true %7D,%0A content: %7B type: String %7D%0A %7D);%0A%0A
User.has
@@ -3334,24 +3334,424 @@
);%0A %7D);%0A%0A
+ it('create should convert id from string to ObjectID if format matches',%0A function(done) %7B%0A var oid = new db.ObjectID().toString();%0A Post1.create(%7Bid: oid, title: 'c', content: 'CCC'%7D, function (err, post) %7B%0A Post1.findById(oid, function (err, post) %7B%0A should.not.exist(err);%0A post.id.should.be.equal(oid);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A
after(fu
|
4b2c28201203fecd0f829597c041ca242eaea081 | fix ids when constructing relationships | src/node_modules/read-csv-data/index.js | src/node_modules/read-csv-data/index.js | var fs = require('fs')
var Path = require('path')
var mapValues = require('lodash.mapvalues')
var parseInput = require('csv-parser')
var runAuto = require('run-auto')
var through = require('through2')
var uuid = require('node-uuid')
var assign = require('lodash.assign')
var Url = require('url')
var config = require('config')
var debug = require('debug')('holodex:read-csv-data')
var store = require('base/store')
var types = require('types')
var typesByCollection = types.indexedByCollection
module.exports = readData
function readData (opts, cb) {
var graph = []
var tasks = mapValues(typesByCollection, function (type, collectionName) {
return getCollection({
dir: opts.dir,
type: type,
collectionName: collectionName,
graph: graph
})
})
runAuto(tasks, function (err) {
if (err) { return cb(err) }
cb(null, graph)
})
}
function getCollection (opts) {
var task = [function (cb, results) {
debug('starting', opts.collectionName)
readCollection({
dir: opts.dir,
collectionName: opts.collectionName
})
.pipe(trimify())
.pipe(typify(opts.collectionName, opts.graph))
.on('end', function () {
debug('finished', opts.collectionName)
cb()
})
.on('error', cb)
.resume()
}]
if (opts.collectionName === 'relationships') {
task.unshift('people', 'groups', 'roleTypes', 'relationshipTypes', 'linkTypes')
}
return task
}
function readCollection (opts) {
var fileName = Path.join(opts.dir, opts.collectionName + '.csv')
var stream = fs.createReadStream(fileName)
stream.on('error', function (err) {
// if file not found, end stream
// TODO check for specific error
console.log(err.message)
this.push(null)
})
return stream.pipe(parseInput())
}
function trimify () {
return through.obj(function (data, enc, cb) {
cb(null, mapValues(data, function (val) {
return val.trim()
}))
})
}
function typify (collectionName, graph) {
var type = types.indexedByCollection[collectionName]
var Model = type.Model
// hard-coded parsers for types of data
// TODO fix HACK
var parsers = {
Role: function parseRole (attrs) {
return {
id: 'roles/' + uuid(),
type: 'roleTypes/' + attrs.role,
agent: 'people/' + attrs.agent
}
},
RoleType: function parseRoleType (attrs) {
return assign(attrs, {
relationshipType: 'relationshipTypes/' + attrs.relationshipType
})
},
LinkType: function parseLinkType (attrs) {
return assign(attrs, {
relationshipType: 'relationshipTypes/' + attrs.relationshipType,
source: 'roleTypes/' + attrs.source,
target: 'roleTypes/' + attrs.target
})
},
Relationship: function parseRelationship (attrs) {
var apiUrl = Url.format(config.api.url)
var linkType = store.findById(apiUrl + '/linkTypes/' + attrs.link)
var relId = 'relationships/' + uuid()
var sourceRole = Model.new({
'@id': uuid(),
'@type': 'Role',
type: linkType.source.getId(),
agent: findAgent(attrs.source).getId(),
relationship: relId
})
var targetRole = Model.new({
'@id': uuid(),
'@type': 'Role',
type: linkType.target.getId(),
agent: findAgent(attrs.target).getId(),
relationship: relId
})
graph.push(sourceRole, targetRole)
return {
id: uuid(),
type: linkType.relationshipType.getId(),
}
}
}
return through.obj(function (attrs, enc, cb) {
var type = Model.prototype.getType()
if (parsers[type]) {
attrs = parsers[type](attrs)
}
if (attrs.id == null) {
attrs.id = uuid()
}
// rename idAttribute to '@id'
attrs['@id'] = collectionName + '/' + attrs.id
delete attrs.id
// add '@type' attribute
attrs['@type'] = type
var model = Model.new(attrs)
model.save()
graph.push(model)
cb(null, model)
})
}
function print () {
return through.obj(function (model, enc, cb) {
console.log(model.toJSON())
cb()
})
}
function findAgent (id) {
var apiUrl = Url.format(config.api.url)
return store.findById(apiUrl + '/people/' + id) ||
store.findById(apiUrl + '/groups/' + id)
}
| JavaScript | 0.000015 | @@ -3001,32 +3001,43 @@
%7B%0A '@id':
+ 'roles/' +
uuid(),%0A
@@ -3021,32 +3021,32 @@
les/' + uuid(),%0A
-
'@type':
@@ -3227,16 +3227,27 @@
'@id':
+ 'roles/' +
uuid(),
@@ -3446,32 +3446,32 @@
%0A return %7B%0A
-
id: uuid
@@ -3465,16 +3465,35 @@
id:
+ 'relationships/' +
uuid(),
|
d2a2e43c5e5561ab1601e64fcfbfe8be864eda5e | Remove erroneous semicolon in security test script | test/security/pwn.js | test/security/pwn.js | (function(){
var message = 'Ya been pwned by an XSS from an unsanitized script tag injection.';
if(alertify){
alertify.error(message);
} else {
document.body.innerHTML = '<h1>' + message + '</h1>';
};
})();
| JavaScript | 0.99886 | @@ -208,16 +208,15 @@
1%3E';%0A %7D
-;
%0A%7D)();%0A
|
2561595f61aaffbd4fbb653128a7d36321e96308 | fix body-copying behavior on GET and HEAD requests in some browsers | src/http-client.js | src/http-client.js | import {HttpClientConfiguration} from './http-client-configuration';
import {RequestInit, Interceptor} from './interfaces';
import 'core-js';
/**
* An HTTP client based on the Fetch API.
*/
export class HttpClient {
/**
* The current number of active requests.
* Requests being processed by interceptors are considered active.
*/
activeRequestCount: number = 0;
/**
* Indicates whether or not the client is currently making one or more requests.
*/
isRequesting: boolean = false;
/**
* Indicates whether or not the client has been configured.
*/
isConfigured: boolean = false;
/**
* The base URL set by the config.
*/
baseUrl: string = '';
/**
* The default request init to merge with values specified at request time.
*/
defaults: RequestInit = null;
/**
* The interceptors to be run during requests.
*/
interceptors: Interceptor[] = [];
constructor() {
if (typeof fetch === 'undefined') {
throw new Error('HttpClient requires a Fetch API implementation, but the current environment doesn\'t support it. You may need to load a polyfill such as https://github.com/github/fetch.');
}
}
/**
* Configure this client with default settings to be used by all requests.
*
* @param config - A configuration object, or a function that takes a config
* object and configures it.
*
* @chainable
*/
configure(config: RequestInit|(config: HttpClientConfiguration) => void|HttpClientConfiguration): HttpClient {
let normalizedConfig;
if (typeof config === 'object') {
normalizedConfig = { defaults: config };
} else if (typeof config === 'function') {
normalizedConfig = new HttpClientConfiguration();
let c = config(normalizedConfig);
if (typeof c === HttpClientConfiguration) {
normalizedConfig = c;
}
} else {
throw new Error('invalid config');
}
let defaults = normalizedConfig.defaults;
if (defaults && defaults.headers instanceof Headers) {
// Headers instances are not iterable in all browsers. Require a plain
// object here to allow default headers to be merged into request headers.
throw new Error('Default headers must be a plain object.');
}
this.baseUrl = normalizedConfig.baseUrl;
this.defaults = defaults;
this.interceptors.push(...normalizedConfig.interceptors || []);
this.isConfigured = true;
return this;
}
/**
* Starts the process of fetching a resource. Default configuration parameters
* will be applied to the Request. The constructed Request will be passed to
* registered request interceptors before being sent. The Response will be passed
* to registered Response interceptors before it is returned.
*
* See also https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*
* @param input - The resource that you wish to fetch. Either a
* Request object, or a string containing the URL of the resource.
* @param - An options object containing settings to be applied to
* the Request.
*/
fetch(input: Request|string, init?: RequestInit): Promise<Response> {
this::trackRequestStart();
let request = Promise.resolve().then(() => this::buildRequest(input, init, this.defaults));
let promise = processRequest(request, this.interceptors)
.then(result => {
let response = null;
if (result instanceof Response) {
response = result;
} else if (result instanceof Request) {
response = fetch(result);
} else {
throw new Error(`An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [${result}]`);
}
return processResponse(response, this.interceptors);
});
return this::trackRequestEndWith(promise);
}
}
function trackRequestStart() {
this.isRequesting = !!(++this.activeRequestCount);
}
function trackRequestEnd() {
this.isRequesting = !!(--this.activeRequestCount);
}
function trackRequestEndWith(promise) {
let handle = this::trackRequestEnd;
promise.then(handle, handle);
return promise;
}
function parseHeaderValues(headers) {
let parsedHeaders = {};
for (let name in headers || {}) {
if (headers.hasOwnProperty(name)) {
parsedHeaders[name] = (typeof headers[name] === 'function') ? headers[name]() : headers[name];
}
}
return parsedHeaders;
}
function buildRequest(input, init = {}) {
let defaults = this.defaults || {};
let source;
let url;
let body;
if (input instanceof Request) {
if (!this.isConfigured) {
// don't copy the request if there are no defaults configured
return input;
}
source = input;
url = input.url;
body = input.blob();
} else {
source = init;
url = input;
body = init.body;
}
let parsedDefaultHeaders = parseHeaderValues(defaults.headers);
let requestInit = Object.assign({}, defaults, { headers: {} }, source, { body });
let request = new Request((this.baseUrl || '') + url, requestInit);
setDefaultHeaders(request.headers, parsedDefaultHeaders);
return request;
}
function setDefaultHeaders(headers, defaultHeaders) {
for (let name in defaultHeaders || {}) {
if (defaultHeaders.hasOwnProperty(name) && !headers.has(name)) {
headers.set(name, defaultHeaders[name]);
}
}
}
function processRequest(request, interceptors) {
return applyInterceptors(request, interceptors, 'request', 'requestError');
}
function processResponse(response, interceptors) {
return applyInterceptors(response, interceptors, 'response', 'responseError');
}
function applyInterceptors(input, interceptors, successName, errorName) {
return (interceptors || [])
.reduce((chain, interceptor) => {
let successHandler = interceptor[successName];
let errorHandler = interceptor[errorName];
return chain.then(
successHandler && interceptor::successHandler,
errorHandler && interceptor::errorHandler);
}, Promise.resolve(input));
}
| JavaScript | 0 | @@ -4701,24 +4701,87 @@
input.url;%0A
+ if (input.method !== 'GET' && input.method !== 'HEAD') %7B%0A
body = i
@@ -4793,16 +4793,22 @@
blob();%0A
+ %7D%0A
%7D else
@@ -4873,16 +4873,56 @@
y;%0A %7D%0A%0A
+ let bodyObj = body ? %7B body %7D : null;%0A
let pa
@@ -5051,25 +5051,24 @@
source,
- %7B
body
- %7D
+Obj
);%0A let
|
00c68399e37c09d6d718cb8e184232b9e3c3ec80 | Update EU_cookies_law.min.js | EU_cookies_law.min.js | EU_cookies_law.min.js | /*! Simple EU Cookies Law Compliance without dependencies by cara-tm.com, 2017. MIT license */
var EU_cookies_law=function(r){"use strict";var msg="You refuse external third-party cookies: none, at the initiative of this site, is present on your device.",
future='1 Month',
minutes=1;
var domain=window.location.hostname,lang=(navigator.language||navigator.browserLanguage),countries=['AT','BE','BG','HR','CZ','CY','DK','EE','FI','FR','DE','EL','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','SK','SI','ES','SE','GB','UK'],affected!==1,seconds=60,mins=minutes,accept_cookies=document.getElementById('ok-cookies'),refuse_cookies=document.getElementById('no-cookies');if(0!==navigator.cookieEnabled){for(var i=0;i<countries.length;i++){if(countries[i]===lang.substring(0,2).toUpperCase()){affected!==0;break}}
if(affected!==1){sanitize_msg('');jsloader(r);}else check_cookies();
accept_cookies.onclick=function(evt){launch(evt);evt.preventDefault();};function launch(){future=Number(future.replace(/\D+$/,''));var expires=new Date(new Date().setMonth(new Date().getMonth()+future));cookie_creation('Ok',expires);jsloader(r);sanitize_msg('');}refuse_cookies.onclick=function(evt){var tomorrow=new Date(new Date().setDate(new Date().getDate()+1));cookie_creation('No',tomorrow);sanitize_msg(msg);window.location='';evt.preventDefault();};function getCookie(sName){var oRegex=new RegExp('(?:; )?'+sName+'=([^;]*);?');if(oRegex.test(document.cookie))
return decodeURIComponent(RegExp.$1);else return null}
function check_cookies(){tick();if(getCookie(domain)==='Ok'+domain){sanitize_msg('');jsloader(r)}else if(getCookie(domain)==='No'+domain){sanitize_msg(msg)}}
function cookie_creation(c,e){return document.cookie=domain+'='+encodeURIComponent(c+domain)+';expires='+e.toGMTString()}
function jsloader(el){var s=[];var a=document.getElementsByTagName("script")[0];if(!window.scriptHasRun){window.scriptHasRun=true;for(var i=0;i<el.length;i++){if(el[i]!=0||!window.scriptHasRun){window.scriptHasRun=true;s[i]=document.createElement('script');s[i].src=el[i];document.getElementsByTagName('head')[0].appendChild(s[i])||a.parentNode.insertBefore(s[i],a)}}}}
function sanitize_msg(m){document.getElementById("cookies-delay").innerHTML='';return document.getElementById('cookie-choices').innerHTML=m};
function tick(){if(minutes!=0&&null!==document.getElementById('counter')){var counter=document.getElementById('counter'),current_minutes=mins-1;seconds--;if(typeof counter.innerHTML!==null)counter.innerHTML=current_minutes.toString()+':'+(seconds<10?'0':'')+String(seconds);if(seconds>0){setTimeout(tick,1000);}else{if(mins>1){countdown(mins-1);}}if(seconds==0){launch();sanitize_msg('');}}else document.getElementById('cookies-delay').innerHTML='';}}else{sanitize_msg("Veuillez activer les Cookies sur votre navigateur.");}};
// Array of third part JS files to load (with external cookies) if only the 'Cookies Choice' button is accepted by visitors or after a delay if the counter feature is enabled:
EU_cookies_law(["js/google-analytics.js", " "]);
| JavaScript | 0 | @@ -1495,16 +1495,17 @@
urn null
+;
%7D%0Afuncti
@@ -1594,16 +1594,17 @@
oader(r)
+;
%7Delse if
@@ -1654,16 +1654,17 @@
msg(msg)
+;
%7D%7D%0Afunct
@@ -1778,16 +1778,17 @@
String()
+;
%7D%0Afuncti
@@ -2146,16 +2146,17 @@
(s%5Bi%5D,a)
+;
%7D%7D%7D%7D%0Afun
@@ -2291,18 +2291,18 @@
erHTML=m
-%7D
;
+%7D
%0Afunctio
|
2559bbadf7de3f94e2028bd503e903a60ba159a4 | Remove the upload button in folder views (#950) | source/features/remove-upload-files-button.js | source/features/remove-upload-files-button.js | import select from 'select-dom';
import * as pageDetect from '../libs/page-detect';
const repoUrl = pageDetect.getRepoURL();
export default () => {
if (pageDetect.isRepoRoot()) {
const uploadFilesButton = select(`.file-navigation a[href^="/${repoUrl}/upload"]`);
if (uploadFilesButton) {
uploadFilesButton.remove();
}
}
};
| JavaScript | 0 | @@ -171,16 +171,43 @@
poRoot()
+ %7C%7C pageDetect.isRepoTree()
) %7B%0A%09%09co
|
2770897c6b795898e9e6404d61026fd292192e7c | Fix weird floating green bug thingy | src/main/js/components/Workspace.js | src/main/js/components/Workspace.js | var React = require('react');
var Interact = require('interact.js');
var _ = require('lodash');
var PersonContainer = require('containers/PersonContainer.js');
var Space = require('components/Space.js');
var Workspace = React.createClass({
componentDidMount: function() {
var self = this;
Interact('.draggable')
.draggable({
inertia:true,
restrict: {
restriction: ".workspace"
},
autoScroll: true,
onmove: dragMoveListener
});
function dragMoveListener (event) {
// Keep the dragged position in the data-x/data-y attributes
var target = event.target;
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// Translate the element on the screen
target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
// Update the position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
var fromSpaceIndex, toSpaceIndex;
Interact('.dropzone')
.dropzone({
// Only accept elements matching this CSS selector
accept: '.draggable.drag-drop',
// Require a 75% element overlap for a drop to be possible
overlap: 0.50,
// target -> dropzoneElement, relatedTarget -> draggableElement
ondropactivate: function (event) {
event.target.classList.add('drop-active');
},
ondropdeactivate: function (event) {
event.target.classList.remove('drop-active');
},
ondragenter: function (event) {
event.target.classList.add('drop-target');
event.relatedTarget.classList.add('can-drop');
toSpaceIndex = getIndexFromId(event.target.id);
},
ondragleave: function (event) {
event.target.classList.remove('drop-target');
event.relatedTarget.classList.remove('can-drop');
if(fromSpaceIndex === undefined) {
fromSpaceIndex = getIndexFromId(event.target.id);
}
},
ondrop: function (event) {
event.target.classList.remove('drop-target');
var personIndex = getIndexFromId(event.relatedTarget.id);
if(fromSpaceIndex === undefined) {
fromSpaceIndex = toSpaceIndex;
}
self.props.movePerson(fromSpaceIndex, toSpaceIndex, personIndex);
fromSpaceIndex = undefined;
toSpaceIndex = undefined;
}
});
function getIndexFromId(idString) {
var segments = _.split(idString, '_');
return parseInt(segments[segments.length-1]);
}
},
render: function() {
return <div id="space_-1" className="container-fluid workspace dropzone">
<div className="floatingSpace">
<h2>Floating</h2>
{this.props.people.map(function (person, idx) {
return <PersonContainer key={person.name} name={person.name} index={idx} spaceIndex={-1}/>
})}
</div>
{this.props.spaces.map(function (space, idx) {
return <Space key={idx} name={space.name} people={space.people} index={idx}/>;
})}
</div>
}
});
module.exports = Workspace;
| JavaScript | 0 | @@ -2595,16 +2595,86 @@
arget');
+%0A event.relatedTarget.classList.remove('can-drop');
%0A%0A
@@ -2962,24 +2962,318 @@
sonIndex);%0A%0A
+ if (fromSpaceIndex === toSpaceIndex) %7B%0A event.relatedTarget.removeAttribute('style');%0A event.relatedTarget.removeAttribute('data-x');%0A event.relatedTarget.removeAttribute('data-y');%0A %7D%0A%0A
|
50b105a0da0695ba25e67b03a6df354e712e0c6c | correct test | test/subscription.js | test/subscription.js | const hub = require('../')
const test = require('tape')
// test('subscription - val + fields', t => {
// const server = hub({
// _uid_: 'server',
// port: 6060,
// a: {
// val: 'a',
// b: { c: 'c!' }
// }
// })
// server.set({ nostamp: 'nostamp!' }, false)
// const client = hub({
// _uid_: 'client',
// url: 'ws://localhost:6060'
// })
// Promise.all([
// client.get([ 'a', 'b', 'c' ], {}).once('c!'),
// client.get([ 'a' ], {}).once('a')
// ]).then(() => {
// client.subscribe({ nostamp: true })
// return client.get('nostamp', {}).once('nostamp!')
// }).then(() => {
// t.pass('received correct payload')
// client.set(null)
// server.set(null)
// t.end()
// })
// client.subscribe({ a: true })
// })
test('subscription - reuse', t => {
const server = hub({
_uid_: 'server',
port: 6060,
a: 'hello'
})
server.set({ nostamp: 'nostamp!' }, false)
const client = hub({
_uid_: 'client',
url: 'ws://localhost:6060'
})
const client2 = hub({
_uid_: 'client2',
url: 'ws://localhost:6060'
})
client.subscribe({ a: true })
client2.subscribe({ a: true })
Promise.all([
client.get('a', {}).once(true),
client2.get('a', {}).once(true)
]).then(() => {
t.pass('received correct payload (reuse)')
client.set(null)
client2.set(null)
server.set(null)
t.end()
})
})
| JavaScript | 0.000717 | @@ -1118,17 +1118,16 @@
'%0A %7D)%0A%0A
-%0A
client
@@ -1419,12 +1419,11 @@
()%0A %7D)%0A
-%0A
%7D)%0A
|
8b096564b08a788d8d10f04c541e885ac49c2867 | Add correct column widths | src/pages/dataTableUtilities/columns.js | src/pages/dataTableUtilities/columns.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import { tableStrings } from '../../localization';
const PAGE_COLUMN_WIDTHS = {
customerInvoice: [2, 4, 2, 2, 1],
supplierInvoice: [1, 3, 1, 1, 1],
};
const PAGE_COLUMNS = {
customerInvoice: ['itemCode', 'itemName', 'availableQuantity', 'totalQuantity', 'remove'],
supplierInvoice: ['itemCode', 'itemName', 'totalQuantity', 'editableExpiryDate', 'remove'],
};
const COLUMNS = () => ({
itemCode: {
key: 'itemCode',
title: tableStrings.item_code,
sortable: true,
},
itemName: {
key: 'itemName',
title: tableStrings.item_name,
sortable: true,
},
availableQuantity: {
key: 'availableQuantity',
title: tableStrings.available_stock,
sortable: true,
alignText: 'right',
},
totalQuantity: {
key: 'totalQuantity',
type: 'editable',
title: tableStrings.quantity,
sortable: true,
alignText: 'right',
},
remove: {
key: 'remove',
type: 'checkable',
title: tableStrings.remove,
alignText: 'center',
},
editableExpiryDate: {
key: 'editableExpiryDate',
type: 'date',
title: tableStrings.batch_expiry,
alignText: 'center',
},
});
const getColumns = page => {
const columnKeys = PAGE_COLUMNS[page];
const widths = PAGE_COLUMN_WIDTHS[page];
if (!columnKeys) return [];
if (!(columnKeys.length === widths.length)) return [];
const columns = COLUMNS();
return columnKeys.map((columnKey, i) => ({ ...columns[columnKey], width: widths[i] }));
};
export default getColumns;
| JavaScript | 0.001313 | @@ -201,18 +201,18 @@
e: %5B
-1, 3, 1, 1
+2, 4, 2, 2
, 1%5D
|
38908396f516ce76132bab0a2c288835668c00c9 | Fix stream view spec to look for different things on FF and on webkit. Sigh. | spec/javascripts/app/views/stream_view_spec.js | spec/javascripts/app/views/stream_view_spec.js | describe("app.views.Stream", function(){
beforeEach(function(){
loginAs({name: "alice", avatar : {small : "http://avatar.com/photo.jpg"}});
this.posts = $.parseJSON(spec.readFixture("multi_stream_json"))["posts"];
this.stream = new app.models.Stream();
this.stream.add(this.posts);
this.view = new app.views.Stream({model : this.stream});
app.stream.bind("fetched", this.collectionFetched, this); //untested
// do this manually because we've moved loadMore into render??
this.view.render();
_.each(this.view.collection.models, function(post){ this.view.addPost(post); }, this);
});
describe("initialize", function(){
it("binds an infinite scroll listener", function(){
spyOn($.fn, "scroll");
new app.views.Stream({model : this.stream});
expect($.fn.scroll).toHaveBeenCalled();
});
});
describe("#render", function(){
beforeEach(function(){
this.statusMessage = this.stream.posts.models[0];
this.reshare = this.stream.posts.models[1];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
this.reshareElement = $(this.view.$("#" + this.reshare.get("guid")));
});
context("when rendering a status message", function(){
it("shows the message in the content area", function(){
expect(this.statusElement.find(".post-content p").text()).toContain("LONG POST"); //markdown'ed
});
});
});
describe('clicking read more', function() {
var readMoreLink;
beforeEach(function() {
this.statusMessage = this.stream.posts.models[0];
this.statusElement = $(this.view.$("#" + this.statusMessage.get("guid")));
readMoreLink = this.statusElement.find('.read-more a');
readMoreLink.text("read more");
});
it('expands the post', function() {
expect(this.statusElement.find('.collapsible .details').attr('style')).toContain('display: none;');
readMoreLink.click();
expect(this.statusElement.find('.collapsible .details').attr('style')).not.toContain('display: none;');
});
it('removes the read-more div', function() {
expect(this.statusElement.find('.read-more').length).toEqual(1);
readMoreLink.click();
expect(this.statusElement.find('.read-more').length).toEqual(0);
});
xit('collapses the p elements', function() {
// This does not work on firefox. Seems to be different behavior of the expander plugin. Needs more work.
expect(this.statusElement.find('.collapsible p').length).toEqual(2);
readMoreLink.click();
expect(this.statusElement.find('.collapsible p').length).toEqual(1);
});
});
describe("infScroll", function(){
// NOTE: inf scroll happens at 500px
it("calls render when the user is at the bottom of the page", function(){
spyOn($.fn, "height").andReturn(0);
spyOn($.fn, "scrollTop").andReturn(100);
spyOn(this.view, "render");
this.view.infScroll();
expect(this.view.render).toHaveBeenCalled();
});
});
describe("removeLoader", function() {
it("emptys the pagination div when the stream is fetched", function(){
$("#jasmine_content").append($('<div id="paginate">OMG</div>'));
expect($("#paginate").text()).toBe("OMG");
this.view.stream.trigger("fetched");
expect($("#paginate")).toBeEmpty();
});
});
describe("unbindInfScroll", function(){
it("unbinds scroll", function() {
spyOn($.fn, "unbind");
this.view.unbindInfScroll();
expect($.fn.unbind).toHaveBeenCalledWith("scroll");
});
});
});
| JavaScript | 0 | @@ -2306,17 +2306,16 @@
);%0A%0A
-x
it('coll
@@ -2334,16 +2334,26 @@
elements
+ on webkit
', funct
@@ -2375,109 +2375,271 @@
/ Th
-is does not work on firefox. Seems to be different behavior of the expander plugin. Needs more work.%0A
+e expander plugin has different behavior on firefox and webkit %3E.%3C%0A expect(this.statusElement.find('.collapsible p').length).toEqual(2);%0A readMoreLink.click();%0A if(this.statusElement.find('.collapsible .summary').length %3E 0) %7B%0A // Firefox%0A
@@ -2715,38 +2715,46 @@
;%0A
-readMoreLink.click();%0A
+%7D else %7B %0A // Chrome%0A
ex
@@ -2816,24 +2816,32 @@
toEqual(1);%0A
+ %7D%0A
%7D);%0A %7D)
|
5a5d8f8086c70f4cd328ea806e01e0e523fbcaa9 | Fix test | test/test.winston.js | test/test.winston.js | var expect = require('chai').expect;
var winstonSupport = require('../lib/winston');
var winston = require('winston');
var runServer = require('../lib/testHelper').runServer;
describe("winston", function(){
describe('name', function(){
it('should be "fluent"', function(done){
expect(winstonSupport.name).to.be.equal('fluent');
done();
});
});
describe('transport', function(){
it('should send log records', function(done){
runServer(function(server, finish){
var logger = new (winston.Logger)({
transports: [
new (winstonSupport.Transport)('debug', {port: server.port})
]
});
logger.info('foo %s', 'bar', {x: 1});
setTimeout(function(){
finish(function(data){
expect(data[0].tag).to.be.equal('debug');
expect(data[0].data).exist;
expect(data[0].time).exist;
expect(data[0].data.message).to.be.equal('foo bar');
expect(data[0].data.level).to.be.equal('info');
expect(data[0].data.meta.x).to.be.equal(1);
done();
});
}, 1000);
});
});
});
});
| JavaScript | 0.000004 | @@ -289,16 +289,22 @@
expect
+((new
(winston
@@ -311,16 +311,30 @@
Support.
+Transport)()).
name).to
|
4d633f24b26d224580c3fef255fa352623fd982a | Use velocity to animate thread scroll for better performance | src/modules/Thread/events/scroll.js | src/modules/Thread/events/scroll.js | const {
headerHeight,
threadpostScrollDuration,
threadpostScrollHighlightDuration
} = window.appSettings;
export default function createPostScroller( $context ) {
return function (href) {
const $item = $context.find(href);
const offset = $item[0].offsetTop;
console.log(`Post scrolled to has offset: "${offset}px"`);
$context.animate({
scrollTop: offset - headerHeight
}, threadpostScrollDuration);
$item.addClass('highlight');
setTimeout(() => $item.removeClass('highlight'),
threadpostScrollHighlightDuration
);
}
}
| JavaScript | 0.000004 | @@ -254,219 +254,279 @@
-const offset = $item%5B0%5D.offsetTop;%0A%0A console.log(%60Post scrolled to has offset: %22$%7Boffset%7Dpx%22%60);%0A%0A $context.animate(%7B%0A scrollTop: offset - headerHeight%0A %7D, threadpostScrollDuration
+// $context.animate(%7B%0A // scrollTop: offset - headerHeight%0A // %7D, threadpostScrollDuration);%0A%0A $item.velocity('scroll', %7B%0A container: $context,%0A duration: threadpostScrollDuration,%0A offset: -headerHeight%0A %7D
);%0A%0A
|
a4911813d9bcbeca50968e538940f1934822e14d | fix example, add missing comma | aura_components/registration/form/main.js | aura_components/registration/form/main.js | /**
*
* Shows a form so the user can fill any kind of data.
*
* Define the fields using the `admin/registration` component.
* Client-side validation is handled automatically and forms are build using a form builder with support for several field types.
* Look at the JSON samples below to get a feel on what field types are supported.
*
* ## Supported field types
*
* ### Text
* ```js
* {
* type : 'text',
* name : 'unique_name',
* label : 'Name',
* pattern : 'Regex/HTML5 Standard',
* value : 'Default Value',
* autocomplete: false,
* required: true,
* error : 'Error message',
* placeholder : 'bob',
* }
* ```
*
* ### Email
* ```js
* {
* type : 'email',
* name : 'unique_name',
* label : 'Email',
* pattern : 'Regex/HTML5 Standard',
* value : '',
* required: true,
* error : 'Invalid Email',
* placeholder : 'you@awesome.com'
* }
* ```
* ### Url
* ```js
* {
* type : 'url',
* name : 'unique_name',
* label : 'Name',
* pattern : 'Regex/HTML5 Standard',
* value : '',
* required: true,
* error : 'You made an error',
* placeholder : 'placeholder content'
* }
* ```
*
* ### Telephone
* ```js
* {
* type : 'tel',
* name : 'unique_name',
* label : 'Name',
* pattern : 'Regex/HTML5 Standard',
* value : '',
* required: true,
* error : 'You made an error',
* placeholder : 'placeholder content'
* }
* ```
*
* ### Select
* ```js
* {
* type : 'select',
* name : 'unique_name',
* label : 'Name',
* value : '',
* required: true,
* options:[
* {label:"Label", value: "value"},
* {label:"Label", value: "value"},
* {label:"Label", value: "value"}
* ],
* error : 'You made an error',
* placeholder : 'placeholder content'
* }
* ```
*
* ### Checkbox
* ```js
* {
* type : 'checkbox',
* name : 'unique_name',
* label : 'Name',
* value : '',
* required: true,
* error : 'You made an error'
* },
* ```
*
* @name Form
* @param {Boolean} editable Wether to offer the user to modify his form again once he submitted it.
* @action {achieve}
* @datasource {activities}
* @template {template_name}
* @your_custom_tag {name} value
* @your_custom_tag value
* @example <div data-hull-component='registration/form'></div>
*/
Hull.define(['underscore', 'h5f'], function(_, H5F) {
return {
type: 'Hull',
templates: ['form', 'complete'],
refreshEvents: ['model.hull.me.change'],
require:{
paths:{
h5f:'h5f'
}
}
complete: false,
options:{
editable:false
},
defaultFields: [
{
type : 'text',
name : 'name',
label : 'Name',
value : '',
required: true,
error : 'Please enter your name',
placeholder : 'bob'
},
{
type : 'email',
name : 'email',
label : 'Email',
value : '',
required: true,
error : 'Invalid Email',
placeholder : 'you@awesome.com'
}
],
datasources: {
fields: function() {
var extra = this.sandbox.data.api.model('app').get('extra');
return extra.profile_fields || this.defaultFields;
}
},
initialize : function(options, callback) {
this.formId = "form_"+(new Date()).getTime();
var _ = this.sandbox.util._;
_.bindAll.apply(undefined, [this].concat(_.functions(this)));
},
validate: function() {
this._ensureFormEl();
var isValid = this.formEl.checkValidity();
if(isValid) return isValid;
this.$el.find('[data-hull-input]').each(function(key, el){
var $el = $(el),
id = $el.attr('id');
var errorMsg = $el.siblings('[data-hull-error]')
errorMsg.text((el.checkValidity()) ? '' : $el.data('errorMessage'));
});
return false;
},
register: function(profile) {
var self = this;
me = this.sandbox.data.api.model('me');
if (this.loggedIn()) {
this.api('me/profile', 'put', profile, function(newProfile) {
me.set('profile', newProfile);
self.render();
});
}
},
beforeRender: function(data) {
data.formId = this.formId;
var fields = this.sandbox.util._.map(data.fields, function(f) {
f.value = this._findFieldValue(f.name);
return f;
}, this);
var profile = data.me.profile || {};
// Check if user.profile contains all the fields with their respective
// value. If it's the case we consider the form as complete.
var isComplete = this.sandbox.util._.every(fields, function(f) {
var profileField = profile[f.name];
if (f.type === 'checkbox') {
return profileField == f.value;
} else {
return !!profileField && profileField === f.value;
}
});
this.template = isComplete ? 'complete' : 'form';
this.fields = fields;
},
afterRender: function() {
if (this.template === 'form') {
this._ensureFormEl();
H5F.setup(this.formEl, {
validClass: "hull-form__input--valid",
invalidClass: "hull-form__input--invalid",
requiredClass: "hull-form__input--required",
placeholderClass: "hull-form__input--placeholder"
});
}
},
actions: {
edit: function(e) {
e.preventDefault();
e.stopPropagation();
this.render("form");
return false;
},
submit: function(e, opts) {
e && e.preventDefault();
if (!this.validate()) {
e && e.stopPropagation();
e && e.stopImmediatePropagation();
return false;
}
var fields = this.sandbox.util._.clone(this.fields),
extra = {},
el = this.$el;
this.sandbox.util._.each(fields, function(field) {
if (field.type == 'checkbox') {
extra[field.name] = el.find('#hull-form-' + field.name).is(':checked');
} else {
extra[field.name] = el.find('#hull-form-' + field.name).val();
}
});
this.register(extra);
}
},
_findFieldValue: function(name) {
var me = this.data.me.toJSON() || {};
var identities = this.sandbox.util._.reduce(me.identities, this.sandbox.util._.bind(function(memo, i) {
return this.sandbox.util._.extend(memo, i);
}, this), {});
me.profile = me.profile || {};
identities = identities || {};
return me.profile[name] || me[name] || identities[name];
},
_ensureFormEl: function() {
if (this.formEl == null) {
this.formEl = document.getElementById(this.formId);
}
}
};
});
| JavaScript | 0.00098 | @@ -2302,16 +2302,21 @@
ion/form
+@hull
'%3E%3C/div%3E
@@ -2543,24 +2543,25 @@
%7D%0A %7D
+,
%0A%0A comple
|
f05fb051917e564d4059bc7d9e4cc26487f00273 | remove unused force arg | src/issue-store.js | src/issue-store.js | import _ from 'underscore';
import {EventEmitter} from 'events';
import Client from './github-client';
import {fetchAll, KANBAN_LABEL, ICEBOX_NAME} from './helpers';
const RELOAD_TIME = 60 * 1000;
const toIssueListKey = (repoOwner, repoName) => {
return repoOwner + '/' + repoName + '/issues';
};
const toIssueKey = (repoOwner, repoName, issueNumber) => {
return repoOwner + '/' + repoName + '/issues/' + issueNumber;
};
const toCommentListKey = (repoOwner, repoName, issueNumber) => {
return repoOwner + '/' + repoName + '/issues/' + issueNumber + '/comments';
};
const toCommentKey = (repoOwner, repoName, issueNumber, commentId) => {
return repoOwner + '/' + repoName + '/issues/' + issueNumber + '/comments/' + commentId;
};
let cacheIssues = {};
let cacheLastViewed = {};
const initialTimestamp = new Date();
class IssueStore extends EventEmitter {
off() { // EventEmitter has `.on` but no matching `.off`
const slice = [].slice;
const args = arguments.length >= 1 ? slice.call(arguments, 0) : [];
return this.removeListener.apply(this, args);
}
fetch(repoOwner, repoName, issueNumber) {
const issue = Client.getOcto().repos(repoOwner, repoName).issues(issueNumber);
const key = toIssueKey(repoOwner, repoName, issueNumber);
if (cacheIssues[key]) {
return Promise.resolve(cacheIssues[key]);
} else {
return issue.fetch()
.then((val) => {
cacheIssues[key] = val;
this.emit('change', key, val);
this.emit('change:' + key, val);
return val;
});
}
}
fetchPullRequest(repoOwner, repoName, issueNumber) {
const issue = Client.getOcto().repos(repoOwner, repoName).pulls(issueNumber);
const key = toIssueKey(repoOwner, repoName, issueNumber);
return issue.fetch()
.then((val) => {
cacheIssues[key] = val;
this.emit('change', key, val);
this.emit('change:' + key, val);
return val;
});
}
fetchAll(repoOwner, repoName, force) {
const listKey = toIssueListKey(repoOwner, repoName);
// Start polling
if (!this.polling) {
this.polling = setTimeout(() => {
this.polling = null;
this.fetchAll(repoOwner, repoName, true);
}, RELOAD_TIME);
}
if (cacheIssues[listKey] && !force) {
return Promise.resolve(cacheIssues[listKey]);
} else {
const issues = Client.getOcto().repos(repoOwner, repoName).issues.fetch;
return fetchAll(issues)
.then((vals) => {
cacheIssues[listKey] = vals;
for (let issue of vals) {
const issueNumber = issue.number;
const key = toIssueKey(repoOwner, repoName, issueNumber);
cacheIssues[key] = issue;
}
this.emit('change:' + listKey, vals);
return vals;
});
}
}
update(repoOwner, repoName, issueNumber, opts) {
const issue = Client.getOcto().repos(repoOwner, repoName).issues(issueNumber);
const listKey = toIssueListKey(repoOwner, repoName);
const key = toIssueKey(repoOwner, repoName, issueNumber);
return issue.update(opts)
.then((val) => {
cacheIssues[key] = val;
// invalidate the issues list
delete cacheIssues[listKey];
// this.emit('change', toIssueListKey(repoOwner, repoName));
// this.emit('change', key, val);
this.emit('change:' + key, val);
});
}
move(repoOwner, repoName, issueNumber, newLabel) {
// Find all the labels, remove the kanbanLabel, and add the new label
const key = toIssueKey(repoOwner, repoName, issueNumber);
const listKey = toIssueListKey(repoOwner, repoName);
const issue = cacheIssues[key];
// Exclude Kanban labels
const labels = _.filter(issue.labels, (label) => {
if (ICEBOX_NAME === label.name || KANBAN_LABEL.test(label.name)) {
return false;
}
return true;
});
const labelNames = _.map(labels);
// When moving back to icebox do not add a new label
if (ICEBOX_NAME !== newLabel.name) {
labelNames.push(newLabel.name);
}
return Client.getOcto().repos(repoOwner, repoName).issues(issueNumber).update({labels: labelNames})
.then(() => {
// invalidate the issues list
delete cacheIssues[listKey];
this.emit('change');
this.emit('change:' + key);
this.emit('change:' + listKey);
});
}
createLabel(repoOwner, repoName, opts) {
return Client.getOcto().repos(repoOwner, repoName).labels.create(opts);
}
fetchComments(repoOwner, repoName, issueNumber) {
const commentListKey = toCommentListKey(repoOwner, repoName, issueNumber);
if (cacheIssues[commentListKey]) {
return Promise.resolve(cacheIssues[commentListKey]);
} else {
return Client.getOcto().repos(repoOwner, repoName).issues(issueNumber).comments.fetch()
.then((comments) => {
cacheIssues[commentListKey] = comments;
this.emit('change:' + commentListKey);
return comments;
});
}
}
createComment(repoOwner, repoName, issueNumber, opts) {
const listKey = toCommentListKey(repoOwner, repoName, issueNumber);
const issueKey = toIssueKey(repoOwner, repoName, issueNumber);
const issue = Client.getOcto().repos(repoOwner, repoName).issues(issueNumber);
return issue.comments.create(opts)
.then((val) => {
const commentNumber = val.id;
const key = toCommentKey(repoOwner, repoName, issueNumber, commentNumber);
cacheIssues[key] = val;
// invalidate the issues list
delete cacheIssues[listKey];
delete cacheIssues[issueKey];
this.emit('change', issueKey);
// this.emit('change', key, val);
this.emit('change:' + key, val);
});
}
setLastViewed(repoOwner, repoName, issue) {
const issueKey = toIssueKey(repoOwner, repoName, issue.number);
const now = new Date();
const isNew = !cacheLastViewed[issueKey] || (now.getTime() - cacheLastViewed[issueKey].getTime() > 10000);
cacheLastViewed[issueKey] = now;
if (isNew) {
this.emit('change:' + issueKey, issue);
}
}
getLastViewed(repoOwner, repoName, issueNumber) {
const issueKey = toIssueKey(repoOwner, repoName, issueNumber);
return cacheLastViewed[issueKey] || initialTimestamp;
}
}
const Store = new IssueStore();
export {toIssueKey, toIssueListKey, Store};
| JavaScript | 0.000129 | @@ -1967,15 +1967,8 @@
Name
-, force
) %7B%0A
@@ -2250,18 +2250,8 @@
Key%5D
- && !force
) %7B%0A
|
fac54d5ba2296bd891dc60da065f7503af984f4e | Revert "We need an entity name" | blueprints/ember-cli-latex-maths/index.js | blueprints/ember-cli-latex-maths/index.js | module.exports = {
//description: '',
normalizeEntityName: function() {}, // no-op since we're just adding dependencies
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
// afterInstall: function(options) {
// // Perform extra work here.
// }
afterInstall: function() {
return this.addBowerPackageToProject('katex'); // is a promise
}
};
| JavaScript | 0.000009 | @@ -36,92 +36,8 @@
'',
-%0A normalizeEntityName: function() %7B%7D, // no-op since we're just adding dependencies
%0A%0A
|
ea219d201fdc10358b34cf4e87c0143af2f5ae3b | Fix "dialogFieldRefresh #initializeDialogSelectPicker ... has no expectations" | spec/javascripts/dialog_field_refresh_spec.js | spec/javascripts/dialog_field_refresh_spec.js | describe('dialogFieldRefresh', function() {
describe('#addOptionsToDropDownList', function() {
var data = {};
beforeEach(function() {
var html = "";
html += '<select class="dynamic-drop-down-345 selectpicker">';
html += '</select>';
setFixtures(html);
});
context('when the refreshed values contain a checked value', function() {
context('when the refreshed values contain a null key', function() {
beforeEach(function() {
data = {values: {refreshed_values: [[null, 'not test'], ['123', 'is test']], checked_value: 123}};
});
it('it does not blow up', function() {
var test = function() {
dialogFieldRefresh.addOptionsToDropDownList(data, 345);
};
expect(test).not.toThrow();
});
it('selects the option that corresponds to the checked value', function() {
dialogFieldRefresh.addOptionsToDropDownList(data, 345);
expect($('.dynamic-drop-down-345.selectpicker').val()).toBe('123');
});
});
});
context('when the refreshed values do not contain a checked value', function() {
beforeEach(function() {
data = {values: {refreshed_values: [["test", "test"], ["not test", "not test"]], checked_value: null}};
});
it('selects the first option', function() {
dialogFieldRefresh.addOptionsToDropDownList(data, 345);
expect($('.dynamic-drop-down-345.selectpicker').val()).toBe('test');
});
});
});
describe('#refreshDropDownList', function() {
beforeEach(function() {
spyOn(dialogFieldRefresh, 'addOptionsToDropDownList');
spyOn($.fn, 'selectpicker');
spyOn($, 'post').and.callFake(function() {
var d = $.Deferred();
d.resolve("the data");
return d.promise();
});
});
it('calls addOptionsToDropDownList', function() {
dialogFieldRefresh.refreshDropDownList('abc', 123, 'test');
expect(dialogFieldRefresh.addOptionsToDropDownList).toHaveBeenCalledWith("the data", 123);
});
it('ensures the select picker is refreshed', function() {
dialogFieldRefresh.refreshDropDownList('abc', 123, 'test');
expect($.fn.selectpicker).toHaveBeenCalledWith('refresh');
});
it('sets the value in the select picker', function() {
dialogFieldRefresh.refreshDropDownList('abc', 123, 'test');
expect($.fn.selectpicker).toHaveBeenCalledWith('val', 'test');
});
it('uses the correct selector', function() {
dialogFieldRefresh.refreshDropDownList('abc', 123, 'test');
expect($.fn.selectpicker.calls.mostRecent().object.selector).toEqual('#abc');
});
});
describe('#initializeDialogSelectPicker', function() {
var fieldName, selectedValue, url;
beforeEach(function() {
spyOn(dialogFieldRefresh, 'triggerAutoRefresh');
spyOn(window, 'miqInitSelectPicker');
spyOn(window, 'miqSelectPickerEvent');
spyOn($.fn, 'selectpicker');
fieldName = 'fieldName';
fieldId = 'fieldId';
selectedValue = 'selectedValue';
url = 'url';
var html = "";
html += '<select id=fieldName class="dynamic-drop-down-193 selectpicker">';
html += '<option value="1">1</option>';
html += '<option value="2" selected="selected">2</option>';
html += '</select>';
setFixtures(html);
});
it('initializes the select picker', function() {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url);
expect(window.miqInitSelectPicker).toHaveBeenCalled();
});
it('sets the value of the select picker', function() {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url);
expect($.fn.selectpicker).toHaveBeenCalledWith('val', 'selectedValue');
});
it('uses the correct selector', function() {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url);
expect($.fn.selectpicker.calls.mostRecent().object.selector).toEqual('#fieldName');
});
it('sets up the select picker event', function() {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url);
expect(window.miqSelectPickerEvent).toHaveBeenCalledWith('fieldName', 'url', {callback: jasmine.any(Function)});
});
it('triggers the auto refresh when the drop down changes', function(done) {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url);
done();
expect(dialogFieldRefresh.triggerAutoRefresh).toHaveBeenCalledWith(fieldId, 'true');
});
it('triggers autorefresh with "false" when triggerAutoRefresh arg is false', function(done) {
dialogFieldRefresh.initializeDialogSelectPicker(fieldName, fieldId, selectedValue, url, 'false');
done();
expect(dialogFieldRefresh.triggerAutoRefresh).toHaveBeenCalledWith(fieldId, 'false');
});
});
});
| JavaScript | 0.000007 | @@ -4445,32 +4445,28 @@
', function(
-done
) %7B%0A
+
dialog
@@ -4548,30 +4548,16 @@
, url);%0A
- done();%0A
ex
@@ -4738,20 +4738,16 @@
unction(
-done
) %7B%0A
@@ -4850,22 +4850,8 @@
');%0A
- done();%0A
|
6c3f7569aa4e41f34d9447f1095b886e94e7c801 | Remove Error type as it is a javascript file | templates/expo-template-tabs/App.js | templates/expo-template-tabs/App.js | import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import * as Font from 'expo-font';
import React, { useState } from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import AppNavigator from './navigation/AppNavigator';
export default function App(props) {
const [isLoadingComplete, setLoadingComplete] = useState(false);
if (!isLoadingComplete && !props.skipLoadingScreen) {
return (
<AppLoading
startAsync={loadResourcesAsync}
onError={handleLoadingError}
onFinish={() => handleFinishLoading(setLoadingComplete)}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
async function loadResourcesAsync() {
await Promise.all([
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free to
// remove this if you are not using it in your app
'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
}),
]);
}
function handleLoadingError(error: Error) {
// In this case, you might want to report the error to your error reporting
// service, for example Sentry
console.warn(error);
}
function handleFinishLoading(setLoadingComplete) {
setLoadingComplete(true);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
| JavaScript | 0.000001 | @@ -1397,15 +1397,8 @@
rror
-: Error
) %7B%0A
|
a1f070f309dba348b5c537ae9efdc34cf622fa0b | handle condition where expected value is an empty string | test/acceptance/acceptance_tests.js | test/acceptance/acceptance_tests.js | const fs = require('fs');
const _ = require('lodash');
const tape = require('tape');
const filename = process.argv[2];
if (!filename) {
console.error('no source supplied');
process.exit(1);
}
if (!fs.existsSync(filename)) {
console.error(`file ${filename} not found`);
process.exit(1);
}
// this function matches the behavior of row_fxn_regexp in the machine, with the
// addition of trimming return values to match behavior later in the machine
function getActualValue(matcher, replace) {
// if a replace was specified, replace the matched groups
// eg - if matched groups are ["abc", "a", "c"] and replace is "$1:$2"
// then the output is "a:c"
if (matcher) {
if (replace) {
return matcher.reduce((acc, curr, idx) => {
// ignore the first matched group since it's the entire string
return idx === 0 ? acc : acc.replace(`$${idx}`, curr);
}, replace);
}
// otherwise, return the trimmed concatenation of all the matched groups
return matcher.slice(1).join('').trim();
}
}
function shouldRunAcceptanceTests(source) {
return source.test && // return false if there's no 'test' blob
_.get(source.test, 'enabled', true) && // default 'enabled' to true
_.get(source.test, 'acceptance-tests', []).length > 0;
}
fs.readFile(filename, (err, data) => {
const source = JSON.parse(data);
if (!shouldRunAcceptanceTests(source)) {
return;
}
// find all the conform fields that utilize the regexp function and compile
// them for later. The output of this is an object keyed on the regexp fields.
const fields_with_regexp = Object.keys(source.conform).reduce((acc, curr) => {
if (_.isObject(source.conform[curr]) && source.conform[curr]['function'] === 'regexp') {
acc[curr] = {
// which field to use from the test inputs blob
input_field: source.conform[curr].field,
regexp: new RegExp(source.conform[curr].pattern),
replace: source.conform[curr].replace
};
}
return acc;
}, {});
// iterate the tests, validating each
source.test['acceptance-tests'].forEach((acceptanceTest) => {
tape.test(`testing '${acceptanceTest.description}'`, (t) => {
// iterate the conform fields that use the regexp function
Object.keys(fields_with_regexp).forEach((field) => {
// figure out which input value to use from the inputs blob
const input_value = acceptanceTest.inputs[fields_with_regexp[field].input_field];
const expected_value = acceptanceTest.expected[field];
// run test only if test has input and expected value for this field
if (input_value && expected_value) {
// the compiled regexp to match with
const regexp = fields_with_regexp[field].regexp;
// the specific match group(s) to use, if any
const replace = fields_with_regexp[field].replace;
// run the regex against the input value
const actual_value = getActualValue(input_value.match(regexp), replace);
t.equals(actual_value, expected_value,
`${field} field: expected '${expected_value}' from input '${input_value}'`);
}
});
t.end();
});
});
});
| JavaScript | 0.00003 | @@ -1034,16 +1034,30 @@
);%0A %7D%0A%0A
+ return '';%0A%0A
%7D%0A%0Afunct
@@ -2685,16 +2685,30 @@
ed_value
+ !== undefined
) %7B%0A
|
43ce6e09f4fbe8f3fc5fe09d5b5986d4ee57ea55 | fix auth.account data util | test/data/auth/account-data-util.js | test/data/auth/account-data-util.js | "use strict";
var _getSert = require("../getsert");
var generateCode = require("../../../src/utils/code-generator");
var Role = require("./role-data-util");
class AccountDataUtil {
getSert(input) {
var ManagerType = require("../../../src/managers/auth/account-manager");
return _getSert(input, ManagerType, (data) => {
return {
username: data.username
};
});
}
getNewData() {
return Role.getTestData()
.then((role) => {
var Model = require("spot-models").auth.Account;
var data = new Model();
var code = generateCode();
data.username = `${code}@unit.test`;
data.password = "Standar123";
data.email = `${code}@unit.test`;
data.isLocked = false;
data.profile = {
firstname: "John",
lastname: code,
gender: "M",
dob: new Date(),
email: `${code}@unit.test`
};
data.roles = [role];
data.facebook = {};
return Promise.resolve(data);
});
}
getTestData() {
return this.getNewData()
.then((data) => {
data.username = "dev";
data.email = "dev@unit.test";
data.profile.firstname = "Test";
data.profile.lastname = "Unit";
return this.getSert(data);
});
}
}
module.exports = new AccountDataUtil();
| JavaScript | 0.000028 | @@ -1074,17 +1074,16 @@
it.test%60
-
%0A
@@ -1499,24 +1499,168 @@
e = %22Unit%22;%0A
+ data.profile.email = %22dev@unit.test%22;%0A data.profile.gender = %22M%22;%0A data.profile.dob = new Date();%0A
|
015563fd86fc238e7951ce9af48b8445553b31fc | include default channel in tests | test/httpApi-authorizedUser.test.js | test/httpApi-authorizedUser.test.js | const app = require('../app');
const server = app.http;
const mockgoose = app.mockgoose;
const chai = require('chai'),
expect = chai.expect,
should = chai.should();
const request = require('supertest');
const io = require('socket.io-client');
const events = require('../events');
const models = require('../models');
const serverPort = 3001;
const serverUrl = `http://localhost:${serverPort}`;
const apiUrls = {
register: '/api/register',
signIn: '/api/authenticate',
signOut: '/api/logout',
users: '/api/users',
userChannels: '/api/user/channels',
channelMessages: '/api/channel/somechannel/messages',
};
const defaultUser = user = {
username: 'mikko',
password: 'mikko',
};
describe('authorized user', () => {
before((done) => {
server.listen(serverPort, () => {
done();
});
});
afterEach((done) => {
mockgoose.reset(() => {
done();
});
});
it('should be able to sign out', (done) => {
request(serverUrl)
.post(apiUrls.register)
.send(defaultUser)
.expect('set-cookie', /express.sid/)
.end((err, res) => {
const cookie = res.headers['set-cookie'];
request(serverUrl)
.post(apiUrls.signOut)
.send(defaultUser)
.set('Cookie', cookie)
.end((err, res) => {
expect(res.status).to.equal(200);
done();
});
});
});
it('should be able to get the list of users', (done) => {
request(serverUrl)
.post(apiUrls.register)
.send(defaultUser)
.expect('set-cookie', /express.sid/)
.end((err, res) => {
const cookie = res.headers['set-cookie'];
request(serverUrl)
.get(apiUrls.users)
.send(defaultUser)
.set('Cookie', cookie)
.end((err, res) => {
expect(res.status).to.equal(200);
expect(res.body).length.to.be(1);
expect(res.body[0].local).to.have.property('username');
expect(res.body[0].local).to.have.property('online');
done();
});
});
});
it('should be able to get the list of users channels', (done) => {
request(serverUrl)
.post(apiUrls.register)
.send(defaultUser)
.expect('set-cookie', /express.sid/)
.end((err, res) => {
const newChannel = new models.Channel();
newChannel.name = 'somechannel';
newChannel.save()
.then(() => models.User.findOneAndUpdate(
{ 'local.username': defaultUser.username },
{ $push: { 'local.channels': 'somechannel' } }).exec())
.then(() => {
const cookie = res.headers['set-cookie'];
request(serverUrl)
.get(apiUrls.userChannels)
.send(defaultUser)
.set('Cookie', cookie)
.end((err, res) => {
expect(res.status).to.equal(200);
expect(res.body.local.channels.length).to.equal(1);
expect(res.body.local.channels).to.include('somechannel');
done();
});
});
});
});
it('should not be able to get the list of messages from channel that user isn\'t joined', (done) => {
request(serverUrl)
.post(apiUrls.register)
.send(defaultUser)
.expect('set-cookie', /express.sid/)
.end((err, res) => {
const cookie = res.headers['set-cookie'];
request(serverUrl)
.get(apiUrls.channelMessages)
.send(defaultUser)
.set('Cookie', cookie)
.end((err, res) => {
expect(res.status).to.equal(401);
expect(res.body).to.have.property('error', 'Not joined to channel.');
done();
});
});
});
it('should be able to get the list of messages from channel that user is joined', (done) => {
request(serverUrl)
.post(apiUrls.register)
.send(defaultUser)
.expect('set-cookie', /express.sid/)
.end((err, res) => {
const newChannel = new models.Channel();
newChannel.name = 'somechannel';
newChannel.save()
.then(() => models.User.findOneAndUpdate(
{ 'local.username': defaultUser.username },
{ $push: { 'local.channels': 'somechannel' } }).exec())
.then(() => {
const cookie = res.headers['set-cookie'];
request(serverUrl)
.get(apiUrls.channelMessages)
.send(defaultUser)
.set('Cookie', cookie)
.end((err, res) => {
expect(res.status).to.equal(200);
done();
});
});
});
});
});
| JavaScript | 0 | @@ -313,24 +313,63 @@
/models');%0A%0A
+const config = require('../config/');%0A%0A
const server
@@ -3451,21 +3451,118 @@
o.equal(
-1
+2
);%0A%0A
+ expect(res.body.local.channels).to.include(config.defaultChannel);%0A
|
a978d3d342c20c4071005397ef316ee0bb216fbe | Increase wait-time for glob return | test/new-server/cli-get-fileSpec.js | test/new-server/cli-get-fileSpec.js | 'use strict';
var module = require('../../lib/index');
var setup = module.setup;
var file1 = "test/fixtures/index.html";
var file2 = "test/fixtures/forms.html";
var file3 = "test/fixtures/scrolling.html";
var css = "test/fixtures/assets/style.css";
var scss = "test/fixtures/scss/main.scss";
describe("Style Injector: transform the files option into useable watchers", function () {
it("can load", function () {
expect(setup).toBeDefined();
});
describe("When getting single files with a string", function () {
var files;
var cb;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return an array of files even if only 1 file", function () {
files = setup.getFiles(file1, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1]);
});
});
it("should return an array of files if an array given", function () {
files = setup.getFiles([file1, file2], cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("when getting multiple files given as strings", function () {
describe("When the files DO exist", function () {
var files = [file1, file2];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file1, file2]);
});
});
});
describe("When the files DO NOT exist", function () {
//
var files = ["test/fixtures/index.html", "test/fixtures/kittie.html"];
var cb;
beforeEach(function(){
cb = jasmine.createSpy("callback1");
});
it("should return an array of the files", function () {
files = setup.getFiles(files, cb);
waits(50);
runs(function () {
expect(cb).toHaveBeenCalledWith(["test/fixtures/index.html"]);
});
});
});
});
describe("Getting files from a glob", function () {
var cb;
var files;
beforeEach(function(){
cb = jasmine.createSpy();
});
it("should return files from a single glob string", function () {
files = setup.getFiles("test/fixtures/*.html", cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3]);
});
});
it("should return files from an array of globs", function () {
files = setup.getFiles([
"test/fixtures/*.html",
"test/fixtures/assets/*.css",
"test/fixtures/scss/*.scss"], cb);
waits(100);
runs(function () {
expect(cb).toHaveBeenCalledWith([file2, file1, file3, css, scss]);
});
});
});
}); | JavaScript | 0.000001 | @@ -3132,33 +3132,33 @@
waits(
-1
+3
00);%0A
|
a22c0fb268bb97d85d7aa25dd2bb1b32f1718d91 | Implement file ediiting | Container.js | Container.js | /**
* @author Christopher Klpap
* @description This component displays the Verse so selection, edit and comments can be made
******************************************************************************/
import React from 'react'
import View from './components/View'
const NAMESPACE = "VerseCheck";
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import SelectionHelpers from './utils/selectionHelpers'
class VerseCheck extends React.Component {
constructor(props) {
super(props)
this.state = {
mode: 'select',
comment: undefined,
verseText: undefined,
tags: []
}
let that = this
this.tagList = [
["spelling", "Spelling"],
["punctuation", "Punctuation"],
["grammar", "Grammar"],
["meaning", "Meaning"],
["wordChoice", "Word Choice"],
["other", "Other"]
]
this.actions = {
handleGoToNext: function() {
props.actions.goToNext()
},
handleGoToPrevious: function() {
props.actions.goToPrevious()
},
changeSelections: function(selections) {
// optimize the selections to address potential issues and save
selections = SelectionHelpers.optimizeSelections(that.verseText, selections);
props.actions.changeSelections(selections, props.loginReducer.userdata.username)
},
changeMode: function(mode) {
let newState = that.state
newState.mode = mode
that.setState(newState)
},
handleComment: function(e) {
const comment = e.target.value
let newState = that.state
newState.comment = comment
that.setState(newState)
},
cancelComment: function(e) {
that.setState({
mode: 'select',
comment: undefined
})
},
saveComment: function() {
that.props.actions.addComment(that.state.comment, that.props.loginReducer.userdata.username)
that.setState({
mode: 'select',
comment: undefined
})
},
handleTagsCheckbox: function(tag, e) {
let newState = that.state
if (newState.tags === undefined) newState.tags = []
if (!newState.tags.includes(tag)) {
newState.tags.push(tag)
} else {
newState.tags = newState.tags.filter( _tag => _tag !== tag)
}
that.setState(newState)
},
handleEditVerse: function(e) {
const verseText = e.target.value
let newState = that.state
newState.verseText = verseText
that.setState(newState)
},
cancelEditVerse: function(e) {
that.setState({
mode: 'select',
verseText: undefined,
tags: []
})
},
saveEditVerse: function() {
let {targetVerse, loginReducer, actions} = that.props
let before = targetVerse
let username = loginReducer.userdata.username
actions.addVerseEdit(before, that.state.verseText, that.state.tags, username)
that.setState({
mode: 'select',
verseText: undefined,
tags: []
})
},
toggleReminder: function() {
that.props.actions.toggleReminder(that.props.loginReducer.userdata.username)
}
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.contextIdReducer.contextId != this.props.contextIdReducer.contextId) {
this.setState({
mode: 'select',
comments: undefined,
verseText: undefined,
tags: []
})
}
}
render() {
let that = this
let {chapter, verse} = this.props.contextIdReducer.contextId.reference
if (this.props.resourcesReducer.bibles.targetLanguage) {
this.verseText = this.props.resourcesReducer.bibles.targetLanguage[chapter][verse];
} else {
this.verseText = null;
}
return (
<MuiThemeProvider>
<View {...this.props} actions={this.actions}
mode={this.state.mode}
comment={this.state.comment !== undefined ? this.state.comment : this.props.commentsReducer.text}
verseText={this.state.verseText !== undefined ? this.state.verseText : this.verseText}
tags={this.state.tags}
/>
</MuiThemeProvider>
);
}
}
module.exports = {
name: NAMESPACE,
container: VerseCheck
}
| JavaScript | 0.000003 | @@ -2827,16 +2827,57 @@
actions
+, contextIdReducer, projectDetailsReducer
%7D = that
@@ -3046,33 +3046,105 @@
e.tags, username
-)
+, contextIdReducer.contextId, projectDetailsReducer.projectSaveLocation);
%0A that.se
@@ -3182,40 +3182,8 @@
t',%0A
- verseText: undefined,%0A
@@ -3657,25 +3657,24 @@
that = this%0A
-%0A
let %7Bcha
|
785151564291dcc0d1482758b3a723976f4878d7 | fix in content visibility | src/javascript/static/pages/home.js | src/javascript/static/pages/home.js | const Login = require('../../_common/base/login');
const localize = require('../../_common/localize').localize;
const State = require('../../_common/storage').State;
const TabSelector = require('../../_common/tab_selector');
const urlFor = require('../../_common/url').urlFor;
const BinaryPjax = require('../../app/base/binary_pjax');
const BinarySocket = require('../../app/base/socket');
const isEuCountry = require('../../app/common/country_base').isEuCountry;
const FormManager = require('../../app/common/form_manager');
const isBinaryApp = require('../../config').isBinaryApp;
const Home = (() => {
let clients_country;
const onLoad = () => {
TabSelector.onLoad();
BinarySocket.wait('website_status', 'authorize', 'landing_company').then(() => {
clients_country = State.getResponse('website_status.clients_country');
// we need to initiate selector after it becoming visible
TabSelector.repositionSelector();
const form_id = '#frm_verify_email';
FormManager.init(form_id, [
{ selector: '#email', validations: ['req', 'email'], request_field: 'verify_email' },
{ request_field: 'type', value: 'account_opening' },
]);
FormManager.handleSubmit({
form_selector : form_id,
fnc_response_handler: handler,
fnc_additional_check: checkCountry,
});
socialLogin();
if (isEuCountry()) {
$('.mfsa_message').slideDown(300);
$('.eu-hide').setVisibility(0);
}
});
};
const socialLogin = () => {
$('#google-signup').off('click').on('click', (e) => {
e.preventDefault();
window.location.href = Login.socialLoginUrl('google');
});
};
const checkCountry = (req) => {
if ((clients_country !== 'my') || /@binary\.com$/.test(req.verify_email)) {
return true;
}
$('#frm_verify_email').find('div')
.html($('<p/>', { class: 'notice-msg center-text', html: localize('Sorry, account signup is not available in your country.') }));
return false;
};
const handler = (response) => {
const error = response.error;
if (error) {
$('#signup_error').setVisibility(1).text(error.message);
} else if (isBinaryApp()) {
BinaryPjax.load(urlFor('new_account/virtualws'));
} else {
$('.signup-box div').replaceWith($('<p/>', { text: localize('Thank you for signing up! Please check your email to complete the registration process.'), class: 'gr-10 gr-centered center-text' }));
$('#social-signup').setVisibility(0);
}
};
const onUnload = () => {
TabSelector.onUnload();
};
return {
onLoad,
onUnload,
};
})();
module.exports = Home;
| JavaScript | 0.000003 | @@ -1595,56 +1595,8 @@
0);%0A
- $('.eu-hide').setVisibility(0);%0A
|
d4065427962c1bcfae1ed3f0a14c2eb2ae8f73b2 | fix lint | src/layers/grid-layer/grid-layer.js | src/layers/grid-layer/grid-layer.js | // Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Layer from '../../layer';
import {Model, Program, Geometry} from 'luma.gl';
const glslify = require('glslify');
const ATTRIBUTES = {
positions: {size: 3, '0': 'x', '1': 'y', '2': 'unused'},
colors: {size: 4, '0': 'red', '1': 'green', '2': 'blue', '3': 'alpha'}
};
export default class GridLayer extends Layer {
static get attributes() {
return ATTRIBUTES;
}
/**
* @classdesc
* GridLayer
*
* @class
* @param {object} opts
* @param {number} opts.unitWidth - width of the unit rectangle
* @param {number} opts.unitHeight - height of the unit rectangle
*/
constructor(opts) {
super({
unitWidth: 100,
unitHeight: 100,
...opts
});
}
initializeState() {
const {gl, attributeManager} = this.state;
this.setState({
model: this.getModel(gl)
});
attributeManager.addInstanced(ATTRIBUTES, {
positions: {update: this.calculatePositions},
colors: {update: this.calculateColors}
});
this.updateCell();
}
willReceiveProps(oldProps, newProps) {
super.willReceiveProps(oldProps, newProps);
const cellSizeChanged =
newProps.unitWidth !== oldProps.unitWidth ||
newProps.unitHeight !== oldProps.unitHeight;
if (cellSizeChanged || this.state.viewportChanged) {
this.updateCell();
}
}
getModel(gl) {
return new Model({
program: new Program(gl, {
vs: glslify('./grid-layer-vertex.glsl'),
fs: glslify('./grid-layer-fragment.glsl'),
id: 'grid'
}),
geometry: new Geometry({
id: this.props.id,
drawMode: 'TRIANGLE_FAN',
vertices: new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0])
}),
instanced: true
});
}
updateCell() {
const {width, height, unitWidth, unitHeight} = this.props;
const numCol = Math.ceil(width * 2 / unitWidth);
const numRow = Math.ceil(height * 2 / unitHeight);
this.setState({
numCol,
numRow,
numInstances: numCol * numRow
});
const {attributeManager} = this.state;
attributeManager.invalidateAll();
const MARGIN = 2;
const scale = new Float32Array([
unitWidth - MARGIN * 2,
unitHeight - MARGIN * 2,
1
]);
this.setUniforms({scale});
}
calculatePositions(attribute, numInstances) {
const {unitWidth, unitHeight, width, height} = this.props;
const {numCol} = this.state;
const {value, size} = attribute;
for (let i = 0; i < numInstances; i++) {
const x = i % numCol;
const y = Math.floor(i / numCol);
value[i * size + 0] = x * unitWidth - width;
value[i * size + 1] = y * unitHeight - height;
value[i * size + 2] = 0;
}
}
calculateColors(attribute) {
const {data, unitWidth, unitHeight, width, height} = this.props;
const {numCol, numRow} = this.state;
const {value, size} = attribute;
value.fill(0.0);
for (const point of data) {
const pixel = this.project([point.position.y, point.position.x]);
const space = this.screenToSpace(pixel);
const colId = Math.floor((space.x + width) / unitWidth);
const rowId = Math.floor((space.y + height) / unitHeight);
if (colId < numCol && rowId < numRow) {
const i4 = (colId + rowId * numCol) * size;
value[i4 + 0] += 1;
value[i4 + 1] += 5;
value[i4 + 2] += 1;
value[i4 + 3] = 0.6;
}
}
this.setUniforms({maxCount: Math.max(...value)});
}
}
| JavaScript | 0.000013 | @@ -4435,16 +4435,32 @@
lue%5Bi4 +
+ 2%5D = value%5Bi4 +
0%5D += 1
@@ -4493,36 +4493,8 @@
5;%0A
- value%5Bi4 + 2%5D += 1;%0A
|
643c4f809de50861fcc63df149d56a8034340ad3 | Add differencesById function to get the differences between to arrays of objects that contain an 'id' field. | website/app/index/util.js | website/app/index/util.js | function isImage(mime) {
switch (mime) {
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
case "image/x-ms-bmp":
case "image/bmp":
return true;
default:
return false;
}
}
function numberWithCommas(n) {
n = n.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(n)) {
n = n.replace(pattern, "$1,$2");
}
return n;
}
function bytesToSizeStr(bytes) {
if(bytes === 0) return '0 Byte';
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function _add_json_callback(url) {
return url + "&callback=JSON_CALLBACK";
}
function _add_json_callback2(url) {
var qIndex = url.indexOf("?");
var argSeparator = "&";
if (qIndex == -1) {
argSeparator = "?";
}
return url + argSeparator + "callback=JSON_CALLBACK";
}
String.prototype.capitalize = function () {
return this.replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
};
// save a reference to the core implementation
var indexOfValue = _.indexOf;
// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({
// return the index of the first array element passing a test
indexOf: function (array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}
});
| JavaScript | 0 | @@ -1120,16 +1120,415 @@
CK%22;%0A%7D%0A%0A
+function differenceById(from, others) %7B%0A var idsFrom = from.map(function(entry) %7B%0A return entry.id;%0A %7D);%0A var idsOthers = others.map(function(entry) %7B%0A return entry.id;%0A %7D);%0A%0A var diff = _.difference(idsFrom, idsOthers);%0A return from.filter(function(entry) %7B%0A return _.indexOf(diff, function(e) %7B%0A return e == entry.id;%0A %7D) !== -1;%0A %7D)%0A%7D%0A%0A
String.p
@@ -2305,13 +2305,12 @@
;%0A %7D%0A
-%0A
%7D);%0A
|
3a4825862bae25157bbfefe51eb0d9a9f70b1d8e | Add test on robot to check instanciation with serialPort | tests/server/robot_test.js | tests/server/robot_test.js | var chai = require('chai');
var expect = chai.expect;
var Robot = require('../../src/Robot');
var sinon = require('sinon');
describe('Robot', function() {
describe('#contructor', function() {
it('should be instanciate', function() {
var robot = new Robot
expect(robot).to.be.instanceof(Robot);
});
it('should be instanciate with an adapater', function() {
var robot = new Robot();
});
});
describe('#setSpeed', function() {
it('should set speed with an amplitude and alpha', function() {
var robot = new Robot();
robot.setSpeed(2, 100);
expect(robot.x).to.be.equal(-42);
expect(robot.y).to.be.equal(-91);
});
});
describe('#move', function() {
var sandbox;
var fakeSerialPort;
var robot;
beforeEach(function() {
sandbox = sinon.sandbox.create();
fakeSerialPort = {
write: sinon.spy()
};
robot = new Robot(fakeSerialPort);
robot.x = 41;
robot.y = 90;
});
it('should write x,y on serial port', function(done) {
robot.move();
sinon.assert.calledWithExactly(fakeSerialPort.write, sinon.match(function(value) {
return JSON.stringify(value.toJSON())=== JSON.stringify([robot.x, robot.y]);
}));
done();
});
afterEach(function(done) {
sandbox.restore();
done();
});
});
});
| JavaScript | 0 | @@ -387,34 +387,123 @@
var
-robot = new Robot(
+fakeAdapter = %7B%7D;%0A var robot = new Robot(fakeAdapter);%0A expect(robot.serialPort).to.deep.equal(%7B%7D
);%0A %7D
|
52f786328eba779610777cf14b7943e7d8cab282 | Disable import/export linting rule since it will fail when only one action is defined, but pass on mutliple actions | generators/root/templates/action/const.js | generators/root/templates/action/const.js | /* Populated by react-webpack-redux:action */
| JavaScript | 0 | @@ -1,8 +1,58 @@
+/* eslint-disable import/prefer-default-export */%0A
/* Popul
|
077407297bc919cf829aaf60b4236a326c49d436 | improve build config | scripts/rollup.config.js | scripts/rollup.config.js | import commonjs from 'rollup-plugin-commonjs'
import nodeResolve from 'rollup-plugin-node-resolve'
import json from 'rollup-plugin-json'
import babel from 'rollup-plugin-babel'
import buble from 'rollup-plugin-buble'
import { terser } from 'rollup-plugin-terser'
const pkg = require('../package.json')
const banner = `/**
* vue-meta v${pkg.version}
* (c) ${new Date().getFullYear()} Declan de Wet & Sébastien Chopin (@Atinux)
* @license MIT
*/
`.replace(/ {4}/gm, '').trim()
const baseConfig = {
input: 'src/browser.js',
output: {
file: pkg.web,
format: 'umd',
name: 'VueMeta',
sourcemap: false,
banner
},
plugins: [
json(),
nodeResolve(),
commonjs(),
/*buble({
objectAssign: 'Object.assign'
}),*/
]
}
export default [{
...baseConfig,
}, {
...baseConfig,
output: {
...baseConfig.output,
file: pkg.web.replace('.js', '.min.js'),
},
plugins: [
...baseConfig.plugins,
babel({
runtimeHelpers: true,
presets: ['@nuxt/babel-preset-app']
}),
terser()
]
}, {
...baseConfig,
input: 'src/index.js',
output: {
...baseConfig.output,
file: pkg.main,
format: 'cjs'
},
external: Object.keys(pkg.dependencies)
}]
| JavaScript | 0.000022 | @@ -255,16 +255,63 @@
-terser'
+%0Aimport defaultsDeep from 'lodash/defaultsDeep'
%0A%0Aconst
@@ -527,29 +527,106 @@
()%0A%0A
-const baseC
+function rollupConfig(%7B%0A plugins = %5B%5D,%0A ...config%0A %7D) %7B%0A%0A return defaultsDeep(%7B%7D, c
onfig
- =
+,
%7B%0A
+
in
@@ -642,32 +642,34 @@
/browser.js',%0A
+
+
output: %7B%0A fi
@@ -670,23 +670,29 @@
-file: pkg.web,%0A
+ name: 'VueMeta',%0A
@@ -709,38 +709,19 @@
md',%0A
- name: 'VueMeta',%0A
-
sourcema
@@ -738,22 +738,28 @@
+
banner%0A
+
%7D,%0A
+
+
plug
@@ -773,16 +773,18 @@
+
json(),%0A
@@ -775,24 +775,26 @@
json(),%0A
+
nodeReso
@@ -802,88 +802,216 @@
ve()
-,
%0A
-commonjs(),%0A /*buble(%7B%0A objectAssign: 'Object.assign'%0A %7D),*/
+%5D.concat(plugins),%0A %7D)%0A%7D%0A%0Aconst babelConfig = %7B%0A runtimeHelpers: true,%0A exclude : 'node_modules/**',%0A presets: %5B%5B'@nuxt/babel-preset-app', %7B%0A // useBuiltIns: 'usage',%0A // target: %7B ie: 9 %7D
%0A
+%7D%5D
%5D%0A%7D%0A
@@ -1031,91 +1031,175 @@
lt %5B
-%7B
%0A
-...baseConfig,%0A%7D, %7B%0A ...base
+rollupConfig(%7B%0A output: %7B%0A file: pkg.web,%0A %7D,%0A plugins: %5B%0A babel(babel
Config
+)
,%0A
-output: %7B%0A ...baseConfig.
+ commonjs()%0A %5D%0A %7D),%0A rollupConfig(%7B%0A
output
-,%0A
+: %7B%0A
+
file
@@ -1235,21 +1235,25 @@
n.js'),%0A
+
%7D,%0A
+
plugin
@@ -1265,121 +1265,50 @@
-...baseConfig.plugins,%0A babel(%7B%0A runtimeHelpers: true,%0A presets: %5B'@nuxt/babel-preset-app'%5D%0A %7D
+ babel(babelConfig),%0A commonjs(
),%0A
+
@@ -1322,32 +1322,37 @@
)%0A
-%5D%0A%7D, %7B%0A ...base
+ %5D%0A %7D),%0A rollup
Config
-,%0A
+(%7B%0A
in
@@ -1374,16 +1374,18 @@
.js',%0A
+
+
output:
@@ -1392,32 +1392,8 @@
%7B%0A
- ...baseConfig.output,%0A
@@ -1408,16 +1408,18 @@
g.main,%0A
+
form
@@ -1428,21 +1428,64 @@
: 'cjs'%0A
+
%7D,%0A
+ plugins: %5B%0A commonjs()%0A %5D,%0A
extern
@@ -1518,11 +1518,15 @@
encies)%0A
-%7D
+ %7D)%0A
%5D%0A
|
7777b2f6b31d3ea8366af600811a8ac13871d302 | Update EnvironmentPlugin TODO comment | lib/EnvironmentPlugin.js | lib/EnvironmentPlugin.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
const WebpackError = require("./WebpackError");
/** @typedef {import("./Compiler")} Compiler */
const needsEnvVarFix =
["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
process.platform === "win32";
class EnvironmentPlugin {
constructor(...keys) {
if (keys.length === 1 && Array.isArray(keys[0])) {
this.keys = keys[0];
this.defaultValues = {};
} else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") {
this.keys = Object.keys(keys[0]);
this.defaultValues = keys[0];
} else {
this.keys = keys;
this.defaultValues = {};
}
}
/**
* @param {Compiler} compiler webpack compiler instance
* @returns {void}
*/
apply(compiler) {
const definitions = this.keys.reduce((defs, key) => {
// TODO remove once the fix has made its way into Node 8.
// Work around https://github.com/nodejs/node/pull/18463,
// affecting Node 8 & 9 by performing an OS-level
// operation that always succeeds before reading
// environment variables:
if (needsEnvVarFix) require("os").cpus();
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
if (value === undefined) {
compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => {
const error = new WebpackError(
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.warnings.push(error);
});
}
defs[`process.env.${key}`] =
value === undefined ? "undefined" : JSON.stringify(value);
return defs;
}, {});
new DefinePlugin(definitions).apply(compiler);
}
}
module.exports = EnvironmentPlugin;
| JavaScript | 0 | @@ -946,12 +946,12 @@
%09//
-TODO
+NOTE
rem
@@ -967,40 +967,41 @@
the
-fix has made its way into Node 8
+required node version is %3E=8.10.0
.%0A%09%09
|
b3cec47999a8be85b616546e53665ab56396c836 | fix export | src/Parser/Core/Modules/Items/BFA/Dungeons/HarlansLoadedDice.js | src/Parser/Core/Modules/Items/BFA/Dungeons/HarlansLoadedDice.js | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'Parser/Core/Analyzer';
import { formatPercentage, formatNumber } from 'common/format';
import { calculateSecondaryStatDefault } from 'common/stats';
/**
* Harlan's Loaded Dice
* Your attacks and abilities have a chance to roll the loaded dice, gaining a random combination of Mastery, Haste, and Critical Strike for 15 sec.
*
* Example: https://www.warcraftlogs.com/reports/LR2jNyrk3GmPXgZ9#fight=4&type=auras&source=5
*/
class GalecallersBoon extends Analyzer {
smallBuffValue = 0;
bigBuffValue = 0;
smallBuffs = [
SPELLS.LOADED_DIE_CRITICAL_STRIKE_SMALL.id,
SPELLS.LOADED_DIE_HASTE_SMALL.id,
SPELLS.LOADED_DIE_MASTERY_SMALL.id,
];
bigBuffs = [
SPELLS.LOADED_DIE_MASTERY_BIG.id,
SPELLS.LOADED_DIE_CRITICAL_STRIKE_BIG.id,
SPELLS.LOADED_DIE_HASTE_BIG.id,
];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.HARLANS_LOADED_DICE.id);
if (this.active) {
this.smallBuffValue = calculateSecondaryStatDefault(355, 169, this.selectedCombatant.getItem(ITEMS.HARLANS_LOADED_DICE.id).itemLevel);
this.bigBuffValue = calculateSecondaryStatDefault(355, 284, this.selectedCombatant.getItem(ITEMS.HARLANS_LOADED_DICE.id).itemLevel);
}
}
get bigBuffUptime() {
return this.bigBuffs.reduce((a, b) => a + this.selectedCombatant.getBuffUptime(b), 0) / 3 / this.owner.fightDuration;
}
get smallBuffUptime() {
return this.smallBuffs.reduce((a, b) => a + this.selectedCombatant.getBuffUptime(b), 0) / 3 / this.owner.fightDuration;
}
get totalBuffUptime() {
return (this.bigBuffUptime + this.smallBuffUptime);
}
getAverageCrit() {
return (this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_CRITICAL_STRIKE_BIG.id) * this.bigBuffValue + this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_CRITICAL_STRIKE_SMALL.id) * this.smallBuffValue) / this.owner.fightDuration;
}
getAverageHaste() {
return (this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_HASTE_BIG.id) * this.bigBuffValue + this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_HASTE_SMALL.id) * this.smallBuffValue) / this.owner.fightDuration;
}
getAverageMastery() {
return (this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_MASTERY_BIG.id) * this.bigBuffValue + this.selectedCombatant.getBuffUptime(SPELLS.LOADED_DIE_MASTERY_SMALL.id) * this.smallBuffValue) / this.owner.fightDuration;
}
buffTriggerCount() { //Either the big buff or the small buff will be applied on a proc, so just counting the mastery gets total amount of procs.
return this.selectedCombatant.getBuffTriggerCount(SPELLS.LOADED_DIE_MASTERY_SMALL.id) + this.selectedCombatant.getBuffTriggerCount(SPELLS.LOADED_DIE_MASTERY_BIG.id);
}
item() {
return {
item: ITEMS.HARLANS_LOADED_DICE,
result: (
<dfn data-tip={`
<ul>
<li>Procced ${this.buffTriggerCount()} times.</li>
<li>You had an uptime of ${formatPercentage(this.smallBuffUptime)}% on the small buffs.</li>
<li> You had an uptime of ${formatPercentage(this.bigBuffUptime)}% on the large buffs.</li>
</ul>`}>
{formatPercentage(this.totalBuffUptime)}% uptime<br />
{formatNumber(this.getAverageHaste())} average Haste<br />
{formatNumber(this.getAverageCrit())} average Crit<br />
{formatNumber(this.getAverageMastery())} average Mastery
</dfn>
),
};
}
}
export default GalecallersBoon;
| JavaScript | 0.000001 | @@ -548,31 +548,33 @@
/%0Aclass
-GalecallersBoon
+HarlansLoadedDice
extends
@@ -3576,21 +3576,23 @@
ult
-GalecallersBoon
+HarlansLoadedDice
;%0A
|
cea687e75c54459b2d04ee3d65bbb994cfccb66e | Update locales verify script to count special chars | scripts/locales/verify.js | scripts/locales/verify.js | const fs = require('fs')
const path = require('path')
const defaultLocale = require('../../src/config.js').bot.locale
const COLORS = {
RESET: '\x1b[0m',
RED: '\x1b[31m',
GREEN: '\x1b[32m',
CYAN: '\x1b[36m'
}
const referenceLocaleData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', `${defaultLocale}.json`)))
const fileNames = fs.readdirSync(path.join(__dirname, '..', '..', 'src', 'locales'))
const errorStringsByLocale = {}
function traverse (object, reference, location, locale) {
for (const key in reference) {
if (typeof reference[key] !== typeof object[key]) {
errorStringsByLocale[locale].push(`${COLORS.CYAN}${location}[${key}]${COLORS.RESET} expected ${COLORS.GREEN}${typeof reference[key]}${COLORS.RESET} but found ${COLORS.RED}${typeof object[key]}${COLORS.RESET}`)
} else if (typeof reference[key] === 'object' && typeof object[key] === 'object') {
traverse(object[key], reference[key], location + `[${key}]`, locale)
}
}
}
for (const fileName of fileNames) {
const localeData = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'locales', fileName)))
const locale = fileName.replace('.json', '')
errorStringsByLocale[locale] = []
traverse(localeData, referenceLocaleData, locale, locale)
}
const okStrings = []
const errorStrings = []
for (const locale in errorStringsByLocale) {
const strings = errorStringsByLocale[locale]
if (strings.length === 0) {
okStrings.push(`${COLORS.GREEN}√${COLORS.RESET} ${locale} ${locale === 'en-US' ? '(Reference)' : ''}`)
continue
}
// Prettify the logs
let longestLocation = 0
for (const line of strings) {
const parts = line.split('expected')
const location = parts[0]
if (location.length > longestLocation) {
longestLocation = location.length
}
}
for (let i = 0; i < strings.length; ++i) {
const parts = strings[i].split('expected')
let location = parts[0]
while (location.length < longestLocation) {
location += ' '
}
parts[0] = location
strings[i] = parts.join('expected')
}
errorStrings.push(`${COLORS.RED}X${COLORS.RESET} ${locale}\n${strings.join('\n')}`)
}
console.log(okStrings.join('\n'))
console.log(errorStrings.join('\n'))
console.log(`\nNote that for untranslated strings, their values must be "" (an empty string). They cannot be undefined.\nEmpty string translations will fall back to using the default en-US strings.`) | JavaScript | 0 | @@ -128,16 +128,37 @@
ORS = %7B%0A
+ BRIGHT: '%5Cx1b%5B1m',%0A
RESET:
@@ -230,16 +230,61 @@
%5B36m'%0A%7D%0A
+const CONSTANT_CHARACTERS = %5B'%22', '%5Cn', '%60'%5D%0A
const re
@@ -494,16 +494,17 @@
les'))%0A%0A
+%0A
const er
@@ -944,43 +944,8 @@
ect'
- && typeof object%5Bkey%5D === 'object'
) %7B%0A
@@ -988,24 +988,554 @@
e%5Bkey%5D,
+location + %60%5B$%7Bkey%7D%5D%60, locale)%0A %7D else if (typeof reference%5Bkey%5D === 'string' && object%5Bkey%5D.length %3E 0) %7B%0A for (const character of CONSTANT_CHARACTERS) %7B%0A const referenceCharCount = (reference%5Bkey%5D.match(new RegExp(character, 'g')) %7C%7C %5B%5D).length%0A const charCount = (object%5Bkey%5D.match(new RegExp(character, 'g')) %7C%7C %5B%5D).length%0A if (referenceCharCount !== charCount) %7B%0A const printCharacter = character === '%5Cn' ? '%5C%5Cn' : character%0A errorStringsByLocale%5Blocale%5D.push(%60$%7BCOLORS.CYAN%7D$%7B
location
+ %60%5B$%7Bk
@@ -1522,36 +1522,33 @@
N%7D$%7Blocation
- + %60
+%7D
%5B$%7Bkey%7D%5D
%60, locale)%0A
@@ -1539,67 +1539,365 @@
ey%7D%5D
-%60, locale)%0A %7D%0A %7D%0A%7D%0A%0Afor (const fileName of fileNames) %7B
+$%7BCOLORS.RESET%7D expected $%7BCOLORS.GREEN%7D$%7BreferenceCharCount%7D $%7BCOLORS.BRIGHT%7D$%7BprintCharacter%7D$%7BCOLORS.RESET%7D character(s)$%7BCOLORS.RESET%7D but found $%7BCOLORS.RED%7D$%7BcharCount%7D $%7BCOLORS.BRIGHT%7D$%7BprintCharacter%7D$%7BCOLORS.RESET%7D character(s)%60)%0A %7D%0A %7D%0A %7D%0A %7D%0A%7D%0A%0Afor (const fileName of fileNames) %7B%0A if (fileName === 'en-US.json') %7B%0A continue%0A %7D
%0A c
|
bd697ab9f5db3f6e9377f93c5b946795b59eab28 | update vendor bundle to include new packages | webpack.config.vendor.js | webpack.config.vendor.js | const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
var AssetsPlugin = require('assets-webpack-plugin');
var assetsPluginInstance = new AssetsPlugin({ filename: 'vendor-assets.json' });
const BUILD_DIR = path.resolve(__dirname, 'public');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const sharedConfig = {
stats: { modules: false },
resolve: { extensions: ['.js'] },
module: {
rules: [
{ test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-loader?limit=100000' }
]
},
entry: {
vendor: [
'bootstrap',
'babel-polyfill',
'event-source-polyfill',
'react',
'react-async-script',
'react-bootstrap-slider',
'react-bootstrap-typeahead',
'react-google-recaptcha',
'react-dom',
'react-redux',
'react-redux-toastr',
'redux',
'redux-thunk',
'jquery',
'jquery-migrate',
'jquery-nearest',
'jquery-validation',
'jquery-validation-unobtrusive',
'moment',
'prop-types',
'socket.io-client',
'underscore'
]
},
devtool: isDevBuild ? 'inline-source-map' : 'source-map',
output: {
publicPath: '/',
filename: '[name]-[hash].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new webpack.NormalModuleReplacementPlugin(/\/iconv-loader$/, require.resolve('node-noop')), // Workaround for https://github.com/andris9/encoding/issues/16
assetsPluginInstance
]
};
const clientBundleConfig = merge(sharedConfig, {
output: { path: BUILD_DIR },
module: {
rules: [
]
},
plugins: [
new webpack.DllPlugin({
path: path.join(BUILD_DIR, '[name]-manifest.json'),
name: '[name]_[hash]'
})
]
});
return clientBundleConfig;
};
| JavaScript | 0 | @@ -1414,16 +1414,82 @@
erscore'
+,%0A 'query-string',%0A 'path-to-regexp'
%0A
|
7fe248ce228359a0e5e00fc229df2d032614a9d5 | Allow more powerful overrides in lazylinkfield | src/resources/elements/lazylinkfield.js | src/resources/elements/lazylinkfield.js | import {containerless} from 'aurelia-framework';
import {Field} from './abstract/field';
/**
* LazyLinkfield is a field that lazily proxies the a whole field (value & UI)
* to another place.
*/
@containerless
export class LazyLinkfield extends Field {
target = '#';
overrides = {};
_child = undefined;
/** @inheritdoc */
init(id = '', args = {}) {
this.target = args.target || '#';
this.overrides = args.overrides || {};
return super.init(id, args);
}
createChild() {
this._child = this.resolveRef(this.target).clone();
this._child.parent = this;
for (const [field, value] of Object.entries(this.overrides)) {
const lastSlash = field.lastIndexOf('/');
const path = field.substr(0, lastSlash);
const fieldName = field.substr(lastSlash + 1, field.length);
this._child.resolveRef(path)[fieldName] = value;
}
}
deleteChild() {
this._child = undefined;
}
shouldDisplay() {
const display = super.shouldDisplay();
if (display) {
if (this._child === undefined) {
this.createChild();
}
} else if (this._child !== undefined) {
this.deleteChild();
}
return display;
}
get child() {
return this.display ? this._child : undefined;
}
/**
* Set the value of the target field.
*
* @override
* @param {Object} value The new value to set to the target field.
*/
setValue(value) {
if (!this._child) {
return;
}
this._child.setValue(value);
}
/**
* Get the value of the target field.
*
* @override
* @return {Object} The value of the target field, or undefined if
* {@link #resolveTarget} returns {@linkplain undefined}.
*/
getValue() {
return this._child ? this._child.getValue() : undefined;
}
}
| JavaScript | 0 | @@ -657,224 +657,821 @@
-const lastSlash = field.lastIndexOf('/');%0A const path = field.substr(0, lastSlash);%0A const fieldName = field.substr(lastSlash + 1, field.length);%0A this._child.resolveRef(path)%5BfieldName%5D = value;%0A %7D
+let target;%0A let fieldPath;%0A if (field.includes(';')) %7B%0A %5BelementPath, fieldPath%5D = field.split(';');%0A fieldPath = fieldPath.split('/');%0A target = this._child.resolveRef(elementPath);%0A %7D else %7B%0A fieldPath = field.split('/');%0A target = this._child;%0A %7D%0A const lastFieldPathEntry = fieldPath.splice(-1)%5B0%5D;%0A target = this.resolveRawPath(target, fieldPath);%0A if (value === null) %7B%0A delete target%5BlastFieldPathEntry%5D;%0A %7D else %7B%0A target%5BlastFieldPathEntry%5D = value;%0A %7D%0A %7D%0A %7D%0A%0A resolveRawPath(object, path) %7B%0A if (path.length === 0) %7B%0A return object;%0A %7D else if (path%5B0%5D === '#') %7B%0A return this.resolveRawPath(object, path.splice(1));%0A %7D%0A return this.resolveRawPath(object%5Bpath%5B0%5D%5D, path.splice(1));
%0A %7D
|
f24b7ba1d4c03810d84f35c0e75919d216817851 | Add missing js | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Index.js | src/SumoCoders/FrameworkCoreBundle/Resources/assets/js/Index.js | import {Ajax} from './Framework/Ajax'
import {Form} from './Framework/Form'
import {Link} from './Framework/Link'
import {LoadingBar} from './Framework/LoadingBar'
import {Navbar} from './Framework/Navbar'
import {Popover} from './Framework/Popover'
import {Scrolling} from './Framework/Scrolling'
import {SetHeight} from './Framework/SetHeight'
import {Searchbar} from './Framework/Searchbar'
import {Select} from './Framework/Select'
import {Slider} from './Framework/Slider'
import {Sortable} from './Framework/Sortable'
import {Table} from './Framework/Table'
import {Tabs} from './Framework/Tabs'
import {Tooltip} from './Framework/Tooltip'
export class Index {
constructor () {
this.ajax = new Ajax()
this.form = new Form()
this.link = new Link()
this.loadingBar = new LoadingBar()
this.navbar = new Navbar()
this.scrolling = new Scrolling()
this.setHeight = new SetHeight()
this.searchBar = new Searchbar()
this.table = new Table()
this.tabs = new Tabs()
this.initializeSliders()
this.initializeSortables()
this.initializePopovers()
this.initializeTooltips()
this.initializeSelects()
}
initializeSliders () {
$('.slider').each((index, element) => {
element.slider = new Slider($(element))
})
}
initializeSortables () {
$('.sortable').each((index, element) => {
element.sortable = new Sortable($(element))
})
}
initializePopovers () {
$('[data-toggle="popover"]').each((index, element) => {
element.popover = new Popover($(element))
})
}
initializeTooltips () {
$('[data-toggle="tooltip"]').each((index, element) => {
element.tooltip = new Tooltip($(element))
})
}
initializeSelects () {
$('.select2').each((index, element) => {
element.select2 = new Select($(element))
})
}
}
window.index = new Index()
| JavaScript | 0.999043 | @@ -1148,16 +1148,54 @@
lects()%0A
+ this.initializeOtherChoiceTypes()%0A
%7D%0A%0A i
@@ -1872,16 +1872,506 @@
%7D)%0A %7D
+%0A%0A initializeOtherChoiceTypes () %7B%0A $(function() %7B%0A $('%5Bdata-role=other-choice-list%5D').on('change', function() %7B%0A let $select = $(this)%0A let $textField = $select.closest('%5Bdata-role=other-choice-wrapper%5D').find('%5Bdata-role=other-choice-text-input%5D')%0A if ($select.val() === 'other') %7B%0A $textField.show().focus()%0A $select.hide()%0A%0A return%0A %7D%0A%0A $textField.hide()%0A $select.show()%0A %7D).trigger('change')%0A %7D)%0A %7D
%0A%7D%0A%0Awind
|
0943dd66807181b67745c7ab9a312a8f048ee4c0 | add mainFields | webpack_config/common.js | webpack_config/common.js | /*eslint-env node*/
const path = require('path');
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
entry: './src/entry.js',
},
output: {
path: path.resolve('./dist'),
publicPath: '/dist/',
filename: '[name].js',
jsonpFunction: 'entryJsonp',
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
node: {
fs: 'empty',
},
module: {
rules: [
{
test: /\.worker\.ts$/,
use: {
loader: 'worker-loader',
options: {
inline: true,
},
},
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'webpack-strip-block',
options: {
start: 'IGNORE_WEBPACK:START',
end: 'IGNORE_WEBPACK:END',
},
},
{
loader: 'babel-loader',
},
],
},
{
// eslint-disable-next-line max-len
test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot|cur)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
name: '[hash].[ext]',
limit: 10000,
},
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: { transpileOnly: true },
},
{
test: /\.(css|less)$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publ icPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../',
},
},
{
loader: 'css-loader',
options: {
url: false,
sourceMap: false,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('cssnano')({ preset: 'default' }),
autoprefixer({
overrideBrowserslist: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
remove: false,
}),
],
},
},
{
loader: 'less-loader',
options: {
sourceMap: false,
},
},
],
},
],
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
'@entrylabs/tool': 'EntryTool',
'entry-paint': 'EntryPaint',
},
plugins: [
new CleanWebpackPlugin(['dist'], {
root: path.join(__dirname, '..'),
}),
new ManifestPlugin(),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
| JavaScript | 0.000001 | @@ -572,16 +572,82 @@
json'%5D,%0A
+ mainFields: %5B'jsnext:main', 'main', 'module', 'browser'%5D,%0A
%7D,%0A
|
2c3d10a4c63354899c1e077a6f1a2dc890eed2b7 | Test corrected. | tests/test-apache-crypt.js | tests/test-apache-crypt.js | // Apache crypt.
var crypt = require('../lib/apache-crypt');
module.exports = {
// Test for valid password.
testValidPassword: function(test) {
var crypted = crypt("validPass", "B5xBYM2HbnPqI");
test.ok(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
},
// Test for invalid password.
testInValidPassword: function(test) {
var crypted = crypt("invalidPass", "B5xBYM2HbnPqI");
test.notEqual(crypted, "B5xBYM2HbnPqI", "Wrong password!");
test.done();
}
}; | JavaScript | 0 | @@ -223,10 +223,13 @@
est.
-ok
+equal
(cry
|
297a9ea827655e5fb406a86907bb0d89b01deae8 | fix typo | tests/test-localAddress.js | tests/test-localAddress.js | var request = request = require('../index')
, assert = require('assert')
;
request.get({
uri: 'http://www.google.com', localAddress: '1.2.3.4' // some invalid address
}, function(err, res) {
assert(!res) // asserting that no response received
})
request.get({
uri: 'http://www.google.com', localAddress: '127.0.0.1'
}, function(err, res) {
assert(!res) // asserting that no response received
})
| JavaScript | 0.999991 | @@ -6,26 +6,16 @@
equest =
- request =
require
|
9b0bb45721a2dc5b32823b33a7f4576e1a311b9a | 更新 gulpfile | Gulpfile.js | Gulpfile.js | /**
* jshint strict:true
*/
//npm install gulp gulp-minify-css gulp-uglify gulp-clean gulp-cleanhtml gulp-jshint gulp-strip-debug gulp-zip --save-dev
var gulp = require('gulp');
var watch = require('gulp-watch');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var coffee = require('gulp-coffee');
var sass = require('gulp-sass');
var cleanhtml = require('gulp-cleanhtml');
var minifycss = require('gulp-minify-css');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var zip = require('gulp-zip');
var browserify = require('gulp-browserify');
var paths = require('./paths');
gulp.task('clean', function() {
return gulp.src('build/*', { read: false })
.pipe(clean({ force: true }));
});
gulp.task('copy', function() {
return gulp.src(paths.staticFiles, { base: 'src' })
.pipe(gulp.dest('build'));
});
gulp.task('jshint', function() {
return gulp.src(['Gulpfile.js', 'src/js/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('scripts', function() {
var ignore = ['underscore', 'jquery', 'angular', 'angular-elastic'];
gulp.src('src/js/lib/{lib-all,angular-all}.js')
.pipe(browserify())
.pipe(gulp.dest('./build/js/'));
return gulp.src('src/js/*.js')
.pipe(browserify({ignore: ignore}))
.pipe(gulp.dest('./build/js/'));
});
gulp.task('styles', function() {
return gulp.src(paths.styles)
.pipe(sass())
.pipe(gulp.dest('build/css'));
});
gulp.task('build', ['scripts', 'styles', 'copy']);
gulp.task('watch', ['build'], function() {
gulp.watch(paths.static, ['copy']);
gulp.watch(paths['js:app'], ['scripts']);
gulp.watch(paths['js:page'], ['scripts']);
gulp.watch(paths['js:trans'], ['scripts']);
gulp.watch(paths['js:static'], ['scripts']);
gulp.watch(paths.coffee, ['scripts']);
gulp.watch(paths.styles, ['styles']);
});
gulp.task('zip', ['build'], function() {
var manifest = require('./src/manifest');
var filename = manifest.name + ' v' + manifest.version + '.zip';
return gulp.src('build/**/*')
.pipe(zip(filename))
.pipe(gulp.dest('dist'));
});
//run all tasks after build directory has been cleaned
gulp.task('default', ['clean', 'build']); | JavaScript | 0 | @@ -694,36 +694,38 @@
lean', function(
+cb
) %7B%0A
-
return gulp.sr
@@ -787,16 +787,35 @@
true %7D))
+%0A .on('end', cb)
;%0A%7D);%0A%0Ag
@@ -924,16 +924,17 @@
t('build
+/
'));%0A%7D);
@@ -1389,34 +1389,32 @@
pipe(gulp.dest('
-./
build/js/'));%0A%7D)
@@ -1529,16 +1529,17 @@
uild/css
+/
'));%0A%7D);
@@ -1641,163 +1641,173 @@
%7B%0A
-gulp.watch(paths.static, %5B'copy'%5D);%0A gulp.watch(paths%5B'js:app'%5D, %5B'scripts
+function errorHanlder(error) %7B%0A console.log(error);%0A %7D%0A%0A gulp.watch(paths.staticFiles, %5B'copy
'%5D)
-;
%0A
-gulp.watch(paths%5B'js:page'%5D, %5B'scripts'%5D);%0A gulp.watch(paths%5B'js:trans'%5D
+ .on('error', errorHandler);%0A %0A gulp.watch('src/js/**/*'
, %5B'
@@ -1820,57 +1820,42 @@
s'%5D)
-;
%0A
-gulp.watch(paths%5B'js:static'%5D, %5B'scripts'%5D
+ .on('error', errorHandler
);%0A
+%0A
gu
@@ -1867,73 +1867,65 @@
tch(
-paths.coffee, %5B'script
+'src/css/**/*', %5B'style
s'%5D)
-;
%0A
-gulp.watch(paths.styles, %5B'styles'%5D
+ .on('error', errorHandler
);%0A%7D
|
0c0c53589a54fb7f91f8100c5a3d4929bd00f1ff | Update gulpfile to watch contrib styles and not just core project files | Gulpfile.js | Gulpfile.js | var autoprefix = require("gulp-autoprefixer"),
connect = require("gulp-connect"),
gulp = require("gulp"),
sass = require("gulp-sass");
var paths = {
scss: [
"./core/**/*.scss",
"./contrib/styles.scss"]
};
gulp.task("sass", function () {
return gulp.src(paths.scss)
.pipe(sass({
sourcemaps: true
}))
.pipe(autoprefix("last 2 versions"))
.pipe(gulp.dest("./contrib"))
.pipe(connect.reload());
});
gulp.task("connect", function() {
connect.server({
root: "contrib",
port: 8000,
livereload: true
});
});
gulp.task("default", ["sass", "connect"], function() {
gulp.watch(paths.scss, ["sass"]);
});
| JavaScript | 0 | @@ -223,14 +223,12 @@
rib/
-styles
+**/*
.scs
|
81ab1414e614937b4ec0c841cf1dfd83a496193a | Fix use of wrong length value | src/PiecemealDownloadManager.js | src/PiecemealDownloadManager.js | define(['Promise', './PiecemealDownload'], function(Promise, PiecemealDownload) {
'use script';
function PiecemealDownloadManager(url) {
this.url = url;
}
PiecemealDownloadManager.prototype = {
getBytes: function(offset, length) {
offset = +(offset || 0);
if (isNaN(offset) || !isFinite(offset) || offset < 0) {
throw new TypeError('offset must be a finite number >= 0');
}
if (isNaN(length)) length = Infinity;
if (length < 0) {
throw new TypeError('length must be a number >= 0');
}
if (length === 0) {
return Promise.resolve(new Uint8Array(0));
}
var self = this;
return new Promise(function(resolve, reject) {
var dl = new PiecemealDownload(self.url, [{offset:offset, length:length}]);
var buf = new Uint8Array(length);
var count = 0;
dl.onPiece = function(pieceOffset, pieceBytes) {
if (pieceOffset >= (offset + length)) return;
if ((pieceOffset + pieceBytes.length) <= offset) return;
var diff = pieceOffset - offset;
pieceBytes = pieceBytes.subarray(diff, Math.min(pieceBytes.length, diff + pieceBytes.length));
buf.set(pieceBytes, pieceOffset - offset);
count += pieceBytes.length;
if (count === length) {
resolve(buf);
}
};
dl.startDownload();
});
},
};
return PiecemealDownloadManager;
});
| JavaScript | 0.023183 | @@ -1080,27 +1080,16 @@
diff +
-pieceBytes.
length))
|
e7ffafdb5f931701918b86489b8baf67730b24e4 | Refactor JavaScript slightly | website/javascript/api.js | website/javascript/api.js | export const API_SERVER_URL = "http://35.190.3.178/v1/api";
export const LOGIN_SERVER_URL = "http://35.190.3.178/v1/login";
// TODO: also cache login in local cookie so we don't have to do so many round trips
let cached_me = null;
let logged_in = null;
export function me_cached() {
if (window.localStorage["cache"]) {
return {
user_id: window.localStorage["user_id"],
username: window.localStorage["username"],
};
}
else {
return null;
}
}
export function me() {
if (cached_me !== null) return Promise.resolve(cached_me);
else if (logged_in === false) return Promise.resolve(null);
return $.get({
url: `${LOGIN_SERVER_URL}/me`,
xhrFields: {
withCredentials: true,
},
}).then((me) => {
if (me === null) {
logged_in = false;
return null;
}
logged_in = true;
return get_user(me.user_id).then((user) => {
cached_me = user;
// TODO: invalidate this cache every so often
window.localStorage["cache"] = Date.now();
window.localStorage["user_id"] = user.user_id;
window.localStorage["username"] = user.username;
return user;
});
});
}
export function get_user(user_id) {
return $.get({
url: `${API_SERVER_URL}/user/${user_id}`,
xhrFields: {
withCredentials: true,
},
});
}
export function make_profile_image_url(username) {
return `https://github.com/${username}.png`;
}
export function list_bots(user_id) {
return $.get({
url: `${API_SERVER_URL}/user/${user_id}/bot`,
});
}
export function update_bot(user_id, bot_id, file, progress_callback) {
const method = bot_id === null ? "POST" : "PUT";
const endpoint = bot_id === null ? "bot" : `bot/${bot_id}`;
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
progress_callback(e.loaded / e.total);
}
}, false);
xhr.upload.addEventListener("load", function(e) {
progress_callback(1);
}, false);
xhr.withCredentials = true;
xhr.open(method, `${API_SERVER_URL}/user/${user_id}/${endpoint}`);
const form_data = new FormData();
form_data.append("name", "botFile");
form_data.append("botFile", file);
xhr.send(form_data);
return new Promise((resolve, reject) => {
xhr.onload = function(e) {
if (this.status === 200) {
resolve();
}
else {
const response = JSON.parse(e.target.responseText);
reject(response);
}
};
});
}
export function list_organizations() {
return $.get({
url: `${API_SERVER_URL}/organization`,
});
}
export function register_me(data) {
return $.post({
url: `${API_SERVER_URL}/user`,
data: JSON.stringify(data),
contentType: "application/json",
xhrFields: {
withCredentials: true,
},
});
}
export function get_replay(game_id, progress_callback) {
let game_data_promise = Promise.resolve($.get(`${API_SERVER_URL}/user/0/match/${game_id}`));
let replay_promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", `${API_SERVER_URL}/user/0/match/${game_id}/replay`, true);
xhr.responseType = "arraybuffer";
if (progress_callback) {
xhr.onprogress = function(e) {
progress_callback(e.loaded, e.total);
};
}
xhr.onload = function(e) {
if (this.status === 200) {
const blob = this.response;
resolve(blob);
}
else {
reject();
}
};
xhr.send();
});
return Promise.all([game_data_promise, replay_promise]).then(([game, replay]) => {
return {
game: game,
replay: replay,
}
});
}
export function leaderboard(filters) {
return $.get({
url: `${API_SERVER_URL}/leaderboard`,
data: {
filter: filters,
}
});
}
| JavaScript | 0.000002 | @@ -1681,32 +1681,121 @@
ot%60,%0A %7D);%0A%7D%0A%0A
+export function makeRequest() %7B%0A const xhr = new XMLHttpRequest();%0A return xhr;%0A%7D%0A%0A
export function
@@ -1979,35 +1979,28 @@
const xhr =
-new XMLHttp
+make
Request();%0A
@@ -3426,35 +3426,28 @@
const xhr =
-new XMLHttp
+make
Request();%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.