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 |
|---|---|---|---|---|---|---|---|
b611d5182ddf5783751bb4db0cc3e687633098bd | Fix path with tests on windows | tasks/data-tests.js | tasks/data-tests.js | "use strict";
var path = require('path'),
moment = require('moment'),
tz = require('../').tz,
helpers = require('../tests/helpers/helpers');
/**
* Creates a test for a provided time change (zone.untils[i])
*/
function changeTest (zone, i) {
var until = moment.utc(zone.untils[i]),
minutesOffset = zone.offsets[i],
secondsOffset = Math.round(minutesOffset * 60),
abbr = zone.abbrs[i],
dateTime = until.format('YYYY-MM-DDTHH:mm:ssZ'),
hours = until.clone().subtract(secondsOffset, 'seconds').format('HH:mm:ss');
if (secondsOffset % 60) {
minutesOffset = secondsOffset + ' / 60';
}
return '["' + dateTime + '", "' + hours + '", "' + abbr + '", ' + minutesOffset + ']';
}
/**
* Creates a test for provided year
*/
function yearTest (year, changeTests, name) {
return '\t"' + year + '" : helpers.makeTestYear("' + name + '", [\n\t\t' + changeTests.join(',\n\t\t') + '\n\t])';
}
/**
* Creates tests for all time changes in a timezone
*/
function yearTests (zone) {
var changeTests = {};
zone.untils.forEach(function (until, i) {
if (i < 2 || i >= zone.untils.length - 2) { return; }
var year = moment.utc(until).year();
changeTests[year] = changeTests[year] || [];
changeTests[year].push(changeTest(zone, i));
});
return Object.keys(changeTests).map(function (year) {
return yearTest(year, changeTests[year], zone.name);
}).join(',\n\n');
}
function intro (name) {
var helpers = path.relative(path.dirname('zones/' + name), 'helpers/helpers');
return '"use strict";\n\nvar helpers = require("' + helpers + '");\n\nexports["' + name + '"] = {\n\n';
}
/**
* Creates two guess tests for a timezone, guess:by:offset and guess:by:abbr
*/
function guessTests (zone) {
var mostPopulatedInOffset = helpers.getGuessResult(zone.name, { offset: true });
var mostPopulatedInAbbr = helpers.getGuessResult(zone.name, { abbr: true });
var tests = '';
if (mostPopulatedInOffset === zone.name) {
tests += '\t"guess:by:offset" : helpers.makeTestGuess("' + zone.name + '", { offset: true }),\n\n';
} else if (mostPopulatedInOffset) {
tests += '\t"guess:by:offset" : helpers.makeTestGuess("' + zone.name + '", { offset: true, expect: "' + mostPopulatedInOffset + '" }),\n\n';
}
if (mostPopulatedInAbbr === zone.name) {
tests += '\t"guess:by:abbr" : helpers.makeTestGuess("' + zone.name + '", { abbr: true }),\n\n';
} else if (mostPopulatedInAbbr) {
tests += '\t"guess:by:abbr" : helpers.makeTestGuess("' + zone.name + '", { abbr: true, expect: "' + mostPopulatedInAbbr + '" }),\n\n';
}
return tests;
}
module.exports = function (grunt) {
grunt.registerTask('data-tests', '8. Create unit tests from data-collect.', function () {
tz.load(grunt.file.readJSON('data/packed/latest.json'));
var zones = grunt.file.readJSON('temp/collect/latest.json');
zones.forEach(function (zone) {
var data = intro(zone.name) + guessTests(zone) + yearTests(zone) + '\n};',
dest = path.join('tests/zones', zone.name.toLowerCase() + '.js');
grunt.file.mkdir(path.dirname(dest));
grunt.file.write(dest, data);
grunt.verbose.ok("Created " + zone.name + " tests.");
});
grunt.log.ok('Created tests');
});
};
// Tests should look something like this.
//
// "use strict";
//
// var helpers = require("../../helpers/helpers");
//
// exports["America/Los_Angeles"] = {
// "guess:by:offset" : helpers.makeTestGuess("America/Los_Angeles", { offset: true, expect: "America/Los_Angeles" }),
//
// "guess:by:abbr" : helpers.makeTestGuess("America/Los_Angeles", { abbr: true }),
//
// "1918" : helpers.makeTestYear("America/Los_Angeles", [
// ["1918-03-31T09:59:59+00:00", "01:59:59", "PST", 480],
// ["1918-03-31T10:00:00+00:00", "03:00:00", "PDT", 420],
// ["1918-10-27T08:59:59+00:00", "01:59:59", "PDT", 420],
// ["1918-10-27T09:00:00+00:00", "01:00:00", "PST", 480]
// ]),
//
// "1919" : helpers.makeTestYear("America/Los_Angeles", [
// ["1919-03-30T09:59:59+00:00", "01:59:59", "PST", 480],
// ["1919-03-30T10:00:00+00:00", "03:00:00", "PDT", 420],
// ["1919-10-26T08:59:59+00:00", "01:59:59", "PDT", 420],
// ["1919-10-26T09:00:00+00:00", "01:00:00", "PST", 480]
// ])
// };
| JavaScript | 0.000001 | @@ -1510,16 +1510,36 @@
elpers')
+.replace(/%5C%5C/g, '/')
;%0A%09retur
|
7547d49df37409119c91136e815f746a8d2ea02c | Add chat history with keyup and down | client/Chat.js | client/Chat.js | // @flow
import ms from 'ms';
import socket from './socket';
import messageSchema from '../schemas/message';
import state from './state';
const Message = {
props: ['message'],
data() {
return {title: ''};
},
template: `
<div v-on:mouseover="fromNow" v-bind:title="title">
<div v-if="message.raw">
<span>{{message.text}}</span>
</div>
<div v-else-if="message.html">
<span v-html="message.text"></span>
</div>
<div v-else>
<span class="nav-link font-weight-bold" v-bind:style="'color: ' + message.hashColor">{{message.username}}: </span>
<span v-html="message.text"></span>
</div>
</div>
`,
methods: {
fromNow() {
this.title = ms(Date.now() - this.message.date, { long: true }) + ' ago';
}
}
};
const MessageList = {
props: ['messages'],
components: {
Message
},
template: `
<div class="message-list">
<div v-for="message in messages">
<Message v-bind:message="message" />
</div>
</div>
`,
updated() {
this.$el.scrollTop = this.$el.scrollHeight;
}
};
const Chat = {
props: ['messageList'],
data() {
return {
message: ''
};
},
components: {
MessageList
},
template: `
<div class="col-sm-10">
<MessageList v-bind:messages="messageList" />
<input
type="text"
class="form-control"
v-model="message"
v-on:keyup.enter="createMessage"
/>
</div>
`,
methods: {
createMessage() {
const message = this.message.trim();
const roomName = this.$route.params.id || this.$route.name;
if (!state.username) {
state.rooms.lobby.log.push({raw: true, text: 'Choose a username to chat.'});
this.message = '';
return console.error('Must have username to chat.');
}
if (!message) return console.error('Message cannot be blank.');
if (message.length > 300) return;
socket.emit('chat message', messageSchema.encode({
username: state.username,
room: roomName,
text: message
}));
this.message = '';
}
}
};
module.exports = Chat;
| JavaScript | 0 | @@ -1186,17 +1186,41 @@
sage: ''
+,%0A negativeIndex: 1
%0A
-
%7D;%0A
@@ -1479,24 +1479,105 @@
ateMessage%22%0A
+ v-on:keyup.up=%22pastMessage(1)%22%0A v-on:keyup.down=%22pastMessage(-1)%22%0A
/%3E%0A
@@ -2201,16 +2201,16 @@
%7D));%0A
-
th
@@ -2222,24 +2222,375 @@
ssage = '';%0A
+ this.negativeIndex = 1;%0A %7D,%0A pastMessage(num /*: number */) %7B%0A const filtered = this.messageList.filter(m =%3E m.username === state.username);%0A const index = filtered.length - this.negativeIndex;%0A const message = filtered%5Bindex%5D;%0A if (!message) return;%0A this.message = message.text;%0A this.negativeIndex += num;%0A
%7D%0A %7D%0A%7D;
|
057b1f59b17be202f21052469b56de2f44dc4d92 | use individual arrays to reset stream | lib/client/stream.js | lib/client/stream.js | var utils = require('./utils');
// Event stream factory
module.exports = function factory (instance, inputStream) {
// create stream object
var stream = utils.clone(Stream);
stream._ = instance;
stream._d = [];
stream._o = [];
stream._b = [];
if (inputStream) {
stream._i = inputStream;
stream._ii = inputStream._o.length;
inputStream._o.push(stream);
}
return stream;
};
/**
* Stream like events.
*
* @class Stream
*/
var Stream = {
// handler for incoming data
data: function (method) {
var args = [].slice.call(arguments);
args.splice(0, 1);
this._d.push([method, args]);
return this;
},
// send data
write: function (err, data, reverse) {
// buffer data in paused mode
if (this._p) {
this._b.push([err, data]);
return this;
}
// call custom write handler
if (typeof this._write === 'function') {
data = this._write(err, data, this) || data;
}
// call handlers on output streams
if (this._o.length) {
for (var i = 0, l = this._o.length; i < l; ++i) {
this._o[i].emit(err, data);
}
}
// emit data on input handler (back stream)
if (this._i) {
this._i.emit(err, data, this._ii);
}
return this;
},
emit: function (err, data, ignore) {
var i, l, method, args;
// call data handlers with err and data as arguments
for (i = 0, l = this._d.length; i < l; ++i) {
// call data handler with stream instance as function scope
// and overwrite data with transformed data
data = this._d[i][0].apply(this._, [err, data, this].concat(this._d[i][1])) || data;
}
// call handlers on output streams
if (this._o.length) {
for (i = 0, l = this._o.length; i < l; ++i) {
if (ignore !== i) {
this._o[i].emit(err, data, this._ii);
}
}
}
},
end: function () {
// remove stream from input's outputs
if (this._i) {
this._i._o.splice(this._ii, 1);
}
// remove refs
this._o = this._b = [];
this._ = this._i = null;
// call custom end handler
if (typeof this._end === 'function') {
this._end.apply(this, arguments);
}
return this;
},
// buffer writes
pause: function () {
// enable pause mode
this._p = true;
return this;
},
// write bufferd data
resume: function () {
// disable pause mode
this._p = false;
// write bufferd data
if (this._b.length) {
for (var i = 0, l = this._b.length; i < l; ++i) {
this.write(this._b[i][0], this._b[i][1]);
}
}
return this;
}
};
| JavaScript | 0 | @@ -2341,23 +2341,57 @@
is._o =
-this._b
+%5B%5D;%0A this._b = %5B%5D;%0A this._d
= %5B%5D;%0A
|
21d79b19dc008f52d1da32314113ebeabacaa8dc | use prototype based OOP | javascript/onp.js | javascript/onp.js |
function editdistance(a, b) {
var m, n, offset, delta, size, fp, p;
m = a.length;
n = b.length;
if (m >= n) {
var tmp;
tmp = a;
a = b;
b = tmp;
}
offset = m + 1;
delta = n - m;
size = m + n + 3;
fp = {};
for (var i=0;i<size;++i) {
fp[i] = -1;
}
p = -1;
do {
p = p + 1;
for (var k=-p;k<=delta-1;++k) {
fp[k+offset] = snake(a, b, m, n, k, fp[k-1+offset]+1, fp[k+1+offset]);
}
for (var k=delta+p;k>=delta+1;--k) {
fp[k+offset] = snake(a, b, m, n, k, fp[k-1+offset]+1, fp[k+1+offset]);
}
fp[delta+offset] = snake(a, b, m, n, delta, fp[delta-1+offset]+1, fp[delta+1+offset]);
} while (fp[delta+offset] != n);
return delta + 2 * p
}
function snake(a, b, m, n, k, p, pp) {
y = Math.max(p, pp);
x = y - k;
while (x < m && y < n && a[x] == b[y]) {
x = x + 1;
y = y + 1;
}
return y;
}
if (arguments.lengh < 2) {
print("few arguments")
exit()
}
print(editdistance(arguments[0], arguments[1]))
| JavaScript | 0.000002 | @@ -3,28 +3,20 @@
unction
-editdistance
+Diff
(a, b) %7B
@@ -24,50 +24,13 @@
-var m, n, offset, delta, size, fp, p;%0A
+this.
m =
@@ -43,16 +43,21 @@
th;%0A
+this.
n = b.le
@@ -74,41 +74,61 @@
if (
-m %3E= n) %7B%0A%09var tmp;%0A%09tmp = a;%0A%09a
+this.m %3E= this.n) %7B%0A%09var tmp = this.a;%0A this.a
=
@@ -142,10 +142,14 @@
+this.
b
-
=
@@ -154,24 +154,162 @@
= tmp;%0A %7D
+ else %7B%0A this.a = a;%0A this.b = b;%0A %7D%0A%7D%0A%0ADiff.prototype.editdistance = function () %7B%0A var offset, delta, size, fp, p;
%0A offset
@@ -310,16 +310,21 @@
ffset =
+this.
m + 1;%0A
@@ -339,12 +339,22 @@
=
-n -
+this.n - this.
m;%0A
@@ -365,20 +365,30 @@
ize =
-m +
+this.m + this.
n + 3;%0A
@@ -567,34 +567,27 @@
fset%5D =
+this.
snake(
-a, b, m, n,
k, fp%5Bk-
@@ -698,34 +698,27 @@
fset%5D =
+this.
snake(
-a, b, m, n,
k, fp%5Bk-
@@ -784,34 +784,27 @@
fset%5D =
+this.
snake(
-a, b, m, n,
delta, f
@@ -882,12 +882,16 @@
!=
+this.
n);
-%0A
@@ -922,35 +922,41 @@
%0A
-function snake(a, b, m, n,
+Diff.prototype.snake = function (
k, p
@@ -1018,16 +1018,21 @@
le (x %3C
+this.
m && y %3C
@@ -1036,21 +1036,31 @@
y %3C
-n &&
+this.n && this.
a%5Bx%5D ==
b%5By%5D
@@ -1055,16 +1055,21 @@
a%5Bx%5D ==
+this.
b%5By%5D) %7B%0A
@@ -1080,17 +1080,11 @@
-x = x + 1
+++x
;%0A
@@ -1093,17 +1093,11 @@
-y = y + 1
+++y
;%0A
@@ -1189,26 +1189,27 @@
%0A%7D%0A%0A
-print(editdistance
+var diff = new Diff
(arg
@@ -1232,10 +1232,38 @@
ents%5B1%5D)
-)
+;%0Aprint(diff.editdistance());
%0A
|
3847ecb00ededdb93eb9b9555cbae0b74ca81bff | Disable callback-return lint rule | lib/node_modules/@stdlib/utils/find/lib/find.js | lib/node_modules/@stdlib/utils/find/lib/find.js | 'use strict';
// MODULES //
var isFunction = require( '@stdlib/utils/is-function' );
var isInteger = require( '@stdlib/utils/is-integer' ).isPrimitive;
var isObject = require( '@stdlib/utils/is-plain-object' );
var isString = require( '@stdlib/utils/is-string' ).isPrimitive;
var isArrayLike = require( '@stdlib/utils/is-array-like' );
var hasOwnProp = require( '@stdlib/utils/has-own-property' );
// MAIN //
/**
* Finds elements in an array-like object that satisfy a test condition.
*
* @param {(Array|TypedArray|string)} arr - object from which elements will be tested
* @param {Options} [options] - function options
* @param {integer} [options.k=arr.length] - limits the number of returned elements
* @param {string} [options.returns='indices'] - if `values`, values are returned; if `indices`, indices are returned; if `*`, both indices and values are returned
* @param {Function} clbk - function invoked for each array element. If the return value is truthy, the value is considered to have satisfied the test condition.
* @throws {TypeError} first argument must be an array-like object
* @throws {TypeError} options argument must be an object
* @throws {TypeError} last argument must be a function
* @throws {TypeError} `options.k` must be an integer
* @throws {TypeError} `options.returns` must be a string equal to `values`, `indices` or `*`
* @returns {Array} array of indices, element values, or arrays of index-value pairs
*
* @example
* var data = [ 30, 20, 50, 60, 10 ];
* var vals = find( data, condition );
* // returns [ 0, 2, 3 ]
*
* function condition( val ) {
* return val > 20;
* }
*
* @example
* var data = [ 30, 20, 50, 60, 10 ];
* var opts = {
* 'k': 2,
* 'returns': 'values'
* };
* var vals = find( data, opts, condition );
* // returns [ 30, 50 ]
*
* function condition( val ) {
* return val > 20;
* }
*
* @example
* var data = [ 30, 20, 50, 60, 10 ];
* var vals = find( data, condition );
* // returns []
*
* function condition( val ) {
* return val > 1000;
* }
*
* @example
* var data = [ 30, 20, 50, 60, 10 ];
* var opts = {
* 'k': -2,
* 'returns': 'values'
* };
* var vals = find( data, opts, condition );
* // returns [ 60, 50 ]
*
* function condition( val ) {
* return val > 20;
* }
*
* @example
* var data = [ 30, 20, 50, 60, 10 ];
* var opts = {
* 'k': -2,
* 'returns': '*'
* };
* var vals = find( data, opts, condition );
* // returns [ [3, 60], [2, 50] ]
*
* function condition( val ) {
* return val > 20;
* }
*/
function find( arr, options, clbk ) { // eslint-disable-line no-redeclare
var returns;
var count;
var mode;
var opts;
var len;
var out;
var ret;
var cb;
var i;
var k;
var v;
mode = 0;
returns = [ 'values', 'indices', '*' ];
if ( !isArrayLike( arr ) ) {
throw new TypeError( 'invalid input argument. Must provide an array-like object. Value: `' + arr + '`' );
}
len = arr.length;
if ( arguments.length < 3 ) {
opts = {};
cb = options;
} else {
opts = options;
cb = clbk;
}
if ( !isFunction( cb ) ) {
throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `' + cb + '`' );
}
if ( !isObject( opts ) ) {
throw new TypeError( 'invalid input argument. Options must be an object. Value: `' + opts + '`' );
}
if ( hasOwnProp( opts, 'k' ) ) {
k = opts.k;
if ( !isInteger( k ) ) {
throw new TypeError( 'invalid input argument. `k` must be an integer. Value: `' + k + '`' );
}
} else {
k = len;
}
if ( hasOwnProp( opts, 'returns' ) ) {
ret = opts.returns;
if ( !isString( ret ) || returns.indexOf( ret ) === -1 ) {
throw new TypeError( 'invalid input argument. `returns` option must be a string and have one of the following values: `values`, `indices`, `all`. Value: `' + ret + '`' );
}
if ( ret === 'values' ) {
mode = 1;
} else if ( ret === '*' ) {
mode = 2;
}
}
out = [];
count = 0;
if ( k === 0 ) {
return out;
}
if ( k > 0 ) {
// Search moving from begin-to-end [0,1,...]:
for ( i = 0; i < len; i++ ) {
v = arr[ i ];
if ( cb( v, i, arr ) ) {
if ( mode === 2 ) {
out.push( [ i, v ] );
} else if ( mode === 1 ) {
out.push( v );
} else {
out.push( i );
}
count += 1;
if ( count === k ) {
break;
}
}
}
return out;
}
// Search moving from end-to-begin [...,2,1,0]:
k = -k;
for ( i = len-1; i >= 0; i-- ) {
v = arr[ i ];
if ( cb( v, i, arr ) ) {
if ( mode === 2 ) {
out.push( [ i, v ] );
} else if ( mode === 1 ) {
out.push( v );
} else {
out.push( i );
}
count += 1;
if ( count === k ) {
break;
}
}
}
return out;
} // end FUNCTION find()
// EXPORTS //
module.exports = find;
| JavaScript | 0.000001 | @@ -4053,24 +4053,63 @@
i, arr ) ) %7B
+ // eslint-disable-line callback-return
%0A%09%09%09%09if ( mo
@@ -4453,24 +4453,63 @@
i, arr ) ) %7B
+ // eslint-disable-line callback-return
%0A%09%09%09if ( mod
|
0ee42ec3fb8f395769261b8947522c0504460191 | complete renaming of getCommandsEvent to getCommands | lib/commando/pool.js | lib/commando/pool.js | import DefaultLauncher from 'commando/launcher/default';
import PromiseLauncher from 'commando/launcher/promise';
import { isArray } from 'commando/utils';
export default CommandPool;
// Command pool constructor
// ------------------------
//
// Accepts these args:
// * `eventHub`: Object to use to bind events to command calls
// * `commandMap`: Object which is basically a map to bind event to command call.
// Useful to create binding at startup
// * `options`: Object to set some options. Supported options:
// + launcher: String ('default', 'promise'): enable the setup of the launcher
// using the default ones provided. If you want to setup a custom launcher use
// the `withLauncher(object)` method
function CommandPool(eventHub, commandMap, options) {
var _this = this;
this.eventHub = eventHub;
for(var event in commandMap) {
_this.addCommand(event, commandMap[event]);
}
this.options = options;
};
CommandPool.prototype = {
_commands: {},
// to setup a custom launcher
// return this to enable chaining calls.
withLauncher: function (launcher) {
this._launcher = launcher;
return this;
},
// execute a `command` using command launcher
execute: function(command, args) {
//this.launcher().execute(command, args).catch(this.commandError);
this.launcher().execute(command, args, {error: this.commandError});
},
// main error handler to override
commandError: function (error) {},
// return existing launcher or create a new one if it does not exist
// override this method to provide a new implementation
launcher: function() {
if (!this._launcher) {
this._launcher = new DefaultLauncher();
}
return this._launcher;
},
// internal function to bind an `event` to a `command` call
_bindCommand: function(event, command) {
return this.eventHub.on(event, function () {
this.execute(command, Array.prototype.splice.call(arguments, 0, 1));
}, this);
},
// internal function to unbind an `event` to a `command` call
_unbindCommand: function(event, command) {
return this.eventHub.off(event, function () {
this.execute(command, Array.prototype.splice.call(arguments, 0, 1));
}, this);
},
// internal command which add an (`event`, `command`) couple to command pool
_addCommand: function(event, Command) {
var commands;
this._bindCommand(event, Command);
commands = this.getCommandsEvent(event);
if (commands) {
commands.push(Command);
} else {
this._commands[event] = [Command];
}
},
// internal command which remove an (`event`, `command`) couple to command pool
// support also the removal of all commands binded to `event` by passing a `null` `command`.
_delCommand: function(event, command) {
var commands;
if (!event) {
return this;
}
// unbind `command`
this._unbindCommand(event, command);
// remove commands
if (!command) {
delete this._commands[event];
} else {
commands = this.getCommandsEvent(event);
// remove any commands found
var index = commands.indexOf(command);
if (-1 != index) {
commands.splice(index, 1);
}
}
},
// find the commands binded to an `event`
getCommands: function(event) {
return this._commands[event];
},
// add `commands` to pool and bind them to `event`
addCommand: function(event, commands) {
var commandsArr,
_this = this;
// nothing to do
if (!event) {
return this;
}
// add support for single command
if (!isArray(commands)) {
commandsArr = [commands];
}
// now add the commands
commandsArr.forEach(function(command) {
_this._addCommand(event, command);
});
return this;
},
// replace *all* existing `commands` binded to an `event`
setCommand: function(event, commands) {
if (!event) {
return;
}
this.delCommand(event);
return this.addCommand(event, commands);
},
// delete `commands` binded to `event`
delCommand: function(event, commands) {
var commandsArr,
_this = this;
if (!event) {
return this;
}
if (!commands) {
this._delCommand(event);
} else {
if (isArray(commands)) {
commandsArr = [commands];
}
// now delete the commands
commandsArr.forEach(function(command) {
_this._delCommand(event, command);
});
}
return this;
}
};
| JavaScript | 0 | @@ -2430,37 +2430,32 @@
this.getCommands
-Event
(event);%0A if
@@ -3037,13 +3037,8 @@
ands
-Event
(eve
|
40658a72a25f391408068338436f8c073edbf3ec | remove `new` indicator in doc. | docs/router/routes.js | docs/router/routes.js | // DO NOT ADD ANYTHING ELSE EXCEPT ROUTE ITEM INTO THIS FILE
// routes order = menu order
const routes = [
{
path: '/',
meta: {
type: 'home',
label: 'Home'
},
component: () => import('./../components/Home.vue')
},
{
path: '/getting-started',
meta: {
type: 'usage',
label: 'Getting Started',
url: 'usage/GettingStarted.md'
},
component: () => import('./../pages/usage/GettingStarted.md')
},
{
path: '/i18n',
meta: {
type: 'usage',
label: 'I18n',
url: 'usage/I18n.md'
},
component: () => import('./../pages/usage/I18n.md')
},
{
path: '/button',
meta: {
type: 'component',
label: 'Button',
url: 'components/Btn.md',
group: 'Basic'
},
component: () => import('./../pages/components/Btn.md')
},
{
path: '/button-group',
meta: {
type: 'component',
label: 'ButtonGroup',
url: 'components/BtnGroup.md',
group: 'Basic'
},
component: () => import('./../pages/components/BtnGroup.md')
},
{
path: '/collapse',
meta: {
type: 'component',
label: 'Collapse',
url: 'components/Collapse.md',
group: 'Basic'
},
component: () => import('./../pages/components/Collapse.md')
},
{
path: '/dropdown',
meta: {
type: 'component',
label: 'Dropdown',
url: 'components/Dropdown.md',
group: 'Popup'
},
component: () => import('./../pages/components/Dropdown.md')
},
{
path: '/modal',
meta: {
type: 'component',
label: 'Modal',
url: 'components/Modal.md',
group: 'Popup'
},
component: () => import('./../pages/components/Modal.md')
},
{
path: '/tooltip',
meta: {
type: 'component',
label: 'Tooltip',
url: 'components/Tooltip.md',
group: 'Popup'
},
component: () => import('./../pages/components/Tooltip.md')
},
{
path: '/popover',
meta: {
type: 'component',
label: 'Popover',
url: 'components/Popover.md',
group: 'Popup'
},
component: () => import('./../pages/components/Popover.md')
},
{
path: '/multi-select',
meta: {
type: 'component',
label: 'MultiSelect',
url: 'components/MultiSelect.md',
group: 'Form',
new: true
},
component: () => import('./../pages/components/MultiSelect.md')
},
{
path: '/typeahead',
meta: {
type: 'component',
label: 'Typeahead',
url: 'components/Typeahead.md',
group: 'Form'
},
component: () => import('./../pages/components/Typeahead.md')
},
{
path: '/date-picker',
meta: {
type: 'component',
label: 'DatePicker',
url: 'components/DatePicker.md',
group: 'Form'
},
component: () => import('./../pages/components/DatePicker.md')
},
{
path: '/time-picker',
meta: {
type: 'component',
label: 'TimePicker',
url: 'components/TimePicker.md',
group: 'Form'
},
component: () => import('./../pages/components/TimePicker.md')
},
{
path: '/alert',
meta: {
type: 'component',
label: 'Alert',
url: 'components/Alert.md',
group: 'Notice'
},
component: () => import('./../pages/components/Alert.md')
},
{
path: '/notification',
meta: {
type: 'component',
label: 'Notification',
url: 'components/Notification.md',
group: 'Notice'
},
component: () => import('./../pages/components/Notification.md')
},
{
path: '/message-box',
meta: {
type: 'component',
label: 'MessageBox',
url: 'components/MessageBox.md',
group: 'Notice'
},
component: () => import('./../pages/components/MessageBox.md')
},
{
path: '/navbar',
meta: {
type: 'component',
label: 'Navbar',
url: 'components/Navbar.md',
group: 'Navigation',
new: true
},
component: () => import('./../pages/components/Navbar.md')
},
{
path: '/tabs',
meta: {
type: 'component',
label: 'Tabs',
url: 'components/Tabs.md',
group: 'Navigation'
},
component: () => import('./../pages/components/Tabs.md')
},
{
path: '/breadcrumbs',
meta: {
type: 'component',
label: 'Breadcrumbs',
url: 'components/Breadcrumbs.md',
group: 'Navigation'
},
component: () => import('./../pages/components/Breadcrumbs.md')
},
{
path: '/pagination',
meta: {
type: 'component',
label: 'Pagination',
url: 'components/Pagination.md',
group: 'Indicator'
},
component: () => import('./../pages/components/Pagination.md')
},
{
path: '/progress-bar',
meta: {
type: 'component',
label: 'ProgressBar',
url: 'components/ProgressBar.md',
group: 'Indicator'
},
component: () => import('./../pages/components/ProgressBar.md')
},
{
path: '/carousel',
meta: {
type: 'component',
label: 'Carousel',
url: 'components/Carousel.md',
group: 'Others'
},
component: () => import('./../pages/components/Carousel.md')
},
{
path: '/affix',
meta: {
type: 'component',
label: 'Affix',
url: 'components/Affix.md',
group: 'Others'
},
component: () => import('./../pages/components/Affix.md')
},
{
path: '/scroll-spy',
meta: {
type: 'component',
label: 'ScrollSpy',
url: 'components/ScrollSpy.md',
group: 'Others'
},
component: () => import('./../pages/components/ScrollSpy.md')
}
]
export default routes
| JavaScript | 0 | @@ -2321,33 +2321,16 @@
: 'Form'
-,%0A new: true
%0A %7D,%0A
@@ -3930,25 +3930,8 @@
ion'
-,%0A new: true
%0A
|
1abf045b302d26ac36b5c230e09c88a2c8eaba38 | Add the ability to have storage client set alternate serviceType | lib/pkgcloud/openstack/storage/storageClient.js | lib/pkgcloud/openstack/storage/storageClient.js | /*
* storageClient.js: A base StorageClient for Openstack &
* Rackspace storage clients
*
* (C) 2013 Rackspace
* Ken Perkins
* MIT LICENSE
*
*/
var urlJoin = require('url-join'),
_ = require('underscore');
const CONTAINER_META_PREFIX = 'x-container-meta-';
const CONTAINER_REMOVE_META_PREFIX = 'x-remove-container-meta-';
const OBJECT_META_PREFIX = 'x-object-meta-';
const OBJECT_REMOVE_META_PREFIX = 'x-object-remove-meta-';
var Client = exports.StorageClient = function () {
this.serviceType = 'object-store';
}
/**
* client._getUrl
*
* @description get the url for the current storage service
*
* @param options
* @returns {exports|*}
* @private
*/
Client.prototype._getUrl = function (options) {
options = options || {};
var fragment = '';
if (options.container) {
fragment = encodeURIComponent(options.container);
}
if (options.path) {
fragment = urlJoin(fragment, options.path.split('/').map(encodeURIComponent).join('/'));
}
if (fragment === '' || fragment === '/') {
return this._serviceUrl;
}
return urlJoin(this._serviceUrl, fragment);
};
Client.prototype.serializeMetadata = function (prefix, metadata) {
if (!metadata) {
return {};
}
var serializedMetadata = {};
_.keys(metadata).forEach(function (key) {
serializedMetadata[prefix + key] = metadata[key];
});
return serializedMetadata;
};
Client.prototype.deserializeMetadata = function (prefix, metadata) {
if (!metadata) {
return {};
}
var deserializedMetadata = {};
_.keys(metadata).forEach(function (key) {
if (key.indexOf(prefix) !== -1) {
deserializedMetadata[key.split(prefix)[1]] = metadata[key];
}
});
return deserializedMetadata;
};
Client.prototype.CONTAINER_META_PREFIX = CONTAINER_META_PREFIX;
Client.prototype.CONTAINER_REMOVE_META_PREFIX = CONTAINER_REMOVE_META_PREFIX;
Client.prototype.OBJECT_META_PREFIX = OBJECT_META_PREFIX;
Client.prototype.OBJECT_REMOVE_META_PREFIX = OBJECT_REMOVE_META_PREFIX;
| JavaScript | 0 | @@ -976,24 +976,192 @@
'/'));%0A %7D%0A%0A
+ var serviceUrl = options.serviceType ? this._identity.getServiceEndpointUrl(%7B%0A serviceType: options.serviceType,%0A region: this.region%0A %7D) : this._serviceUrl;%0A%0A
if (fragme
@@ -1204,22 +1204,16 @@
return
-this._
serviceU
@@ -1238,22 +1238,16 @@
urlJoin(
-this._
serviceU
@@ -1261,16 +1261,17 @@
gment);%0A
+%0A
%7D;%0A%0AClie
|
6640791aef091c3bcf74e57016fd709559321ba0 | fix reported number of results for list command | lib/commands/list.js | lib/commands/list.js | /*!
* CPM - Couch Package Manager
* Copyright (c) 2010 Caolan McMahon
* MIT Licensed
*/
/**
* Module dependencies
*/
var logger = require('../logger'),
instance = require('../instance'),
repository = require('../repository'),
settings = require('../settings'),
packages = require('../packages'),
utils = require('../../lib/utils'),
help = require('./help'),
url = require('url');
/**
* Executes the list command
*/
module.exports = function (args, options) {
settings.loadSettings(null, function(err, settings){
if (err) return logger.error(err);
logger.debug('settings:', settings);
var ins = repository.resolveInstance(settings, args[0]);
try { instance.validateInstance(ins); }
catch (e) { return logger.error(e); }
logger.info('Hostname:', ins.hostname);
logger.info('Port:', ins.port);
logger.info('DB:', ins.db);
repository.list(ins, function (err, packages) {
if (err) return logger.error(err);
var names = Object.keys(packages);
if (names.length) console.log('');
names.forEach(function (n) {
console.log(utils.padRight(n,30) + packages[n].join(', '));
});
logger.end(
packages.length + ' result' +
((packages.length !== 1) ? 's': '')
);
});
});
};
| JavaScript | 0.000001 | @@ -1294,22 +1294,19 @@
-packag
+nam
es.lengt
|
02afbec042f76fab8e6fc23825a913d69aa2b23c | Fix missing headers in Windows 8 upload proxy | www/windows8/FileTransferProxy.js | www/windows8/FileTransferProxy.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
var FileTransferError = require('./FileTransferError'),
FileUploadResult = require('org.apache.cordova.core.file.FileUploadResult'),
FileEntry = require('org.apache.cordova.core.file.FileEntry');
module.exports = {
upload:function(successCallback, error, options) {
var filePath = options[0];
var server = options[1];
var win = function (fileUploadResult) {
successCallback(fileUploadResult);
};
if (filePath === null || typeof filePath === 'undefined') {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
if (String(filePath).substr(0, 8) == "file:///") {
filePath = Windows.Storage.ApplicationData.current.localFolder.path + String(filePath).substr(8).split("/").join("\\");
}
Windows.Storage.StorageFile.getFileFromPathAsync(filePath).then(function (storageFile) {
storageFile.openAsync(Windows.Storage.FileAccessMode.read).then(function (stream) {
var blob = MSApp.createBlobFromRandomAccessStream(storageFile.contentType, stream);
var formData = new FormData();
formData.append("source\";filename=\"" + storageFile.name + "\"", blob);
WinJS.xhr({ type: "POST", url: server, data: formData }).then(function (response) {
var code = response.status;
storageFile.getBasicPropertiesAsync().done(function (basicProperties) {
Windows.Storage.FileIO.readBufferAsync(storageFile).done(function (buffer) {
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
var fileContent = dataReader.readString(buffer.length);
dataReader.close();
win(new FileUploadResult(basicProperties.size, code, fileContent));
});
});
}, function () {
error(FileTransferError.INVALID_URL_ERR);
});
});
},function(){error(FileTransferError.FILE_NOT_FOUND_ERR);});
},
download:function(win, error, options) {
var source = options[0];
var target = options[1];
var headers = options[4] || {};
if (target === null || typeof target === undefined) {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
if (String(target).substr(0, 8) == "file:///") {
target = Windows.Storage.ApplicationData.current.localFolder.path + String(target).substr(8).split("/").join("\\");
}
var path = target.substr(0, String(target).lastIndexOf("\\"));
var fileName = target.substr(String(target).lastIndexOf("\\") + 1);
if (path === null || fileName === null) {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
var download = null;
Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).then(function (storageFile) {
var uri = Windows.Foundation.Uri(source);
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
if (headers) {
for (var header in headers) {
downloader.setRequestHeader(header, headers[header]);
}
}
download = downloader.createDownload(uri, storageFile);
download.startAsync().then(function () {
win(new FileEntry(storageFile.name, storageFile.path));
}, function () {
error(FileTransferError.INVALID_URL_ERR);
});
});
});
}
};
require("cordova/commandProxy").add("FileTransfer",module.exports); | JavaScript | 0.000004 | @@ -1156,16 +1156,56 @@
ons%5B1%5D;%0A
+ var headers = options%5B8%5D %7C%7C %7B%7D;%0A
%0A%0A
@@ -2161,16 +2161,34 @@
formData
+, headers: headers
%7D).then
|
20df59b0fc11c79a95b271b0d796e3a7f1af0650 | Fix resizing issue in split mode. Alsop, remove annotation that the spec is read only, although it is invisible. | src/components/input-panel/compiled-spec-header/index.js | src/components/input-panel/compiled-spec-header/index.js | import React from 'react';
import { connect } from 'react-redux';
import * as EditorActions from '../../../actions/editor';
const toggleStyle = {
cursor:'pointer',
position: 'absolute',
bottom: 0,
};
const svgStyle = {
position:'absolute',
right:'50%',
height: 25,
width: 35
}
class CompiledSpecDisplayHeader extends React.Component {
editVegaSpec () {
this.props.updateVegaSpec(JSON.stringify(this.props.value, null, 2));
}
render () {
if (this.props.compiledVegaSpec) {
const toggleStyleUp = Object.assign({}, toggleStyle, {
position: 'static'
});
return (
<div className="editor-header"
style={toggleStyleUp}
onClick={this.props.showCompiledVegaSpec}>
<span style={{marginLeft: 10}}>
Compiled Vega
</span>
<svg
style={svgStyle}>
<polygon points="5,5 30,5 17.5,20" />
</svg>
<button
onClick={this.editVegaSpec.bind(this)}
style={{position:'absolute', right:'3%', cursor:'pointer'}}>
Edit Vega spec
</button>
</div>
);
} else {
return (
<div className={'full-height-wrapper'}
onClick={this.props.showCompiledVegaSpec}>
<div className="editor-header" style={toggleStyle}>
<span style={{marginLeft: 10}}>
Compiled Vega
</span>
<svg
style={svgStyle}>
<polygon points="5,20 30,20 17.5,5" />
</svg>
<span style={{marginRight: 10, position: 'absolute', right: 0}}>
Read Only
</span>
</div>
</div>
);
}
}
};
function mapStateToProps (state, ownProps) {
return {
value: state.app.vegaSpec,
compiledVegaSpec: state.app.compiledVegaSpec,
mode: state.app.mode,
};
}
const mapDispatchToProps = function (dispatch) {
return {
updateVegaSpec: (val) => {
dispatch(EditorActions.updateVegaSpec(val));
},
showCompiledVegaSpec: () => {
dispatch(EditorActions.showCompiledVegaSpec());
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CompiledSpecDisplayHeader);
| JavaScript | 0 | @@ -623,17 +623,16 @@
%3Cdiv
-
classNam
@@ -1212,54 +1212,8 @@
div
-className=%7B'full-height-wrapper'%7D%0A
onCl
@@ -1530,129 +1530,8 @@
vg%3E%0A
- %3Cspan style=%7B%7BmarginRight: 10, position: 'absolute', right: 0%7D%7D%3E%0A Read Only%0A %3C/span%3E%0A
|
2e40d8d28af218c73aa8bce71bf21062fc841766 | return on error | lib/convert2video.js | lib/convert2video.js | 'use strict';
var fs = require('fs');
var child = require('child_process');
var uuid = require('uuid');
var dataURIBuffer = require('data-uri-to-buffer');
var glob = require('glob');
var async = require('async');
var TMP_DIR = __dirname + '/../tmp/';
var IMAGE_FORMAT = 'jpg';
exports.transform = function (mediaArr, next) {
// write images to tmp files
var mediaId = uuid.v4();
var count = 0;
var deleteFiles = function () {
glob(TMP_DIR + mediaId + '*', function (err, files) {
if (err) {
console.log('glob error: ', err);
return;
}
files.forEach(function (file) {
fs.unlink(file, function (err) {
if (err) {
console.log('error unlinking ' + file + ':', err);
}
});
});
});
};
var done = function(err, videos) {
next(err, videos);
deleteFiles();
};
var writeVideo = function () {
var types = [{
format: 'webm',
ffmpegArgs: '" -filter:v "setpts=2.5*PTS" -vcodec libvpx -an "'
}, {
format: 'mp4',
ffmpegArgs: '" -filter:v "setpts=2.5*PTS" -c:v libx264 -r 30 -an -pix_fmt yuv420p "'
}];
async.map(types, function (type, callback) {
var video = new Buffer(0);
var command = [
'ffmpeg -i "',
TMP_DIR + mediaId + '-%d.' + IMAGE_FORMAT,
type.ffmpegArgs,
TMP_DIR + mediaId + '.' + type.format,
'"'
].join('');
child.exec(command, { timeout: 3000 }, function (err, stdout, stderr) {
if (err) {
callback(err);
}
var filename = TMP_DIR + mediaId + '.' + type.format;
var readStream = fs.createReadStream(filename);
readStream.on('data', function (chunk) {
video = Buffer.concat([video, chunk]);
});
readStream.on('error', function (err) {
callback(err);
});
readStream.on('end', function () {
var base64 = video.toString('base64');
callback(null, {
format: type.format,
data: 'data:video/' + type.format + ';base64,' + base64
});
});
});
}, function (err, results) {
var videos = {};
if (err) {
done(err);
}
else {
results.forEach(function (result) {
videos[result.format] = result.data;
});
done(null, videos);
}
});
};
var fileFinished = function() {
count++;
if (count === mediaArr.length) {
writeVideo();
}
};
for (var i = 0; i < mediaArr.length; i ++) {
var frame = mediaArr[i];
if (frame.length > 30000 * 4 / 3) {
return done(new Error('File too large'));
}
var buffer = dataURIBuffer(frame);
var writeStream = fs.createWriteStream(TMP_DIR + mediaId + '-' + i + '.' + IMAGE_FORMAT);
writeStream
.on('error', done)
.end(buffer, fileFinished);
}
};
| JavaScript | 0.000033 | @@ -1524,32 +1524,39 @@
rr) %7B%0A
+return
callback(err);%0A
|
48dcb0994166e5dfaca57096669de1680c63d2fa | version minificada | jquery.rut.min.js | jquery.rut.min.js | !function(a){function b(a){return a.replace(/[\.\-]/g,"")}function c(a){rutAndDv=i(a);var b=rutAndDv[0],c=rutAndDv[1];if(!b||!c)return b||a;for(var d="";b.length>3;)d="."+b.substr(b.length-3)+d,b=b.substring(0,b.length-3);return b+d+"-"+c}function d(a){return a.type&&a.type.match(/^key(up|down|press)/)&&(8==a.keyCode||16==a.keyCode||17==a.keyCode||18==a.keyCode||20==a.keyCode||27==a.keyCode||37==a.keyCode||38==a.keyCode||39==a.keyCode||40==a.keyCode||91==a.keyCode)}function e(a){if("string"!=typeof a)return!1;var c=b(a);if(c.length<2)return!1;var d=c.charAt(c.length-1).toUpperCase(),e=parseInt(c.substr(0,c.length-1));return 0/0===e?!1:f(e).toString().toUpperCase()===d}function f(a){var b=0,c=2;if("number"==typeof a){a=a.toString();for(var d=a.length-1;d>=0;d--)b+=a.charAt(d)*c,c=(c+1)%8||2;switch(b%11){case 1:return"k";case 0:return 0;default:return 11-b%11}}}function g(a){a.val(c(a.val()))}function h(a){e(a.val())?a.trigger("rutValido",i(a.val())):a.trigger("rutInvalido")}function i(a){var c=b(a);if(0==c.length)return[null,null];if(1==c.length)return[c,null];var d=c.charAt(c.length-1),e=c.substring(0,c.length-1);return[e,d]}var j={validateOn:"blur",formatOn:"blur",ignoreControlKeys:!0},k={init:function(b){if(this.length>1)for(var c=0;c<this.length;c++)console.log(this[c]),a(this[c]).rut(b);else{var e=this;e.opts=a.extend({},j,b),e.opts.formatOn&&e.on(e.opts.formatOn,function(a){e.opts.ignoreControlKeys&&d(a)||g(e,a)}),e.opts.validateOn&&e.on(e.opts.validateOn,function(a){h(e,a)})}return this}};a.fn.rut=function(b){return k[b]?k[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("El método "+b+" no existe en jQuery.rut"):k.init.apply(this,arguments)},a.computeDV=function(a){var c=b(a);return computeDV(c)},a.formatRut=function(a){return c(a)},a.validateRut=function(b,c){if(e(b)){var d=i(b);return a.isFunction(c)&&c(d[0],d[1]),!0}return!1}}(jQuery); | JavaScript | 0.000001 | @@ -1721,17 +1721,17 @@
computeD
-V
+v
=functio
|
855c0ca0e021936e3237e2a068f68e3f0b95c309 | Update CrowdFundrr.js | js/CrowdFundrr.js | js/CrowdFundrr.js | /*
var CrowdFunding = web3.eth.contractFromAbi([{"constant":true,"inputs":[],"name":"numCampaigns","outputs":[{"name":"numCampaigns","type":"uint256"}]},{"constant":false,"inputs":[],"name":"get_numCampaigns","outputs":[{"name":"r_numCampaigns","type":"uint256"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"checkGoalReached","outputs":[{"name":"reached","type":"bool"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"getCampain","outputs":[{"name":"r_name","type":"string32"},{"name":"r_website","type":"string32"},{"name":"r_benificiary","type":"address"},{"name":"r_fundingGoal","type":"uint256"},{"name":"r_numFunders","type":"uint256"},{"name":"r_amount","type":"uint256"},{"name":"r_timelimit","type":"uint256"}]},{"constant":false,"inputs":[{"name":"name","type":"string32"},{"name":"website","type":"string32"},{"name":"beneficiary","type":"address"},{"name":"goal","type":"uint256"},{"name":"timelimit","type":"uint256"}],"name":"newCampaign","outputs":[{"name":"campaignID","type":"uint256"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"contribute","outputs":[]},{"constant":true,"inputs":[],"name":"campaigns","outputs":[{"name":"campaigns","type":"mapping(uint256=>structCampaign)"}]}]);
contract CrowdFunding{function numCampaigns()constant returns(uint256 numCampaigns){}function get_numCampaigns()returns(uint256 r_numCampaigns){}function checkGoalReached(uint256 campaignID)returns(bool reached){}function getCampain(uint256 campaignID)returns(string32 r_name,string32 r_website,address r_benificiary,uint256 r_fundingGoal,uint256 r_numFunders,uint256 r_amount,uint256 r_timelimit){}function newCampaign(string32 name,string32 website,address beneficiary,uint256 goal,uint256 timelimit)returns(uint256 campaignID){}function contribute(uint256 campaignID){}function campaigns()constant returns(mapping(uint256 => struct Campaign) campaigns){}}
2c0f7b6f… :numCampaigns
4fb2a9e1… :get_numCampaigns
5b2329d4… :checkGoalReached
76370504… :getCampain
99329342… :newCampaign
c1cbbca7… :contribute
cb5697f9… :campaigns
// New Campaign Transaction
// newCampaign(string32 name, string32 website, address beneficiary, uint goal, uint timelimit)
// contract.transact().newCampaign("My Great Campaign"
// , "mygreatcampaign.com", "0x6465940d1a1a7901f89476ff87a945e0fb1d07db", 50000, 4232408243);
// Contribute to Campaign
// contribute(uint campaignID)
// contract.transact({value: 34598}).newCampaign();
// Check Goal Reached
// checkGoalReached(uint campaignID) returns (bool reached)
// contract.transact().checkGoalReached(campaignID);
// Get Number of Campaigns
// get_numCampaigns() returns (uint r_numCampaigns)
// var get_numCampaigns = contract.call().get_numCampaigns();
// Get Campaign Function (uint ID)
var getCampaign = contract.call().getCampaign(34827423);
var number = web3.eth.number;
var info = web3.eth.block(number);
// contract.transact({from: addr2, value: 100000}).join(addr1);
*/
var eth = web3.eth;
var contractAbi = [{"constant":true,"inputs":[],"name":"numCampaigns","outputs":[{"name":"numCampaigns","type":"uint256"}]},{"constant":false,"inputs":[],"name":"get_numCampaigns","outputs":[{"name":"r_numCampaigns","type":"uint256"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"checkGoalReached","outputs":[{"name":"reached","type":"bool"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"getCampain","outputs":[{"name":"r_name","type":"string32"},{"name":"r_website","type":"string32"},{"name":"r_benificiary","type":"address"},{"name":"r_fundingGoal","type":"uint256"},{"name":"r_numFunders","type":"uint256"},{"name":"r_amount","type":"uint256"},{"name":"r_timelimit","type":"uint256"}]},{"constant":false,"inputs":[{"name":"name","type":"string32"},{"name":"website","type":"string32"},{"name":"beneficiary","type":"address"},{"name":"goal","type":"uint256"},{"name":"timelimit","type":"uint256"}],"name":"newCampaign","outputs":[{"name":"campaignID","type":"uint256"}]},{"constant":false,"inputs":[{"name":"campaignID","type":"uint256"}],"name":"contribute","outputs":[]},{"constant":true,"inputs":[],"name":"campaigns","outputs":[{"name":"campaigns","type":"mapping(uint256=>structCampaign)"}]}];
var contractAddr = "0xf3c47f714b662b56490593c3dda75d2e6ad68b37";
var contract = eth.contract(contractAddr, contractAbi);
// New Campaign Transaction
// newCampaign(string32 name, string32 website, address beneficiary, uint goal, uint timelimit)
// contract.transact().newCampaign("My Great Campaign"
// , "mygreatcampaign.com", "0x6465940d1a1a7901f89476ff87a945e0fb1d07db", 50000, 4232408243);
function new_campaign()
{
var c_name = $('#name').val();
var c_website = $('#website').val();
var c_beneficiary = $('#beneficiary').val();
var c_goal = $('#goal').val();
var c_timelimit = $('#timelimit').val();
var new_camp = contract.transact().newCampaign(c_name, c_website, "0x99704a2eb200abcc81b44e685f113bb83eaec43a", 50000, 5897359834);
alert(new_camp);
}
function get_campaign()
{
var c_id = $('#campaign_id').val();
var getCampaign = contract.call().getCampaign(c_id);
alert(getCampaign);
}
| JavaScript | 0.000001 | @@ -5068,16 +5068,17 @@
amp);%0A%7D%0A
+%0A
function
@@ -5174,25 +5174,24 @@
().getCampai
-g
n(c_id);%0A a
|
ccd4b6e373f619a85b183815aedb40baf8fc0376 | check if image or a diff with bg image | js/agentorange.js | js/agentorange.js | var defaultName = "Agent Orange";
if(chrome.storage.sync.get({
paused: false
},function(res){
if(!res.paused){
var finder,
trumpRegex = /realdonaldtrump|donald j. trump|donald john trump|donaldjtrump|Donald J. Trump|Donald J Trump|donald\strump|donaldjtrump|donaldtrump|\btrump(?='s)|DonaldTrump|\b(trump|donald)(\b|(?='s))/gi;
function replace(){
chrome.storage.sync.get({
theWord: defaultName
}, function(items) {
finder = findAndReplaceDOMText(document.body, {
find: trumpRegex,
replace: function(a,b){
return items.theWord;
},
preset:'prose'
});
});
chrome.storage.sync.get({
kittens: false
}, function(item){
if(item.kittens == true){
$('img,div').each(function(i){
var alt = $(this).attr("alt"),
title = $(this).attr('title'),
src = $(this).attr('src'),
bg = $(this).css('background-image');
if((title && title.match(trumpRegex))||(src && src.match(trumpRegex))||(alt && alt.match(trumpRegex)) || (bg && bg.match(trumpRegex)) && !$(this).data('kittenChanged')) {
var imgRef = "https://placekitten.com/"+Math.round($(this).width())+"/"+Math.round($(this).height());
$(this).attr("src",imgRef);
if(bg){
$(this).css('background-image', 'url(' + imgRef + ')');
}
$(this).data('kittenChanged', 'true');
}
});
}
});
};
chrome.storage.onChanged.addListener(function(changes, namespace) {
replace();
});
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
replace();
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
childList: true
//...
});
replace();
}
}));
| JavaScript | 0.000001 | @@ -1310,50 +1310,8 @@
));%0A
- $(this).attr(%22src%22,imgRef);%0A
@@ -1398,24 +1398,89 @@
Ref + ')');%0A
+ %7Delse%7B%0A $(this).attr(%22src%22,imgRef);%0A
|
e1f04e41eab7ca9a25215ee94fa8e376833efc4c | Rewrite Vpn to ES2015 | lib/endpoints/vpn.js | lib/endpoints/vpn.js | 'use strict';
var Vpn = function (request) {
this.request = request;
};
// https://github.com/GleSYS/API/wiki/functions_vpn#vpncreateuser
Vpn.prototype.createUser = function (data) {
return this.request.post('/vpn/createuser', data);
};
// https://github.com/GleSYS/API/wiki/functions_vpn#vpndeleteuser
Vpn.prototype.deleteUser = function (data) {
return this.request.post('/vpn/deleteuser', data);
};
// https://github.com/GleSYS/API/wiki/functions_vpn#vpnedituser
Vpn.prototype.editUser = function (data) {
return this.request.post('/vpn/edituser', data);
};
// https://github.com/GleSYS/API/wiki/functions_vpn#vpnlistusers
Vpn.prototype.listUsers = function () {
return this.request.get('/vpn/listusers');
};
module.exports = Vpn;
| JavaScript | 0.000263 | @@ -12,26 +12,35 @@
';%0A%0A
-var Vpn = function
+class Vpn %7B%0A constructor
(re
@@ -52,16 +52,20 @@
) %7B%0A
+
+
this.req
@@ -80,20 +80,27 @@
equest;%0A
-%7D;%0A%0A
+ %7D%0A%0A
// https
@@ -161,43 +161,22 @@
ser%0A
-Vpn.prototype.createUser = function
+ createUser
(da
@@ -173,32 +173,36 @@
teUser (data) %7B%0A
+
return this.
@@ -232,36 +232,43 @@
teuser', data);%0A
-%7D;%0A%0A
+ %7D%0A%0A
// https://githu
@@ -321,43 +321,22 @@
ser%0A
-Vpn.prototype.deleteUser = function
+ deleteUser
(da
@@ -333,32 +333,36 @@
teUser (data) %7B%0A
+
return this.
@@ -392,36 +392,43 @@
teuser', data);%0A
-%7D;%0A%0A
+ %7D%0A%0A
// https://githu
@@ -479,41 +479,20 @@
ser%0A
-Vpn.prototype.editUser = function
+ editUser
(da
@@ -493,32 +493,36 @@
er (data) %7B%0A
+
+
return this.requ
@@ -554,20 +554,27 @@
data);%0A
-%7D;%0A%0A
+ %7D%0A%0A
// https
@@ -634,48 +634,31 @@
ers%0A
-Vpn.prototype.listUsers = function
+ listUsers
() %7B%0A
+
@@ -704,10 +704,15 @@
');%0A
+ %7D%0A
%7D
-;
%0A%0Amo
|
88f130c5c762a68e02b64178fa0e2cce2c02ae1f | Comment which key progresses algorithm | js/application.js | js/application.js | ;(function(){
var G = dijkstra.hexGrid(2);
var view = new dijkstra.GraphView(G, document.getElementById('graph'), {
placement: function(position){ return {
'x': 100 * position.x,
'y': 100 * position.y
}},
radius: 20,
between: 0.3,
vertex: {
events : {
mouseenter: function(event){
var id = this.getAttribute('data-vertex');
var v = G.findVertex(id);
algorithm.setPathFrom(v);
}
}
}
});
var algorithm = new dijkstra.ShortestPath(G);
algorithm.setSource(G.vertices[0]);
algorithm.setTarget(G.vertices[G.vertices.length - 1]);
algorithm.setPathFrom(G.vertices[G.vertices.length - 1]);
view.visualize(algorithm);
function loop(){
view.update();
requestAnimationFrame(loop);
};
loop();
document.body.addEventListener('keypress', function(event){
if (event.charCode == 32) {
algorithm.step();
}
});
(function(){
function save(){
context.drawImage(image, 0, 0);
var canvasData = canvas.toDataURL('image/png');
link.href= canvasData;
link.download = prefix + (n++) + '.png';
link.click();
}
var prefix = 'dijkstra-';
var n = 0;
var container = document.getElementById('container');
var image = new Image();
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var link = document.createElement('a');
link.style = 'display: none'
document.body.appendChild(link);
image.onload = save;
document.body.addEventListener('keypress', function(event){
if (event.charCode == 112) { /* p */
var imageSrc = 'data:image/svg+xml;base64,'+ btoa(container.innerHTML);
image.src = imageSrc;
}
});
})();
window.G = G;
})();
| JavaScript | 0.000017 | @@ -1026,16 +1026,31 @@
== 32) %7B
+ /* spacebar */
%0A
|
6aa29360328877bed73e57f58f26f33dd4524e54 | Update auto-reload.js | js/auto-reload.js | js/auto-reload.js | /*
* auto-reload.js
* https://github.com/savetheinternet/Tinyboard/blob/master/js/auto-reload.js
*
* Brings AJAX to Tinyboard.
*
* Released under the MIT license
* Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
*
* Usage:
* $config['additional_javascript'][] = 'js/jquery.min.js';
* $config['additional_javascript'][] = 'js/auto-reload.js';
*
*/
$(document).ready(function(){
if($('div.banner').length == 0)
return; // not index
var poll_interval;
var poll = function() {
$.ajax({
url: document.location,
success: function(data) {
$(data).find('div.post.reply').each(function() {
var id = $(this).attr('id');
if($('#' + id).length == 0) {
$(this).insertAfter($('div.post:last').next()).after('<br class="clear">');
$(document).trigger('new_post', this);
}
});
}
});
poll_interval = setTimeout(poll, 5000);
};
$(window).scroll(function() {
if($(this).scrollTop() + $(this).height() < $('div.post:last').position().top + $('div.post:last').height()) {
clearTimeout(poll_interval);
poll_interval = false;
return;
}
if(poll_interval === false) {
poll_interval = setTimeout(poll, 1500);
}
}).trigger('scroll');
});
| JavaScript | 0 | @@ -460,16 +460,77 @@
t index%0A
+%09%09%0A%09if($(%22.post.op%22).size() != 1)%0A%09return; //not thread page%0A
%09%0A%09var p
|
8cbce837aac485e92953e3bcfae567968098fd3d | Change marker icon without generating a new imgt p | src/geo/geometry-views/leaflet/leaflet-marker-adapter.js | src/geo/geometry-views/leaflet/leaflet-marker-adapter.js | var L = require('leaflet');
var MarkerAdapterBase = require('../base/marker-adapter-base');
var LeafletMarkerAdapter = function (nativeMarker) {
this._nativeMarker = nativeMarker;
};
LeafletMarkerAdapter.prototype = new MarkerAdapterBase();
LeafletMarkerAdapter.prototype.constructor = LeafletMarkerAdapter;
LeafletMarkerAdapter.prototype.addToMap = function (leafletMap) {
leafletMap.addLayer(this._nativeMarker);
};
LeafletMarkerAdapter.prototype.removeFromMap = function (leafletMap) {
leafletMap.removeLayer(this._nativeMarker);
};
LeafletMarkerAdapter.prototype.isAddedToMap = function (leafletMap) {
return leafletMap.hasLayer(this._nativeMarker);
};
LeafletMarkerAdapter.prototype.getCoordinates = function () {
var latLng = this._nativeMarker.getLatLng();
return {
lat: latLng.lat,
lng: latLng.lng
};
};
LeafletMarkerAdapter.prototype.setCoordinates = function (coordinates) {
this._nativeMarker.setLatLng(coordinates);
};
LeafletMarkerAdapter.prototype.isDraggable = function () {
return this._nativeMarker.options.draggable;
};
LeafletMarkerAdapter.prototype.getIconURL = function () {
return this._nativeMarker.options.icon.options.iconUrl;
};
LeafletMarkerAdapter.prototype.setIconURL = function (iconURL) {
var newIcon = L.icon({
iconUrl: iconURL
});
this._nativeMarker.setIcon(newIcon);
};
LeafletMarkerAdapter.prototype.on = function () {
this._nativeMarker.on.apply(this._nativeMarker, arguments);
};
LeafletMarkerAdapter.prototype.off = function () {
this._nativeMarker.off.apply(this._nativeMarker, arguments);
};
LeafletMarkerAdapter.prototype.trigger = function () {
this._nativeMarker.fire.apply(this._nativeMarker, arguments);
};
module.exports = LeafletMarkerAdapter;
| JavaScript | 0.000001 | @@ -1,32 +1,4 @@
-var L = require('leaflet');%0A
var
@@ -1229,51 +1229,300 @@
%7B%0A
-var newIcon = L.icon(%7B%0A iconUrl:
+// Leaflet provides the %60setIcon%60 method which generates a new img for the icon.%0A // We want to be able to update the markers icon while it's being dragged. That's%0A // why we're doing this little hack that changes the src of the existing marker img.%0A this._nativeMarker._icon.src =
iconURL
%0A %7D
@@ -1521,13 +1521,8 @@
nURL
-%0A %7D)
;%0A
@@ -1544,24 +1544,46 @@
ker.
-setIcon(newIcon)
+options.icon.options.iconUrl = iconURL
;%0A%7D;
|
a0720000661010be549abe6a196ee9d5644338b0 | fix sprite.Group.some() | lib/gamejs/sprite.js | lib/gamejs/sprite.js | var gamejs = require('gamejs');
var sprite = require('gamejs/sprite');
var arrays = require('gamejs/utils/arrays');
/**
* @fileoverview Provides `Sprite` the basic building block for any game and
* `SpriteGroups`, which are an efficient
* way for doing collision detection between groups as well as drawing layered
* groups of objects on the screen.
*
*/
/**
* Your visible game objects will typically subclass Sprite. By setting it's image
* and rect attributes you can control its appeareance. Those attributes control
* where and what `Sprite.draw(surface)` will blit on the the surface.
* Your subclass should overwrite `update(msDuration)` with its own implementation.
* This function is called once every game tick, it is typically used to update
* the status of that object.
* @constructor
*/
var Sprite = exports.Sprite = function() {
/** @ignore */
this._groups = [];
/** @ignore */
this._alive = true;
/**
* Image to be rendered for this Sprite.
* @type gamejs.Surface
*/
this.image = null;
/**
* Rect describing the position of this sprite on the display.
* @type gamejs.Rect
*/
this.rect = null;
return this;
};
Sprite.prototype.kill = function() {
this._alive = false;
this._groups.forEach(function(group) {
group.remove(this);
}, this);
return;
};
Sprite.prototype.remove = function(groups) {
if (!(groups instanceof Array)) groups = [groups];
groups.forEach(function(group) {
group.remove(this);
}, this);
return;
};
Sprite.prototype.add = function(groups) {
if (!(groups instanceof Array)) groups = [groups];
groups.forEach(function(group) {
group.add(this);
}, this);
return;
};
Sprite.prototype.draw = function(surface) {
surface.blit(this.image, this.rect);
return;
};
// overload
Sprite.prototype.update = function() {};
Sprite.prototype.isDead = function() {
return !this._alive;
};
/**
* Sprites are often grouped. That makes collision detection more efficient and
* improves rendering performance. It also allows you to easly keep track of layers
* of objects which are rendered to the screen in a particular order.
*
* `Group.update()` calls `update()` on all the containing screens; the same is true for `draw()`.
* @constructor
*/
var Group = exports.Group = function() {
/** @ignore */
this._sprites = [];
if (arguments[0] instanceof Sprite ||
(arguments[0] instanceof Array &&
arguments[0].length &&
arguments[0][0] instanceof Sprite
)) {
this.add(arguments[0]);
}
return this;
};
Group.prototype.update = function() {
var updateArgs = arguments;
this._sprites.forEach(function(sp) {
sp.update.apply(sp, updateArgs);
}, this);
return;
};
Group.prototype.add = function(sprites) {
if (!(sprites instanceof Array)) sprites = [sprites];
sprites.forEach(function(sprite) {
this._sprites.push(sprite);
sprite._groups.push(this);
}, this);
return;
};
Group.prototype.remove = function(sprites) {
if (!(sprites instanceof Array)) sprites = [sprites];
sprites.forEach(function(sp) {
arrays.remove(sp, this._sprites);
arrays.remove(this, sp._groups);
}, this);
return;
};
Group.prototype.has = function(sprites) {
if (!(sprites instanceof Array)) sprites = [sprites];
return sprites.every(function(sp) {
return this._sprites.indexOf(sp) !== -1;
}, this);
};
Group.prototype.sprites = function() {
return this._sprites;
}
Group.prototype.draw = function() {
var args = arguments;
this._sprites.forEach(function(sprite) {
sprite.draw.apply(sprite, args);
}, this);
return;
};
Group.prototype.empty = function() {
this._sprites = [];
return;
};
/**
* @returns {Array} of sprites colliding with the point
*/
Group.prototype.collidePoint = function() {
var args = Array.prototype.slice.apply(arguments);
return this._sprites.filter(function(sprite) {
return sprite.rect.collidePoint.apply(sprite.rect, args);
}, this);
}
Group.prototype.forEach = function() {
Array.prototype.forEach.apply(this._sprites, arguments);
};
Group.prototype.some = function() {
Array.prototype.some.apply(this._sprites, arguments);
};
/**
* find Sprites in a Group that intersect another Sprite
*/
exports.spriteCollide = function(sprite, group, doKill, collided) {
var collided = collided || collideRect;
var doKill = doKill || false;
var collidingSprites = [];
group.sprites().forEach(function(groupSprite) {
if (collided(sprite, groupSprite)) {
if (doKill) groupSprite.kill();
collidingSprites.push(groupSprite);
}
});
return collidingSprites;
};
/**
* Find all Sprites that collide between two Groups.
* Returns a list of objects with properties 'a', 'b', that hold
* a ref to colliding objects from A and B.
*/
exports.groupCollide = function(groupA, groupB, doKillA, doKillB) {
var doKillA = doKillA || false;
var doKillB = doKillB || false;
var collideList = [];
groupA.sprites().forEach(function(groupSpriteA) {
groupB.sprites().forEach(function(groupSpriteB) {
if (collideRect(groupSpriteA, groupSpriteB)) {
if (doKillA) groupSpriteA.kill();
if (doKillB) groupSpriteB.kill();
collideList.push({
'a': groupSpriteA,
'b': groupSpriteB
});
}
});
});
return collideList;
};
/**
* Collision detection between two sprites, using rects.
*/
var collideRect = exports.collideRect = function(spriteA, spriteB) {
return spriteA.rect.collideRect(spriteB.rect);
};
| JavaScript | 0.000001 | @@ -4225,32 +4225,39 @@
function() %7B%0A
+return
Array.prototype.
|
d8cd1eb7df08c8b983057ea530be4407af0021be | Improve comments and code formatting | lib/gcli/commands.js | lib/gcli/commands.js | /*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
define(function(require, exports, module) {
var Command = require('gcli/canon').Command;
/**
* hidden 'eval' command
*/
var evalCommandSpec = {
name: 'eval',
params: [
{
name: 'javascript',
type: 'javascript',
description: ''
}
],
returnType: 'html',
description: { key: 'commands_eval_javascript' },
exec: function(args, context) {
// → is right arrow
var resultPrefix = '<em>{ ' + args.javascript + ' }</em> → ';
try {
var result = eval(args.javascript);
if (result === null) {
return resultPrefix + 'null.';
}
if (result === undefined) {
return resultPrefix + 'undefined.';
}
if (typeof result === 'function') {
return resultPrefix +
(result + '').replace(/\n/g, '<br>').replace(/ /g, ' ');
}
return resultPrefix + result;
} catch (e) {
return resultPrefix + 'Exception: ' + e.message;
}
}
};
/**
* We don't want to register the eval commands using canon.addCommand(...)
* because we don't want it to pop up in help etc, however it depends on
* types that are dynamically registered/destroyed, so we can't it them be
* static.
*/
var evalCommand = null;
/**
* Registration and de-registration.
*/
exports.getEvalCommand = function() {
if (!evalCommand) {
evalCommand = new Command(evalCommandSpec);
}
return evalCommand;
};
exports.destroyInternalCommands = function() {
evalCommand = null;
};
});
| JavaScript | 0 | @@ -572,17 +572,66 @@
ht arrow
+. We use explicit entities to ensure XML validity
%0A
-
var
@@ -950,24 +950,52 @@
unction') %7B%0A
+ //   is %0A
retu
@@ -1134,16 +1134,20 @@
t;%0A %7D
+%0A
catch (
@@ -1349,16 +1349,34 @@
help etc
+ in the normal way
, howeve
@@ -1379,16 +1379,19 @@
wever it
+%0A *
depends
@@ -1393,19 +1393,16 @@
pends on
-%0A *
types t
@@ -1461,16 +1461,19 @@
t it
+%0A *
them be
%0A *
@@ -1468,19 +1468,16 @@
them be
-%0A *
static.
|
2cdddec3f455da81de246045a65aaf860503ed92 | add tile as a product dependancy | web/app/components/product/product.js | web/app/components/product/product.js | import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngAnimate from 'angular-animate';
import ngAria from 'angular-aria';
import ngMaterial from 'angular-material';
import {productComponent} from './product-component';
export const product = angular.module('product', [
uiRouter,
ngAnimate,
ngAria,
ngMaterial
])
.directive('product', productComponent);
| JavaScript | 0 | @@ -186,16 +186,50 @@
rial';%0A%0A
+import %7Btile%7D from './tile/tile';%0A
import %7B
@@ -373,16 +373,29 @@
Material
+,%0A tile.name
%0A%5D)%0A.dir
|
b4c96353a9c0a3528e7064160704e4ea43ba21e7 | Update grid-register.js | lib/grid-register.js | lib/grid-register.js | import request from 'request-promise';
import { fs } from 'appium-support';
import logger from './logger';
async function registerNode (configFile, addr, port) {
let data;
try {
data = await fs.readFile(configFile, 'utf-8');
} catch (err) {
logger.error(`Unable to load node configuration file to register with grid: ${err.message}`);
return;
}
// Check presence of data before posting it to the selenium grid
if (!data) {
logger.error('No data found in the node configuration file to send to the grid');
return;
}
await postRequest(data, addr, port);
}
async function registerToGrid (options_post, jsonObject) {
try {
let response = await request(options_post);
if (response === undefined || response.statusCode !== 200) {
throw new Error('Request failed');
}
let logMessage = `Appium successfully registered with the grid on ${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}`;
logger.debug(logMessage);
} catch (err) {
logger.error(`Request to register with grid was unsuccessful: ${err.message}`);
}
}
async function postRequest (data, addr, port) {
// parse json to get hub host and port
let jsonObject;
try {
jsonObject = JSON.parse(data);
} catch (err) {
logger.errorAndThrow(`Syntax error in node configuration file: ${err.message}`);
}
// if the node config does not have the appium/webdriver url, host, and port,
// automatically add it based on how appium was initialized
// otherwise, we will take whatever the user setup
// because we will always set localhost/127.0.0.1. this won't work if your
// node and grid aren't in the same place
if (!jsonObject.configuration.url || !jsonObject.configuration.host || !jsonObject.configuration.port) {
jsonObject.configuration.url = `http://${addr}:${port}/wd/hub`;
jsonObject.configuration.host = addr;
jsonObject.configuration.port = port;
// re-serialize the configuration with the auto populated data
data = JSON.stringify(jsonObject);
}
// prepare the header
let post_headers = {
'Content-Type': 'application/json',
'Content-Length': data.length
};
// the post options
let post_options = {
url: `http://${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}/grid/register`,
method: 'POST',
body: data,
headers: post_headers,
resolveWithFullResponse: true // return the full response, not just the body
};
if (jsonObject.configuration.register !== true) {
logger.debug(`No registration sent (${jsonObject.configuration.register} = false)`);
return;
}
let registerCycleTime = jsonObject.configuration.registerCycle;
if (registerCycleTime !== null && registerCycleTime > 0) {
// initiate a new Thread
let first = true;
logger.debug(`Starting auto register thread for grid. Will try to register every ${registerCycleTime} ms.`);
setInterval(async function () {
if (first !== true) {
let isRegistered = await isAlreadyRegistered(jsonObject);
if (isRegistered !== null && isRegistered !== true) {
// make the http POST to the grid for registration
await registerToGrid(post_options, jsonObject);
}
} else {
first = false;
await registerToGrid(post_options, jsonObject);
}
}, registerCycleTime);
}
}
async function isAlreadyRegistered (jsonObject) {
//check if node is already registered
let id = `http://${jsonObject.configuration.host}:${jsonObject.configuration.port}`;
try {
let response = await request({
uri: `http://${jsonObject.configuration.hubHost}:${jsonObject.configuration.hubPort}/grid/api/proxy?id=${id}`,
method : 'GET',
timeout : 10000,
resolveWithFullResponse: true // return the full response, not just the body
});
if (response === undefined || response.statusCode !== 200) {
throw new Error(`Request failed`);
}
let responseData = JSON.parse(response.body);
return responseData.success;
} catch (err) {
logger.debug("Hub down or not responding: ${err.message}");
}
}
export default registerNode;
| JavaScript | 0 | @@ -4011,16 +4011,155 @@
.body);%0A
+ if (responseData.success !== true) %7B%0A logger.debug(%22%5BERROR%5D %22 + responseData.msg); // if register fail,print the debug msg%0A %7D%0A
retu
|
fe009b71a9d178e6e0788e756aa0cc86dbefff68 | fix tests and use utility to setup constants | custom/icds_reports/static/icds_reports/js/spec/indie-map.directive.spec.js | custom/icds_reports/static/icds_reports/js/spec/indie-map.directive.spec.js | /* global module, inject, chai, Datamap, STATES_TOPOJSON, DISTRICT_TOPOJSON, BLOCK_TOPOJSON */
"use strict";
var pageData = hqImport('hqwebapp/js/initial_page_data');
describe('Indie Map Directive', function () {
var $scope, $location, controller, $httpBackend, $storageService;
pageData.registerUrl('icds_locations', 'icds_locations');
var mockGeography = {
geometry: {type: "Polygon", coordinates: []},
id: "test-id",
properties: {STATE_CODE: "09", name: "Uttar Pradesh"},
type: "Feature",
};
var mockData = {
data: {'test-id': {in_month: 0, original_name: ['Uttar Pradesh'], birth: 0, fillKey: "0%-20%"}},
};
var mockFakeData = {
data: {'test-id': {in_month: 0, original_name: [], birth: 0, fillKey: "0%-20%"}},
};
var mockLocation = {
location_type_name: "state",
parent_id: null,
location_id: "9951736acfe54c68948225cc05fbbd63",
name: "Chhattisgarh",
};
var mockLocations = {
'locations': [{
location_type_name: "state",
parent_id: null,
location_id: "9951736acfe54c68948225cc05fbbd63",
name: "Chhattisgarh",
}],
};
beforeEach(module('icdsApp', function ($provide) {
$provide.constant("userLocationId", null);
$provide.constant("isAlertActive", false);
}));
beforeEach(inject(function ($rootScope, _$compile_, _$location_, _$httpBackend_, storageService) {
$scope = $rootScope.$new();
$location = _$location_;
$httpBackend = _$httpBackend_;
$storageService = storageService;
$httpBackend.expectGET('icds_locations').respond(200, mockLocation);
var element = window.angular.element("<indie-map data='test'></indie-map>");
var compiled = _$compile_(element)($scope);
$httpBackend.flush();
$scope.$digest();
controller = compiled.controller('indieMap');
}));
it('tests instantiate the controller properly', function () {
chai.expect(controller).not.to.be.a('undefined');
});
it('tests init topo json when location level not exist', function () {
var locationLevel = $location.search()['selectedLocationLevel'];
assert.equal(locationLevel, null);
assert.equal(controller.scope, 'ind');
assert.equal(controller.type, 'indTopo');
assert.equal(Datamap.prototype['indTopo'], STATES_TOPOJSON);
});
it('tests init topo json when location level equal -1', function () {
$location.search('selectedLocationLevel', -1);
var locationLevel = $location.search()['selectedLocationLevel'];
assert.equal(locationLevel, -1);
assert.equal(controller.scope, 'ind');
assert.equal(controller.type, 'indTopo');
assert.equal(Datamap.prototype['indTopo'], STATES_TOPOJSON);
});
it('tests init topo json when location level equal 4', function () {
$location.search('selectedLocationLevel', 4);
var locationLevel = $location.search()['selectedLocationLevel'];
assert.equal(locationLevel, 4);
assert.equal(controller.scope, 'ind');
assert.equal(controller.type, 'indTopo');
assert.equal(Datamap.prototype['indTopo'], STATES_TOPOJSON);
});
it('tests init topo json when location level equal 0', function () {
$location.search('selectedLocationLevel', 0);
$location.search('location_name', 'Madhya Pradesh');
var locationLevel = $location.search()['selectedLocationLevel'];
var location = {
location_type: "state",
location_type_name: "state",
map_location_name: "Madhya Pradesh",
name: "Madhya Pradesh",
};
assert.equal(locationLevel, 0);
assert.equal(location.name, 'Madhya Pradesh');
controller.initTopoJson(locationLevel, location);
assert.equal(controller.scope, 'Madhya Pradesh');
assert.equal(controller.type, 'Madhya PradeshTopo');
assert.equal(Datamap.prototype['Madhya PradeshTopo'], DISTRICT_TOPOJSON);
});
it('tests init topo json when location level equal 1', function () {
$location.search('selectedLocationLevel', 1);
$location.search('location_name', 'test');
var locationLevel = $location.search()['selectedLocationLevel'];
var location = {
location_type: "state",
location_type_name: "state",
map_location_name: "test_on_map",
name: "test",
};
assert.equal(locationLevel, 1);
assert.equal(location.name, 'test');
controller.initTopoJson(locationLevel, location);
assert.equal(controller.scope, 'test_on_map');
assert.equal(controller.type, 'test_on_mapTopo');
assert.equal(Datamap.prototype['test_on_mapTopo'], BLOCK_TOPOJSON);
});
it('tests html content of update map', function () {
controller.data = mockData;
var expected = '<div class="modal-header"><button type="button" class="close" ' +
'ng-click="$ctrl.closePopup()" aria-label="Close"><span aria-hidden="true">×</span>' +
'</button></div><div class="modal-body"><button class="btn btn-xs btn-default" ' +
'ng-click="$ctrl.updateMap(\'Uttar Pradesh\')">Uttar Pradesh</button></div>';
var result = controller.getHtmlContent(mockGeography);
assert.equal(expected, result);
});
it('tests update map', function () {
controller.data = mockFakeData;
var expected = {};
var result = $location.search();
assert.deepEqual(expected, result);
assert.deepEqual($storageService.getKey('search'), {
"location_id": null,
});
$httpBackend.expectGET('icds_locations?name=test-id').respond(200, mockLocations);
controller.updateMap(mockGeography);
$httpBackend.flush();
expected = {"location_id": "9951736acfe54c68948225cc05fbbd63", "location_name": "test-id"};
result = $location.search();
assert.deepEqual(expected, result);
assert.deepEqual($storageService.getKey('search'), {
"location_name": "test-id", "location_id": "9951736acfe54c68948225cc05fbbd63",
});
});
});
| JavaScript | 0 | @@ -103,16 +103,68 @@
rict%22;%0A%0A
+var utils = hqImport('icds_reports/js/spec/utils');%0A
var page
@@ -1335,92 +1335,53 @@
-$
+utils.
provide
-.constant(%22userLocationId%22, null);%0A $provide.constant(%22isAlertActive%22
+DefaultConstants($provide, false
, fa
|
e1ddbd300d5913831d30b8903373de5eaa254289 | Allow selection of images in folders with extension (#1976) | lib/gui/os/dialog.js | lib/gui/os/dialog.js | /*
* Copyright 2016 resin.io
*
* 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'
const _ = require('lodash')
const electron = require('electron')
const Bluebird = require('bluebird')
const errors = require('../../shared/errors')
const supportedFormats = require('../../shared/supported-formats')
/**
* @summary Current renderer BrowserWindow instance
* @type {Object}
* @private
*/
const currentWindow = electron.remote.getCurrentWindow()
/**
* @summary Open an image selection dialog
* @function
* @public
*
* @description
* Notice that by image, we mean *.img/*.iso/*.zip/etc files.
*
* @fulfil {Object} - selected image
* @returns {Promise};
*
* @example
* osDialog.selectImage().then((image) => {
* console.log('The selected image is', image.path);
* });
*/
exports.selectImage = () => {
return new Bluebird((resolve) => {
electron.remote.dialog.showOpenDialog(currentWindow, {
// This variable is set when running in GNU/Linux from
// inside an AppImage, and represents the working directory
// from where the AppImage was run (which might not be the
// place where the AppImage is located). `OWD` stands for
// "Original Working Directory".
//
// See: https://github.com/probonopd/AppImageKit/commit/1569d6f8540aa6c2c618dbdb5d6fcbf0003952b7
defaultPath: process.env.OWD,
properties: [
'openFile'
],
filters: [
{
name: 'OS Images',
extensions: _.sortBy(supportedFormats.getAllExtensions())
}
]
}, (files) => {
// `_.first` is smart enough to not throw and return `undefined`
// if we pass it an `undefined` value (e.g: when the selection
// dialog was cancelled).
return resolve(_.first(files))
})
})
}
/**
* @summary Open a warning dialog
* @function
* @public
*
* @param {Object} options - options
* @param {String} options.title - dialog title
* @param {String} options.description - dialog description
* @param {String} [options.confirmationLabel="OK"] - confirmation label
* @param {String} [options.rejectionLabel="Cancel"] - rejection label
* @fulfil {Boolean} - whether the dialog was confirmed or not
* @returns {Promise};
*
* @example
* osDialog.showWarning({
* title: 'This is a warning',
* description: 'Are you sure you want to continue?',
* confirmationLabel: 'Yes, continue',
* rejectionLabel: 'Cancel'
* }).then((confirmed) => {
* if (confirmed) {
* console.log('The dialog was confirmed');
* }
* });
*/
exports.showWarning = (options) => {
_.defaults(options, {
confirmationLabel: 'OK',
rejectionLabel: 'Cancel'
})
const BUTTONS = [
options.confirmationLabel,
options.rejectionLabel
]
const BUTTON_CONFIRMATION_INDEX = _.indexOf(BUTTONS, options.confirmationLabel)
const BUTTON_REJECTION_INDEX = _.indexOf(BUTTONS, options.rejectionLabel)
return new Bluebird((resolve) => {
electron.remote.dialog.showMessageBox(currentWindow, {
type: 'warning',
buttons: BUTTONS,
defaultId: BUTTON_REJECTION_INDEX,
cancelId: BUTTON_REJECTION_INDEX,
title: 'Attention',
message: options.title,
detail: options.description
}, (response) => {
return resolve(response === BUTTON_CONFIRMATION_INDEX)
})
})
}
/**
* @summary Show error dialog for an Error instance
* @function
* @public
*
* @param {Error} error - error
*
* @example
* osDialog.showError(new Error('Foo Bar'));
*/
exports.showError = (error) => {
const title = errors.getTitle(error)
const message = errors.getDescription(error)
electron.remote.dialog.showErrorBox(title, message)
}
| JavaScript | 0 | @@ -1873,17 +1873,16 @@
nv.OWD,%0A
-%0A
pr
@@ -1911,16 +1911,51 @@
penFile'
+,%0A 'treatPackageAsDirectory'
%0A %5D
|
fd980054e51d18d0d15aa38ee67eddff6ce1d766 | Replace if with ternary | scripts/wee-routes.js | scripts/wee-routes.js | import pathToRegExp from 'path-to-regexp';
import { _castString, $isArray, $isFunction, $isString, $unserialize } from 'core/types';
import { _doc } from 'core/variables';
import { $exec } from 'core/core';
const REMOVE_SLASHES_REGEXP = /^\/|\/$/g;
let _routes = [];
let _filters = {};
/**
* Add a route to routes array
*
* @param routes
* @private
*/
function _addRoutes(routes) {
const count = routes.length;
for (let i = 0; i < count; i++) {
let route = _getRoute(routes[i].path);
if (route) {
_routes[route.index] = routes[i];
break;
}
_routes.push(routes[i]);
}
}
/**
* Add a filter to the filter registry
*
* @param name
* @param handler
* @private
*/
function _addFilter(name, handler) {
_filters[name] = handler;
}
/**
* Add multiple filters to filter registry
* @param filters
* @private
*/
function _addFilters(filters) {
filters.forEach(filter => _addFilter(filter.name, filter.handler));
}
/**
* Process filters
*
* @param filter
* @returns {Function|string|Array}
* @private
*/
function _processFilters(filters) {
let shouldExec = true;
if (filters) {
if ($isFunction(filters)) {
shouldExec = $exec(filters);
} else if ($isString(filters)) {
if (_filters[filters]) {
shouldExec = $exec(_filters[filters]);
}
} else if ($isArray(filters)) {
let length = filters.length;
for (let i = 0; i < length; i++) {
let filter = _filters[filters[i]];
if (filter) {
shouldExec = $exec(filter);
if (shouldExec === false) {
break;
}
}
}
}
}
return shouldExec;
}
/**
* Retrieve existing route with associated index
*
* @param {string} value
* @param {string} key
* @returns {Object}
* @private
*/
function _getRoute(value) {
const count = _routes.length;
for (let i = 0; i < count; i++) {
let route = _routes[i];
if (route.path === value || route.name === value) {
return {
route: route,
index: i
};
}
}
return null;
}
/**
* Parse url and return results
*
* @param {string} value
* @returns {Object}
* @private
*/
function _parseUrl(value) {
const a = _doc.createElement('a');
a.href = value || window.location;
const search = a.search,
path = a.pathname.replace(REMOVE_SLASHES_REGEXP, '');
return {
full: '/' + path + search + a.hash,
hash: a.hash.slice(1),
path: '/' + path,
query: search ? $unserialize(search) : {},
segments: path.split('/'),
url: a.href,
port: a.port
};
}
/**
* Extract parameters from current URL based on matching route
*
* @param {string} path
* @param {string} location
* @returns {Object}
* @private
*/
function _getParams(path, location) {
let keys = [],
params = {},
results = pathToRegExp(path, keys).exec(location);
if ($isArray(results)) {
results.slice(1)
.forEach((segment, j) => params[keys[j].name] = _castString(segment));
}
return Object.keys(params).length ? params : null;
}
export default {
/**
* Register routes
*
* @param {Array} routes
* @returns {Object}
*/
map(routes) {
_addRoutes(routes);
return this;
},
/**
* Reset all routes and filters - mainly for testing purposes
*/
reset() {
_routes = [];
_filters = {};
},
/**
* Retrieve all routes or specific route by name/path
*
* @param {string} [value]
* @returns {Object|Array}
*/
routes(value) {
if (value) {
let result = _getRoute(value);
if (result) {
return result.route;
}
}
return _routes;
},
run() {
const uri = this.uri();
const length = _routes.length;
let shouldExec = true;
for (let i = 0; i < length; i++) {
let route = _routes[i];
let path = route.path;
let params = _getParams(path, uri.full);
if (params) {
path = pathToRegExp.compile(path)(params);
}
if (uri.full === path) {
shouldExec = _processFilters(route.filter);
if (shouldExec) {
$exec(route.handler, {
args: [params]
});
}
break;
}
}
},
/**
* Retrieve information about current location
*
* @param {string} [value]
* @returns {Object}
*/
uri(value) {
return _parseUrl(value);
},
/**
* Add a filter or array of filters to internal filter registry
*
* @param {string|Array} name
* @param {Function} [callback]
*/
addFilter(name, callback) {
if ($isArray(name)) {
_addFilters(name);
} else {
_addFilter(name, callback)
}
return this;
},
/**
* Return all registered filters
*
* @returns {{}}
*/
filters() {
return _filters;
}
}; | JavaScript | 1 | @@ -3621,34 +3621,8 @@
i%5D;%0A
-%09%09%09let path = route.path;%0A
%09%09%09l
@@ -3665,37 +3665,36 @@
l);%0A
-%0A
%09%09%09
-if (
+let path =
params
-) %7B
+ ?
%0A%09%09%09%09
-path =
+%09
path
@@ -3710,16 +3710,22 @@
compile(
+route.
path)(pa
@@ -3729,22 +3729,30 @@
(params)
-;%0A%09%09%09%7D
+ : route.path;
%0A%0A%09%09%09if
|
87175045520a8df31dadc2fbd81b683e4284d261 | repair subscribe handling | js/controllers.js | js/controllers.js | 'use strict';
var target = 'http://eneid-api.herokuapp.com/api/';
myApp.factory('Message', ['$resource', function ($resource) {
return $resource(target + 'timeline');
}]);
myApp.factory('User', ['$resource', function ($resource) {
return $resource(target + 'users');
}]);
myApp.controller('TimeLineController', function ($scope, $timeout, Message, $cookies, $route) {
$scope.currentTimeline = 0;
$scope.update = function () {
$scope.messages = Message.query();
$scope.currentTimeline = $scope.currentTimeline + 1;
$timeout($scope.update, 10000);
};
if (!!$cookies.token) {
$scope.update();
}
$scope.sendMessage = function () {
new Message({contents: $scope.content}).$save();
$scope.content = '';
$route.reload();
}
});
myApp.controller('LoggedController', function ($scope, $cookies, $location, $http) {
$scope.disconnect = function () {
delete $cookies.token;
delete $http.defaults.headers.common['Authorization'];
$location.path("/auth");
};
$scope.isLogged = function () {
return !!$cookies.token;
};
$scope.cssClasspath = function () {
return $location.path().substring(1);
}
});
myApp.controller('AuthController', function ($http, $scope, $cookies, $base64, $location) {
$scope.auth = function (email, password) {
var token = $base64.encode(email + ":" + password);
$http.get(target + "timeline", {headers: {"Authorization": "Basic " + token}}).success(function () {
$cookies.token = token;
$http.defaults.headers.common['Authorization'] = "Basic " + $cookies.token;
$location.path("/timeline");
}).error(function (content, error_code) {
console.log("error " + error_code + " during logging");
});
};
$scope.subscribe = function () {
$location.path("/subscribe");
}
});
myApp.controller('SubscribeController', function ($http, $scope, User, $cookies, $base64, $location) {
$scope.subscribe = function (email, password, name, firstName) {
console.log(email, password, name, firstName);
var user = new User({ "email": email, "password": password, "name": name, "firstName": firstName });
user.$save();
console.log(user);
$cookies.token = $base64.encode(email + ":" + password);
$http.defaults.headers.common['Authorization'] = "Basic " + $cookies.token;
$location.path("/timeline");
};
});
| JavaScript | 0 | @@ -2296,27 +2296,39 @@
r.$save(
-);%0A
+function () %7B%0A
console.
@@ -2311,32 +2311,35 @@
n () %7B%0A
+
console.log(user
@@ -2334,20 +2334,25 @@
ole.log(
-user
+arguments
);%0A
@@ -2346,32 +2346,36 @@
ments);%0A
+
+
$cookies.token =
@@ -2407,32 +2407,36 @@
:%22 + password);%0A
+
$http.de
@@ -2503,32 +2503,36 @@
.token;%0A
+
+
$location.path(%22
@@ -2540,23 +2540,96 @@
timeline%22);%0A
+ %7D, function () %7B%0A console.log(arguments);%0A %7D);%0A
%7D;%0A%7D);%0A
|
2ada6c33fca5a88ae22411408b7f6e35fd309831 | Stop functionality wont remove the application untill the refresh occurs | app/assets/javascripts/angular/controllers/winged_monkey_controllers.js | app/assets/javascripts/angular/controllers/winged_monkey_controllers.js | var wingedMonkeyControllers = angular.module('wingedMonkeyControllers',[]);
wingedMonkeyControllers.controller("ProviderAppsCtrl", function($scope, $filter, ProviderApplication) {
$scope.appsLoaded = false;
$scope.refreshProviderApps = function() {
ProviderApplication.query(function(data){
$scope.providerApps = data;
$scope.appsLoaded = true;
});
};
$scope.refreshProviderApps();
$scope.destroyProviderApp = function(app_id) {
$scope.providerApps.forEach(function(app, index) {
if (app_id === app.id) {
app.$delete({id: app.id}, function() {
//success
$scope.providerApps.splice(index, 1);
}, function(response){
//failure
console.log(response);
});
}
});
};
});
| JavaScript | 0 | @@ -549,16 +549,19 @@
%0A
+ //
app.$de
@@ -604,29 +604,128 @@
- //success%0A
+ProviderApplication.delete(%7Bid: app.id%7D, function() %7B%0A //success%0A app.state = %22DELETING%22;%0A //
$sc
|
c033306709dda30edf08dd2ad6412ef382bd20ee | add .running goal flag | lib/interval-scan.js | lib/interval-scan.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.
'use strict';
var assert = require('assert');
var inherits = require('util').inherits;
var EventEmitter = require('tchannel/lib/event_emitter.js');
// TODO: track and report run stats
// - elapsed
// - lag
// - collection size at start
// - per-item elapsed
function IntervalScan(options) {
assert(typeof options.name === 'string',
'must have a name string');
assert(typeof options.each === 'function',
'each must be a function');
assert(typeof options.getCollection === 'function',
'getCollection must be a function');
assert(options.timers,
'must have timers');
var self = this;
EventEmitter.call(self);
self.runBeginEvent = self.defineEvent('runBegin');
self.runEndEvent = self.defineEvent('runEnd');
self.name = options.name;
self.interval = options.interval;
self.each = options.each;
self.getCollection = options.getCollection;
self.timers = options.timers;
self.timer = null;
self.theRun = null;
self.boundRun = run;
function run() {
self.run();
}
}
inherits(IntervalScan, EventEmitter);
IntervalScan.prototype.setInterval =
function setInterval(interval) {
var self = this;
if (self.interval === interval) {
if (!self.timer) {
self.setTimer();
}
return;
}
self.interval = interval;
if (self.timer) {
self.clearTimer();
self.setTimer();
}
};
IntervalScan.prototype.setTimer =
function setTimer() {
var self = this;
if (self.timer || self.theRun || self.interval <= 0) {
return;
}
self.timer = self.timers.setTimeout(self.boundRun, self.interval);
};
IntervalScan.prototype.start =
function start() {
var self = this;
self.setTimer();
};
IntervalScan.prototype.stop =
function stop() {
var self = this;
self.clearTimer();
if (self.theRun) {
self.theRun.clearImmediate();
self.theRun = null;
}
};
IntervalScan.prototype.clearTimer =
function clearTimer() {
var self = this;
if (self.timer) {
self.timers.clearTimeout(self.timer);
self.timer = null;
}
};
IntervalScan.prototype.run =
function run(callback) {
var self = this;
if (self.theRun) {
if (callback) {
callback(new Error('already running'));
}
return;
}
self.clearTimer();
self.theRun = new IntervalScanRun(self, runDone);
function runDone() {
self.theRun = null;
self.setTimer();
if (callback) {
callback();
}
}
};
function IntervalScanRun(scan, callback) {
var self = this;
self.scan = scan;
self.immediate = null;
self.keyIndex = 0;
self.start = null;
self.end = null;
self.collection = null;
self.keys = null;
self.callback = callback;
self.immediate = self.scan.timers.setImmediate(startRun);
function startRun() {
self.start = self.scan.timers.now();
self.collection = self.scan.getCollection();
self.keys = Object.keys(self.collection);
self.scan.runBeginEvent.emit(self.scan, self);
self.nextItem();
}
self.boundDeferNextItem = deferNextItem;
function deferNextItem() {
self.keyIndex++;
self.nextItem();
}
}
IntervalScanRun.prototype.nextItem =
function nextItem() {
var self = this;
if (self.keyIndex < self.keys.length) {
var key = self.keys[self.keyIndex];
var val = self.collection[key];
if (val !== undefined) {
self.scan.each(key, val);
}
self.immediate = self.scan.timers.setImmediate(self.boundDeferNextItem);
} else {
self.finish();
}
};
IntervalScanRun.prototype.finish =
function finish() {
var self = this;
if (self.end === null) {
self.end = self.scan.timers.now();
self.scan.runEndEvent.emit(self.scan, self);
}
if (self.callback) {
self.callback();
self.callback = null;
}
};
IntervalScanRun.prototype.clearImmediate =
function clearImmediate() {
var self = this;
if (self.immediate) {
self.scan.timers.clearImmediate(self.immediate);
self.immediate = null;
}
};
IntervalScan.Run = IntervalScanRun;
module.exports = IntervalScan;
| JavaScript | 0.000001 | @@ -2078,24 +2078,50 @@
ns.timers;%0A%0A
+ self.running = false;%0A
self.tim
@@ -2416,19 +2416,20 @@
if (
-!
self.
-timer
+running
) %7B%0A
@@ -2902,32 +2902,57 @@
r self = this;%0A%0A
+ self.running = true;%0A
self.setTime
@@ -3022,32 +3022,58 @@
r self = this;%0A%0A
+ self.running = false;%0A
self.clearTi
|
b4dbc7fdda88de3c18a2b1d23fb29894ae407903 | Add event handlers for links in ending soon alert | app/imports/ui/components/alerts/alert-ending-soon/alert-ending-soon.js | app/imports/ui/components/alerts/alert-ending-soon/alert-ending-soon.js | import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import moment from 'moment';
import './alert-ending-soon.html';
Template.AlertEndingSoon.onCreated(function onCreated() {
const self = this;
self.threshold = moment.duration(20, 'minutes').asMilliseconds();
self.timeRemaining = new ReactiveVar(0);
self.autorun(() => {
const queue = Template.currentData().queue;
if (self.timeRemainingInterval) Meteor.clearInterval(self.timeRemainingInterval);
self.timeRemainingInterval = Meteor.setInterval(() => {
self.timeRemaining.set(moment(queue.scheduledEndTime).diff(moment()));
}, 1000);
});
});
Template.AlertEndingSoon.helpers({
endingSoon(queue) {
const timeRemaining = Template.instance().timeRemaining.get();
return !queue.isEnded() &&
(timeRemaining > 0) &&
(timeRemaining < Template.instance().threshold);
},
timeRemaining() {
return moment.duration(Template.instance().timeRemaining.get()).humanize();
},
});
| JavaScript | 0 | @@ -1069,12 +1069,356 @@
);%0A %7D,%0A%7D);%0A
+%0ATemplate.AlertEndingSoon.events(%7B%0A 'click .js-edit-end-time'() %7B%0A $('.modal-queue-edit').modal();%0A %7D,%0A%0A 'click .js-end-now'() %7B%0A const ok = confirm('Are you sure you want to end this queue?');%0A if (!ok) return;%0A%0A endQueue.call(%7B%0A queueId: this.queue._id,%0A %7D, (err) =%3E %7B%0A if (err) console.log(err);%0A %7D);%0A %7D,%0A%7D);%0A
|
95693b5bbcd667cfbe5379b4c8a5fd74fa9f8c11 | set webpack stats chunks | server/bin/compile.js | server/bin/compile.js | const helpers = require('../../config/helpers')
const Rimraf = require('rimraf')
const debug = require('debug')('app:build:compile')
const Webpack = require('webpack')
const webpackConfig = require(helpers('./webpack.config.js'))
debug('Starting webpack compile.')
const webpackCompiler = webpackConfig => (
new Promise((resolve, reject) => {
const compiler = Webpack(webpackConfig)
debug('Compiler ------>>>>>>')
compiler.run((error, stats) => {
if (error) {
debug('Webpack compiler encountered a fatal error.', error)
return reject(error)
}
const jsonStats = stats.toJson()
debug(stats.toString({
chunks: true,
chunkModules: true,
colors: true
}))
if (jsonStats.errors.length > 0) {
debug('Webpack compiler encountered errors.')
debug(jsonStats.errors.join('\n'))
return reject(new Error('Webpack compiler encountered errors'))
} else if (jsonStats.warnings.length > 0) {
debug('Webpack compiler encountered warnings.')
debug(jsonStats.warnings.join('\n'))
} else {
debug('No errors or warnings encountered.')
}
return resolve(jsonStats)
})
})
)
const compile = () => {
Promise.resolve().then(() => {
debug('Rm build dir.')
Rimraf(helpers('dist'), error => {
if (error) {
throw new error()
}
return webpackCompiler(webpackConfig)
})
})
.then(stats => {
// success
debug('Webpack: Compiled successfully.')
})
.catch(error => {
debug('Compile error.', error)
process.exit(1)
})
}
compile()
| JavaScript | 0.000001 | @@ -666,19 +666,20 @@
chunks:
-tru
+fals
e,%0A
@@ -695,19 +695,20 @@
odules:
-tru
+fals
e,%0A
|
09ffb04e4032361a4f9fe64572349d145f36edef | fix up demos restore functionality which was broken by removal of Dataset.restore for #196. | demos/multiview/app.js | demos/multiview/app.js | jQuery(function($) {
window.dataExplorer = null;
window.explorerDiv = $('.data-explorer-here');
// This is some fancy stuff to allow configuring the multiview from
// parameters in the query string
//
// For more on state see the view documentation.
var state = recline.View.parseQueryString(decodeURIComponent(window.location.search));
if (state) {
_.each(state, function(value, key) {
try {
value = JSON.parse(value);
} catch(e) {}
state[key] = value;
});
} else {
state.url = 'demo';
}
var dataset = null;
if (state.dataset || state.url) {
dataset = recline.Model.Dataset.restore(state);
} else {
var dataset = new recline.Model.Dataset({
records: [
{id: 0, date: '2011-01-01', x: 1, y: 2, z: 3, country: 'DE', title: 'first', lat:52.56, lon:13.40},
{id: 1, date: '2011-02-02', x: 2, y: 4, z: 24, country: 'UK', title: 'second', lat:54.97, lon:-1.60},
{id: 2, date: '2011-03-03', x: 3, y: 6, z: 9, country: 'US', title: 'third', lat:40.00, lon:-75.5},
{id: 3, date: '2011-04-04', x: 4, y: 8, z: 6, country: 'UK', title: 'fourth', lat:57.27, lon:-6.20},
{id: 4, date: '2011-05-04', x: 5, y: 10, z: 15, country: 'UK', title: 'fifth', lat:51.58, lon:0},
{id: 5, date: '2011-06-02', x: 6, y: 12, z: 18, country: 'DE', title: 'sixth', lat:51.04, lon:7.9}
],
// let's be really explicit about fields
// Plus take opportunity to set date to be a date field and set some labels
fields: [
{id: 'id'},
{id: 'date', type: 'date'},
{id: 'x'},
{id: 'y'},
{id: 'z'},
{id: 'country', 'label': 'Country'},
{id: 'title', 'label': 'Title'},
{id: 'lat'},
{id: 'lon'}
]
});
}
createExplorer(dataset, state);
});
// make Explorer creation / initialization in a function so we can call it
// again and again
var createExplorer = function(dataset, state) {
// remove existing data explorer view
var reload = false;
if (window.dataExplorer) {
window.dataExplorer.remove();
reload = true;
}
window.dataExplorer = null;
var $el = $('<div />');
$el.appendTo(window.explorerDiv);
var views = [
{
id: 'grid',
label: 'Grid',
view: new recline.View.SlickGrid({
model: dataset
}),
},
{
id: 'graph',
label: 'Graph',
view: new recline.View.Graph({
model: dataset
}),
},
{
id: 'map',
label: 'Map',
view: new recline.View.Map({
model: dataset
}),
},
{
id: 'transform',
label: 'Transform',
view: new recline.View.Transform({
model: dataset
})
}
];
window.dataExplorer = new recline.View.MultiView({
model: dataset,
el: $el,
state: state,
views: views
});
}
| JavaScript | 0 | @@ -603,25 +603,153 @@
) %7B%0A
+var
dataset
- =
+Info = _.extend(%7B%0A url: state.url,%0A backend: state.backend%0A %7D,%0A state.dataset%0A );%0A dataset = new
recline
@@ -766,22 +766,20 @@
aset
-.restore(state
+(datasetInfo
);%0A
|
b11060c6734714a7e647bd035dcb8d63eb070457 | fix bug | js/jquery.json.js | js/jquery.json.js | /*!
* jQuery Json Plugin (with Transition Definitions)
* Examples and documentation at: http://json.cn/
* Copyright (c) 2012-2013 China.Ren.
* Version: 1.0.2 (19-OCT-2013)
* Dual licensed under the MIT and GPL licenses.
* http://jquery.malsup.com/license.html
* Requires: jQuery v1.3.1 or later
*/
var JSONFormat = (function(){
var _toString = Object.prototype.toString;
var _bigNums = [];
function format(object, indent_count){
var html_fragment = '';
switch(_typeof(object)){
case 'Null' :0
html_fragment = _format_null(object);
break;
case 'Boolean' :
html_fragment = _format_boolean(object);
break;
case 'Number' :
html_fragment = _format_number(object);
break;
case 'String' :
html_fragment = _format_string(object);
break;
case 'Array' :
html_fragment = _format_array(object, indent_count);
break;
case 'Object' :
html_fragment = _format_object(object, indent_count);
break;
}
return html_fragment;
};
function _format_null(object){
return '<span class="json_null">null</span>';
}
function _format_boolean(object){
return '<span class="json_boolean">' + object + '</span>';
}
function _format_number(object){
return '<span class="json_number">' + object + '</span>';
}
function _format_string(object){
if(!isNaN(object) && object.length>=15 && $.inArray(object, _bigNums)>-1){
return _format_number(object);
}
object = object.replace(/\</g,"<");
object = object.replace(/\>/g,">");
if(0 <= object.search(/^http/)){
object = '<a href="' + object + '" target="_blank" class="json_link">' + object + '</a>'
}
return '<span class="json_string">"' + object + '"</span>';
}
function _format_array(object, indent_count){
var tmp_array = [];
for(var i = 0, size = object.length; i < size; ++i){
tmp_array.push(indent_tab(indent_count) + format(object[i], indent_count + 1));
}
return '<span data-type="array" data-size="' + tmp_array.length + '"><i style="cursor:pointer;" class="fa fa-minus-square-o" onclick="hide(this)"></i>[<br/>'
+ tmp_array.join(',<br/>')
+ '<br/>' + indent_tab(indent_count - 1) + ']</span>';
}
function _format_object(object, indent_count){
var tmp_array = [];
for(var key in object){
tmp_array.push( indent_tab(indent_count) + '<span class="json_key">"' + key + '"</span>:' + format(object[key], indent_count + 1));
}
return '<span data-type="object"><i style="cursor:pointer;" class="fa fa-minus-square-o" onclick="hide(this)"></i>{<br/>'
+ tmp_array.join(',<br/>')
+ '<br/>' + indent_tab(indent_count - 1) + '}</span>';
}
function indent_tab(indent_count){
return (new Array(indent_count + 1)).join(' ');
}
function _typeof(object){
var tf = typeof object,
ts = _toString.call(object);
return null === object ? 'Null' :
'undefined' == tf ? 'Undefined' :
'boolean' == tf ? 'Boolean' :
'number' == tf ? 'Number' :
'string' == tf ? 'String' :
'[object Function]' == ts ? 'Function' :
'[object Array]' == ts ? 'Array' :
'[object Date]' == ts ? 'Date' : 'Object';
};
function loadCssString(){
var style = document.createElement('style');
style.type = 'text/css';
var code = Array.prototype.slice.apply(arguments).join('');
try{
style.appendChild(document.createTextNode(code));
}catch(ex){
style.styleSheet.cssText = code;
}
document.getElementsByTagName('head')[0].appendChild(style);
}
loadCssString(
'.json_key{ color: #92278f;font-weight:bold;}',
'.json_null{color: #f1592a;font-weight:bold;}',
'.json_string{ color: #3ab54a;font-weight:bold;}',
'.json_number{ color: #25aae2;font-weight:bold;}',
'.json_boolean{ color: #f98280;font-weight:bold;}',
'.json_link{ color: #61D2D6;font-weight:bold;}',
'.json_array_brackets{}');
var _JSONFormat = function(origin_data){
//this.data = origin_data ? origin_data :
//JSON && JSON.parse ? JSON.parse(origin_data) : eval('(' + origin_data + ')');
_bigNums = [];
var check_data = origin_data.replace(/\s/g,'');
var bigNum_regex = /([\[:]){1}(\d{15,})([,\}\]])/;
var tmp_bigNums = check_data.match(bigNum_regex);
if(tmp_bigNums!=null && tmp_bigNums.length>2){
_bigNums.push(tmp_bigNums[2]);
origin_data=origin_data.replace(/([\[:])?(\d{15,})([,\}\]])/, "$1\"$2\"$3");
}
this.data = JSON.parse(origin_data);
};
_JSONFormat.prototype = {
constructor : JSONFormat,
toString : function(){
return format(this.data, 1);
}
}
return _JSONFormat;
})();
var last_html = '';
function hide(obj){
var data_type = obj.parentNode.getAttribute('data-type');
var data_size = obj.parentNode.getAttribute('data-size');
obj.parentNode.setAttribute('data-inner',obj.parentNode.innerHTML);
if (data_type === 'array') {
obj.parentNode.innerHTML = '<i style="cursor:pointer;" class="fa fa-plus-square-o" onclick="show(this)"></i>Array[<span class="json_number">' + data_size + '</span>]';
}else{
obj.parentNode.innerHTML = '<i style="cursor:pointer;" class="fa fa-plus-square-o" onclick="show(this)"></i>Object{...}';
}
}
function show(obj){
var innerHtml = obj.parentNode.getAttribute('data-inner');
obj.parentNode.innerHTML = innerHtml;
}
| JavaScript | 0.000001 | @@ -3157,20 +3157,28 @@
).join('
-
+
');%0A
|
7bc900f7b9d18e55011aaeca2abce06e8c2554ce | Add some js bits to the swift Test model. | demos/swift/js/Test.js | demos/swift/js/Test.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
name: 'Test',
requires: [
'somepackage.RequiredClass',
],
imports: [
'testImport',
'testImport2 as testImportTwo',
],
exports: [
'firstName',
],
messages: [
{
name: 'greeting',
message: 'Hello there ${first} ${last}',
description: 'Greeting where ${last} is last name and ${first} is first.',
}
],
properties: [
{
name: 'id',
hidden: true,
swiftExpressionArgs: ['firstName'],
swiftExpression: 'return firstName',
},
{
name: 'anyProp',
},
{
class: 'String',
name: 'exprProp',
swiftExpressionArgs: ['firstName', 'lastName'],
swiftExpression: function() {/*
return firstName + " " + lastName
*/},
},
{
class: 'Int',
name: 'intProp',
},
{
class: 'Boolean',
name: 'boolProp',
},
{
class: 'String',
name: 'prevFirstName',
},
{
class: 'String',
name: 'prevLastName',
},
{
class: 'String',
name: 'firstName',
value: 'John',
swiftPreSet: function() {/*
self.prevFirstName = oldValue as? String ?? ""
return newValue
*/},
},
{
class: 'String',
name: 'lastName',
value: 'Smith',
swiftPostSet: 'self.prevLastName = oldValue as? String ?? ""'
},
{
name: 'factoryProp',
swiftFactory: function() {/*
return ["Hello", "World"]
*/},
},
],
actions: [
{
name: 'swapFirstAndLast',
swiftCode: function() {/*
let firstName = self.firstName
self.firstName = self.lastName
self.lastName = firstName
*/},
},
{
name: 'startLogger',
swiftCode: function() {/*
myListener()
*/},
},
],
methods: [
{
name: 'methodWithAnArgAndReturn',
swiftReturns: 'String',
args: [
{
name: 'name',
swiftType: 'String',
},
],
swiftCode: function() {/*
return String(format: type(of: self).greeting, name, "LASTNAME")
*/},
}
],
listeners: [
{
name: 'myListener',
isMerged: true,
mergeDelay: 500,
swiftCode: function() {/*
NSLog("Hey")
myListener()
*/},
},
],
});
| JavaScript | 0 | @@ -226,16 +226,17 @@
stImport
+?
',%0A '
@@ -246,16 +246,17 @@
tImport2
+?
as test
@@ -627,32 +627,92 @@
urn firstName',%0A
+ expression: function(firstName) %7B return firstName %7D,%0A
%7D,%0A %7B%0A
@@ -1685,24 +1685,51 @@
stAndLast',%0A
+ code: function() %7B%7D,%0A
swiftC
@@ -1883,24 +1883,51 @@
artLogger',%0A
+ code: function() %7B%7D,%0A
swiftC
@@ -2170,16 +2170,43 @@
%5D,%0A
+ code: function() %7B%7D,%0A
sw
@@ -2381,24 +2381,24 @@
rged: true,%0A
-
mergeD
@@ -2408,16 +2408,43 @@
y: 500,%0A
+ code: function() %7B%7D,%0A
sw
|
6104146375acc2d3240be79ed466e0db733fa9a7 | Refactor stub connector and haystack connector code to fix test environment | server/config/base.js | server/config/base.js | module.exports = {
// app port
port: 8080,
// use when https endpoint is needed
// https: {
// keyFile: '', // path for private key file
// certFile: '' // path for ssh cert file
// },
// whether to start in cluster mode or not
cluster: false,
// default timeout in ms for all the downlevels from connector
upstreamTimeout: 55000,
graphite: {
host: 'host',
port: 2003
},
// Refresh interval for auto refreshing trends and alerts
refreshInterval: 60000,
// Google Analytics Tracking ID
gaTrackingID: 'UA-XXXXXXXX-X',
// Feature switches
enableServicePerformance: true,
enableServiceLevelTrends: true,
// this list defines subsystems for which UI should be enabled
// traces connector must be there in connectors config
connectors: {
traces: {
// name of config connector module to use for fetching traces data from downstream
// Options (connector) :
// - haystack - gets data from haystack query service
// - zipkin - bridge for using an existing zipkin api,
// zipkin connector expects a zipkin config field specifying zipkin api url,
// eg. zipkinUrl: 'http://<zipkin>/api/v1'}
// - stub - a stub used during development, will be removed in future
connectorName: 'stub'
},
trends: {
// name of config connector module to use for fetching trends data from downstream
// Options :
// - haystack - gets data from Haystack Metric Tank Setup
// haystack connector also expects config field specifying metricTankUrl
// - stub - a stub used during development, will be removed in future
connectorName: 'stub',
encoder: 'periodreplacement'
},
alerts: {
// name of config connector module to use for fetching anomaly detection data from downstream
// Options :
// - stub - a stub used during development, will be removed in future
connectorName: 'stub',
// frequency of alerts coming in the system
alertFreqInSec: 300,
// While merging the successive alerts, need a buffer time. We will accept the point if successive alert is
// within this buffer
alertMergeBufferTimeInSec: 60,
subscriptions: {
// name of config connector module to use for managing subscriptions
// Options :
// - stub - a stub used during development, will be removed in future
// - meghduta - gets data from Meghduta, this will also need `meghdutaApiUrl`
connectorName: 'stub',
enabled: true
}
},
serviceGraph: {
// name of config connector module to use for fetching dependency graph data from downstream
// options :
// - stub - a stub used during development, will be removed in future
// - haystack - gets data from haystack-service-graph
// you must specify serviceGraphUrl
// e.g. serviceGraphUrl: 'https://<haystack>/serviceGraph'
connectorName: 'stub',
windowSizeInMillis: 3600
}
},
// use if you need SAML back SSO auth
//
// enableSSO: true, // flag for enabling sso
// saml: {
// entry_point: '', // SAML entrypoint
// issuer: '' // SAML issuer
// },
// sessionTimeout: 60 * 60 * 1000, // timeout for session
// sessionSecret: 'XXXXXXXXXXXXX' // secret key for session
};
| JavaScript | 0 | @@ -2704,103 +2704,8 @@
ure%0A
- // - meghduta - gets data from Meghduta, this will also need %60meghdutaApiUrl%60%0A
@@ -3324,25 +3324,24 @@
%7D%0A %7D
-,
%0A%0A // use
|
2b2bd73702f44cd4de92c58324d7c77ff16bde02 | handle new travis states (for building) | js/models/Repo.js | js/models/Repo.js | define(
[
'jquery',
'backbone',
'underscore',
'moment'
],
function ($, Backbone, _, moment) {
"use strict";
return Backbone.Model.extend({
STATUS_PASSED: 'passed',
STATUS_FAILED: 'failed',
STATUS_BUILDING: 'building',
STATUS_UNKNOWN: 'unknown',
isFetchingGithubData: false,
url: function () {
var base = $('body').data('api-url') + '/repos';
return this.isNew() ? base : base + '/' + this.id;
},
fetchGitHubData: function () {
if (this.get('last_release_tag_name') || this.isFetchingGithubData || !this.get('github_access_token')) {
return;
}
this.isFetchingGithubData = true;
var repo = this;
$.getJSON('https://api.github.com/repos/' + this.get('slug') + '/releases?access_token=' + this.get('github_access_token'))
.done(function (releases) {
if (undefined !== releases[0]) {
repo.set('last_release_tag_name', releases[0].tag_name);
repo.set('last_release_html_url', releases[0].html_url);
repo.set('last_release_published_at', releases[0].published_at);
}
}).always(function () {
repo.isFetchingGithubData = false;
});
$.getJSON('https://api.github.com/repos/' + this.get('slug') + '?access_token=' + this.get('github_access_token'))
.done(function (repoInfo) {
repo.set('open_issues_count', repoInfo.open_issues_count);
});
},
presenter: function () {
return _.extend(this.toJSON(), {
status: this.getStatus(),
travisUrl: this.getTravisUrl(),
githubUrl: this.getGithubUrl(),
lastBuildFinishedAt: this.getLastBuildFinishedAt(),
humanizedLastBuildFinishedAt: this.getHumanizedBuildFinishedAt(),
lastReleaseTagName: this.getLastReleaseTagName(),
lastReleaseUrl: this.getLastReleaseUrl(),
lastReleasePublishedAt: this.getLastReleasePublishedAt(),
nbOpenIssues: this.getNbOpenIssues()
});
},
getStatus: function () {
if (null !== this.getLastBuildStartedAt() &&
null === this.getLastBuildFinishedAt()) {
return this.STATUS_BUILDING;
}
if ('passed' === this.get('last_build_state')) {
return this.STATUS_PASSED;
} else if ('errored' === this.get('last_build_state') || 'failed' === this.get('last_build_state')) {
return this.STATUS_FAILED;
}
return this.STATUS_UNKNOWN;
},
getTravisUrl: function () {
return 'https://travis-ci.org/' + this.get('slug') + '/builds/' + this.get('last_build_id');
},
getGithubUrl: function () {
return 'https://github.com/' + this.get('slug');
},
getLastBuildStartedAt: function () {
return this.get('last_build_started_at');
},
getLastBuildFinishedAt: function () {
return this.get('last_build_finished_at');
},
getHumanizedBuildFinishedAt: function () {
if (this.getLastBuildFinishedAt()) {
return moment(this.getLastBuildFinishedAt()).fromNow();
}
return '';
},
getLastReleaseTagName: function () {
this.fetchGitHubData();
return this.get('last_release_tag_name');
},
getLastReleaseUrl: function () {
this.fetchGitHubData();
return this.get('last_release_html_url');
},
getLastReleasePublishedAt: function () {
this.fetchGitHubData();
if (this.get('last_release_published_at')) {
return moment(this.get('last_release_published_at')).fromNow();
}
return 'n/a';
},
getNbOpenIssues: function () {
this.fetchGitHubData();
return undefined !== this.get('open_issues_count') ? this.get('open_issues_count') : 0;
},
isFailed: function () {
return this.STATUS_FAILED === this.getStatus();
},
getRank: function () {
switch (this.getStatus()) {
case this.STATUS_PASSED:
return 4;
case this.STATUS_FAILED:
return 2;
case this.STATUS_BUILDING:
return 1;
default:
return 3;
}
}
});
}
);
| JavaScript | 0 | @@ -2702,32 +2702,212 @@
%7D%0A%0A
+ if ('created' === this.get('last_build_state') %7C%7C 'started' === this.get('last_build_state')) %7B%0A return this.STATUS_BUILDING;%0A %7D%0A%0A
|
45c6d14ecda8ff3c51abae18082baaea3f01e73b | update url | deploy-robot.config.js | deploy-robot.config.js | const authorizedAuthors = ['plantain-00']
const filter = (comment, author) => comment.indexOf('robot') >= 0 &&
comment.indexOf('deploy') >= 0 &&
comment.indexOf('please') >= 0 &&
authorizedAuthors.findIndex(a => a === author) >= 0
module.exports = function (defaultConfig) {
defaultConfig.applications = [
{
repositoryName: 'deploy-robot-demo',
hookSecret: 'test secret',
pullRequest: {
getTestUrl (port, pullRequestId) {
return `http://106.15.39.164:${port}/`
},
mergedCommand: '/opt/scripts/pr_merged.sh',
openedCommand: '/opt/scripts/pr_opened.sh',
closedCommand: '/opt/scripts/pr_closed.sh',
updatedCommand: '/opt/scripts/pr_updated.sh'
},
commentActions: [
{
filter,
command: '/opt/scripts/deploy.sh',
gotMessage: '正在部署...',
doneMessage: '部署已完成,https://deploy-demo.yorkyao.xyz/'
}
]
},
{
repositoryName: 'deploy-robot-backend-demo',
hookSecret: 'test secret',
pullRequest: {
getTestUrl (port, pullRequestId) {
return `http://106.15.39.164:${port}/api/`
},
mergedCommand: '/opt/backend_scripts/pr_merged.sh',
openedCommand: '/opt/backend_scripts/pr_opened.sh',
closedCommand: '/opt/backend_scripts/pr_closed.sh',
updatedCommand: '/opt/backend_scripts/pr_updated.sh'
},
commentActions: [
{
filter,
command: '/opt/backend_scripts/deploy.sh',
gotMessage: '正在部署...',
doneMessage: '部署已完成,https://deploy-demo.yorkyao.xyz/api/'
}
]
}
]
}
| JavaScript | 0.001357 | @@ -921,19 +921,19 @@
yorkyao.
-xyz
+com
/'%0A
@@ -1620,11 +1620,11 @@
yao.
-xyz
+com
/api
|
525d36c00242663e6c02e9022902d07728245f8d | Simplify check of callback function | js/models/list.js | js/models/list.js | "use strict";
var ko = require("knockout");
var Task = require("./task.js");
var generateId = require("uuid").v4;
var List = function List(options) {
options = options || {};
this.id = ko.observable(options.id || generateId());
this.tasks = ko.observableArray([]);
this.storage = ko.observable();
this.apiUrl = options.apiUrl || null;
this.apiClient = options.apiClient || null;
var filterHiddenPropertiesFromJson = function (key, value) {
if (key[0] === "_") {
return undefined;
} else {
return value;
}
};
this.saveToStorage = function () {
var json = ko.toJSON(this, filterHiddenPropertiesFromJson);
if (this.storage()) {
this.storage().setItem(this.id(), json);
}
};
this.loadFromStorage = function (doneCallback) {
this.storage().getItem(this.id(), function (err, json) {
var data = JSON.parse(json);
this.tasks(ko.utils.arrayMap(data.tasks, function (taskData) {
return new Task(taskData, this.tasks);
}.bind(this)));
if (doneCallback && typeof doneCallback === "function") {
doneCallback();
}
}.bind(this));
};
this.saveToServer = function () {
var json = ko.toJSON(this, filterHiddenPropertiesFromJson);
if(this.apiClient) {
this.apiClient.ajax({
type: "PUT",
url: this.apiUrl + "list/" + this.id(),
data: json
});
}
};
this.addingTitle = ko.observable("");
this.addTask = function () {
if (this.addingTitle().trim() !== "") {
this.tasks.push(new Task(this.addingTitle().trim(), this.tasks));
this.addingTitle("");
this.saveToStorage();
}
};
var changeHandler = function () {
this.saveToStorage();
this.saveToServer();
}.bind(this);
this.tasks.subscribe(changeHandler);
this.tasks.subscribe(changeHandler, null, "child changed");
};
module.exports = List;
| JavaScript | 0.00003 | @@ -1132,24 +1132,8 @@
if (
-doneCallback &&
type
@@ -1195,16 +1195,26 @@
allback(
+null, this
);%0A
|
7e57b2d4b8ac66a988cf682261cd2882e694e4aa | refactor path for bigquery | server/initGraphQL.js | server/initGraphQL.js | const fs = require('fs')
const path = require('path')
const bodyParser = require('body-parser')
const { apolloUploadExpress } = require('apollo-upload-server')
const { bigquery_service_endpoint, is_optics_enabled, dev } = require('./config')
const OpticsAgent = require('optics-agent')
const rimraf = require('rimraf')
const CronJob = require('cron').CronJob
// isomorphic-fetch
require('es6-promise').polyfill()
require('isomorphic-fetch')
const { GenericError } = require('./errors')
require('./debug')
const uploadDir = './.tmp'
// https://stackoverflow.com/questions/19167297/in-node-delete-all-files-older-than-an-hour
function removeUpload (ms) {
debug.info(`GraphQL : cleaning ${uploadDir}`)
if (!fs.existsSync(uploadDir)) {
return
}
fs.readdir(uploadDir, (err, files) => {
if (err) {
return debug.error('GraphQL :', err)
}
files.forEach(function (file, index) {
fs.stat(path.join(uploadDir, file), function (err, stat) {
var endTime, now
if (err) {
return debug.error('GraphQL :', err)
}
now = new Date().getTime()
endTime = new Date(stat.ctime).getTime() + ms
if (now > endTime) {
return rimraf(path.join(uploadDir, file), function (err) {
if (err) {
return debug.error(err)
}
debug.info(`GraphQL : removed ${uploadDir}/${file}`)
})
}
})
})
})
}
const init = ({ graphiql_enabled: graphiql, base_url, port, e_wallet_enabled }, app) => {
// Custom GraphQL
NAP.expose = {
extendModel: require('./graphql').extendModel,
setBuildGraphqlSchema: require('./graphql').setBuildGraphqlSchema,
FileType: require('./graphql/types/File'),
GenderType: require('./graphql/types/Gender'),
getFile: require('./graphql').getFile
}
if (fs.existsSync(path.resolve(__dirname, '../graphql/setup.js'))) {
require('../graphql/setup')
}
// CORS
const cors = require('cors')
app.use(cors())
// Helmet
const helmet = require('helmet')
app.use(helmet())
// GraphQL
const graphqlHTTP = require('express-graphql')
const { buildSchema } = require('./graphql')
const { authenticate } = require('./jwt-token')
const schema = is_optics_enabled ? OpticsAgent.instrumentSchema(buildSchema()) : buildSchema()
is_optics_enabled && app.use(OpticsAgent.middleware())
// attach middleware
if (bigquery_service_endpoint) {
const { insertQuery, initMiddleWare } = require('../bigquery/queryCollection')
const chalk = require('chalk')
app.all('/bigQuery/insert', async (req, res) => {
try {
insertQuery(req, res)
} catch (e) {
console.log(chalk.bgRed('BigQuery service error'))
res.status(501).end()
}
})
app.use(initMiddleWare())
}
const initEWallet = (req, res, next) => {
if (e_wallet_enabled) {
req.ewallet = global.NAP.EWallet.getEWallet(req.token)
}
next()
}
const _removeUpload = () => removeUpload(24 * 60 * 60 * 1000)
_removeUpload()
const job = new CronJob({
cronTime: '00 00 05 * * *',
onTick: () => _removeUpload(),
timeZone: 'Asia/Bangkok'
})
job.start()
app.use(
'/graphql',
// http://www.senchalabs.org/connect/limit.html
function limit (req, res, next) {
let received = 0
const bytes = 20 * 1024 * 1024
const len = req.headers['content-length'] ? parseInt(req.headers['content-length'], 10) : null
if (len && len > bytes) return res.status(413).send('content-length is to long')
req.on('new Listener', function handler (event) {
if (event !== 'data') return
req.removeListener('new Listener', handler)
process.nextTick(listen)
})
next()
function listen () {
req.on('data', function (chunk) {
received += Buffer.isBuffer(chunk)
? chunk.length
: Buffer.byteLength(chunk)
if (received > bytes) req.destroy()
})
}
},
bodyParser.json(),
// upload.array('files'),
apolloUploadExpress({
uploadDir
}),
authenticate,
initEWallet,
graphqlHTTP(() => ({
schema,
graphiql,
formatError: ({ originalError, message, stack }) => {
if (originalError && !(originalError instanceof GenericError)) {
console.error('GraphQL track:', originalError)
}
return {
message: message,
code: originalError ? originalError.code : null,
stack: dev ? stack.split('\n') : null
}
}
}))
)
// Status
debug.info(`GraphQL :`, graphiql ? `${base_url}/graphql` : 'N/A')
}
module.exports = init
| JavaScript | 0.01039 | @@ -2576,17 +2576,17 @@
ll('/big
-Q
+q
uery/ins
|
5005c3d42f0cc9aeaa3b051f8bf8a3cad07f9fe8 | Improve clickable behaviour for dropzone | client/acp/components/ImageDrop.react.js | client/acp/components/ImageDrop.react.js | var React = require('react'),
ReactPropTypes = React.PropTypes,
Actions = require('../actions/Actions'),
Dropzone = require('dropzone'),
dropzone = null;
var ImageDrop = React.createClass({
propTypes: {
action : ReactPropTypes.string.isRequired,
dataUrl : ReactPropTypes.string.isRequired,
imageDidSelect: ReactPropTypes.func.isRequired,
success : ReactPropTypes.func.isRequired,
uploadProgress: ReactPropTypes.func.isRequired
},
componentDidMount: function () {
var self = this;
Dropzone.autoDiscover = false;
dropzone = new Dropzone(this.getDOMNode(), {
url : this.props.action,
paramName: 'award',
clickable: true,
maxFiles : 1,
//Overwrite Dropzone events
addedfile: function (file) {
},
success: function (file, response) {
self.props.success(file, response);
},
thumbnail: function (file, dataUrl) {
self.props.imageDidSelect(file, dataUrl);
},
uploadprogress: function (file, progress, bytesSent) {
self.props.uploadProgress(file, progress, bytesSent);
}
});
},
componentWillUnmount: function () {
dropzone.destroy();
dropzone = null;
},
render: function () {
if (this.props.dataUrl) {
return (
<div className="award-preview center-block">
<img className="img-responsive" src={this.props.dataUrl}/>
</div>
);
}
return (
<i className="fa fa-cloud-upload award-upload-icon"></i>
);
}
});
module.exports = ImageDrop; | JavaScript | 0.000001 | @@ -652,48 +652,130 @@
-dropzone = new Dropzone(this.getDOMNode(
+//this.getDOMNode() does not work with complex html%0A dropzone = new Dropzone(React.findDOMNode(this.refs.uploadIcon
), %7B
@@ -1793,32 +1793,54 @@
return (%0A
+ %3Cdiv%3E%0A
%3Ci c
@@ -1890,12 +1890,48 @@
con%22
-%3E%3C/i
+ ref=%22uploadIcon%22%3E%3C/i%3E%0A %3C/div
%3E%0A
|
c6d428ae80e4ea576a6be556ccbcc4378cd3ce23 | fix badge display order bug | client/app/profile/profile.controller.js | client/app/profile/profile.controller.js | 'use strict';
angular.module('hrr10MjbeApp')
.controller('ProfileCtrl', function($scope, $state, Student, Skills) {
$scope.message = 'Hello';
$scope.accepted = 'false';
Skills.getSkills(function(skills) {
$scope.skills = skills;
$scope.skillsData = JSON.stringify(skills);
console.log(skills);
//Student.addOrUpdateSkill(skills[0]._id, 4);
//Student.awardBadges();
//console.log(skills);
});
Student.getSkills(function(skills) {
$scope.studentSkills = skills;
$scope.studentSkillsData = JSON.stringify(skills);
console.log(skills);
//Student.addOrUpdateSkill(skills[0]._id, 4);
//Student.awardBadges();
//console.log(skills);
});
Student.getRequests(function(requests) {
$scope.request = requests[0];
console.log(requests);
});
Student.getTeacher(function(teacher) {
console.log(teacher);
$scope.teacher = teacher;
})
Student.getJoined(function(joined) {
$scope.joined = new Date(joined).toDateString();
})
Student.getName(function(name) {
$scope.name = name;
})
$scope.go = function(){
$state.go('s', {
id: $scope.userselection
});
}
Student.getPoints(function(points) {
$scope.points = points;
})
Student.getBadges(function(badges) {
$scope.badge = badges && badges.length ? JSON.stringify(badges[0]) : 'null';
})
Student.getTimes(function(times) {
console.log('times');
console.log(times);
$scope.times = JSON.stringify(times);
})
$scope.polymerChange = function() {
if ($scope.userselection) {
$scope.go();
}
if ($scope.accepted === 'true') {
console.log('accepting');
Student.acceptRequest(JSON.parse($scope.request), function(res) {
console.log(res);
});
}
}
});
| JavaScript | 0 | @@ -1420,17 +1420,33 @@
(badges%5B
-0
+badges.length - 1
%5D) : 'nu
|
dcbd835b71bf6c88ecc1400505b68ed3d9b995c9 | Streamline push notification | client/scripts/lib/push-notifications.js | client/scripts/lib/push-notifications.js | /* global $ */
import swPromise from './sw.js';
import {sendSubscriptionToServer} from './api.js';
import {notify, warn, error} from './notify';
export default function pushNotifications() {
const pushBanner = $('#emoji__push');
if (pushBanner) {
pushBanner.style.display = 'none';
pushBanner.on('click', subscribe);
}
function subscribe() {
notify('Subscribing');
pushBanner.classList.add('working');
swPromise.then(serviceWorkerRegistration => {
serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
.then(function(subscription) {
pushBanner.style.display = 'none';
return sendSubscriptionToServer(subscription);
notify('Success!');
})
.catch(function(e) {
if (Notification.permission === 'denied') {
pushBanner.style.display = '';
warn('Permission for Notifications was denied');
} else {
// A problem occurred with the subscription; common reasons
// include network errors, and lacking gcm_sender_id and/or
// gcm_user_visible_only in the manifest.
error('Unable to subscribe to push.');
console.log(e);
}
})
.then(() => {
pushBanner.classList.remove('working');
});
});
}
swPromise
.then(serviceWorkerRegistration => serviceWorkerRegistration.pushManager.getSubscription())
.then(subscription => {
if (!subscription) {
if (pushBanner) {
// Not subscribed: show subscribe button
pushBanner.style.display = '';
}
} else {
// Update server with correct info.
return sendSubscriptionToServer(subscription);
}
})
.catch(e => {
// Service workers not supported.
console.log('service workers/push notifications not supported.')
console.log(e);
});
}
| JavaScript | 0 | @@ -423,24 +423,28 @@
romise.then(
+%0A%09%09%09
serviceWorke
@@ -460,21 +460,16 @@
tion =%3E
-%7B%0A%09%09%09
serviceW
@@ -530,24 +530,27 @@
ly: true%7D)%0A%09
+%09)%0A
%09%09.then(func
@@ -569,25 +569,24 @@
ption) %7B%0A%09%09%09
-%09
pushBanner.s
@@ -608,17 +608,16 @@
'none';%0A
-%09
%09%09%09retur
@@ -662,39 +662,13 @@
n);%0A
-%09%09%09%09notify('Success!');%0A%09
%09%09%7D)%0A
-%09
%09%09.c
@@ -686,17 +686,16 @@
on(e) %7B%0A
-%09
%09%09%09if (N
@@ -733,17 +733,16 @@
ied') %7B%0A
-%09
%09%09%09%09push
@@ -772,17 +772,16 @@
'';%0A%09%09%09%09
-%09
warn('Pe
@@ -824,17 +824,16 @@
d');%0A%09%09%09
-%09
%7D else %7B
@@ -834,17 +834,16 @@
else %7B%0A%0A
-%09
%09%09%09%09// A
@@ -902,17 +902,16 @@
ons%0A%09%09%09%09
-%09
// inclu
@@ -962,17 +962,16 @@
and/or%0A
-%09
%09%09%09%09// g
@@ -1012,17 +1012,16 @@
st.%0A%09%09%09%09
-%09
error('U
@@ -1051,17 +1051,16 @@
ush.');%0A
-%09
%09%09%09%09cons
@@ -1078,18 +1078,15 @@
%0A%09%09%09
-%09
%7D%0A
-%09
%09%09%7D)%0A
-%09
%09%09.t
@@ -1097,17 +1097,16 @@
() =%3E %7B%0A
-%09
%09%09%09pushB
@@ -1144,15 +1144,8 @@
');%0A
-%09%09%09%7D);%0A
%09%09%7D)
|
7431f968eb8f8a75423f4ebee29ad3dd7bbfb0d8 | Update Landing.js | client/src/components/Landing/Landing.js | client/src/components/Landing/Landing.js | import React, {Component} from 'react'
import Card from './Card'
import './Landing.css'
import {Row, Col, Container} from 'reactstrap'
import verejneDataIcon from './icons/verejne_data.png'
import prepojeniaIcon from './icons/prepojenia.png'
import obstaravaniaIcon from './icons/obstaravania.png'
import profilyIcon from './icons/profily.png'
class Landing extends Component {
render() {
return (
<div className="landing">
<Container tag="main" role="main" className="landing-container">
<h1 className="title landing-title">
<b>verejne</b>.digital
</h1>
<p className="lead landing-lead">
Aplikácie umelej inteligencie<br /> na dáta slovenských verejných inštitúcii
</p>
<Row className="landing-cards">
<Col md="6" lg="3">
<Card
to="/verejne"
title="Verejné dáta"
text="Obchodujú moji susedia so štátom alebo čerpajú eurofondy?"
imgSrc={verejneDataIcon}
/>
</Col>
<Col md="6" lg="3">
<Card
to="/prepojenia"
title="Prepojenia"
text="Sú víťazi verejných obstarávaní prepojení na politokov?"
imgSrc={prepojeniaIcon}
/>
</Col>
<Col md="6" lg="3">
<Card
to="/obstaravania"
title="Obstarávania"
text="Vyhrávajú firmy, ktoré sú v strate alebo založené len pár dní vopred?"
imgSrc={obstaravaniaIcon}
/>
</Col>
<Col md="6" lg="3">
<Card
to="/profil"
title="Profily"
text="Majetok poslancov podľa priznaní a katastra"
imgSrc={profilyIcon}
/>
</Col>
</Row>
</Container>
<footer className="landing-footer">
<div className="container">
<ul className="float-md-right list-inline">
<li className="list-inline-item">
<a href="https://www.zastavmekorupciu.sk/">
<img src="/nzk.png" alt="Nadácia Zastavme Korupciu" />
</a>
</li>
<li className="list-inline-item">
<a href="https://slovensko.digital/">
<img src="/slovenko.png" alt="slovenko.digital" />
</a>
</li>
<li className="list-inline-item">
<a href="https://www.finstat.sk/">
<img src="/finstat.png" alt="FinStat" />
</a>
</li>
</ul>
<ul className="float-md-left list-inline landing-footer-text">
<li className="list-inline-item list-inline-item-text">
<a
href="https://medium.com/@verejne.digital/o-%C4%8Do-ide-verejne-digital-14a1c6dcbe09"
target="_blank"
rel="noopener noreferrer"
>
O projekte
</a>
</li>
<li className="list-inline-item list-inline-item-text">
<a
href="http://www.facebook.com/verejne.digital"
target="_blank"
rel="noopener noreferrer"
>
Kontaktujte nás cez facebook
</a>
</li>
</ul>
</div>
</footer>
</div>
)
}
}
export default Landing
| JavaScript | 0 | @@ -732,17 +732,17 @@
n%C5%A1tit%C3%BAci
-i
+%C3%AD
%0A
@@ -959,41 +959,41 @@
dia
-so %C5%A1t%C3%A1tom alebo %C4%8Derpaj%C3%BA eurofondy
+alebo obchodn%C3%AD partneri so %C5%A1t%C3%A1tom
?%22%0A
@@ -1214,62 +1214,45 @@
xt=%22
-S%C3%BA v%C3%AD%C5%A5azi verejn%C3%BDch obstar%C3%A1van%C3%AD prepojen%C3%AD na politokov
+Ak%C3%A9 s%C3%BA vz%C5%A5ahy medzi firmami a osobami
?%22%0A
@@ -1476,76 +1476,59 @@
xt=%22
-Vyhr%C3%A1vaj%C3%BA firmy, ktor%C3%A9 s%C3%BA v strate alebo zalo%C5%BEen%C3%A9 len p%C3%A1r dn%C3%AD vopred
+Do ktor%C3%BDch v%C3%BDziev sa prihl%C3%A1si%C5%A5 a ktor%C3%A9 s%C3%BA podozriv%C3%A9
?%22%0A
@@ -1717,16 +1717,16 @@
rofily%22%0A
-
@@ -1782,16 +1782,17 @@
katastra
+.
%22%0A
|
822f82d118435d5085fbcafae38693a1a4565db2 | add attr and related functions | d.js | d.js | import toArray from './util/toArray'
import objectAssign from './util/objectAssign'
class DOM {
constructor (selector) {
let elements = document.querySelectorAll(selector)
this.length = elements.length
objectAssign(this, elements)
}
map (fn) {
toArray(this).map(el => fn.call(el, el))
return this
}
each (fn) {
toArray(this).forEach(el => fn.call(el, el))
return this
}
reduce (fn) {
toArray(this).forEach(el => fn.call(el, el))
return this
}
addClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.add(...classes))
}
removeClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.add(...classes))
}
toggleClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.toggle(...classes))
}
hasClass (className) {
for (let el of toArray(this)) {
if (el.classList.contains(className)) {
return true
}
}
return false
}
on (eventNames, callback) {
let events = eventNames.split(' ')
events.forEach(event =>
this.map(el => el.addEventListener(event, callback, false))
)
return this
}
}
window.$ = window.d = selector => new DOM(selector)
| JavaScript | 0 | @@ -1234,16 +1234,475 @@
this%0A %7D
+%0A%0A attr (attributeName, value=null) %7B%0A if (value == null) %7B%0A return this%5B0%5D%5BattributeName%5D%0A %7D else %7B%0A return this.each(el =%3E el%5BattributeName%5D = value)%0A %7D%0A %7D%0A%0A val (value=null) %7B%0A if (value == null) %7B%0A return this.attr('value')%0A %7D else %7B%0A this.attr('value', value)%0A %7D%0A %7D%0A%0A text (value=null) %7B%0A if (value == null) %7B%0A return this.attr('textContent')%0A %7D else %7B%0A this.attr('textContent', value)%0A %7D%0A %7D
%0A%7D%0A%0Awind
|
068f9393987f58aa6373d34c82e818940186c346 | Update league.js | templates/league.js | templates/league.js | /**
* Created by anonymoussc on 08/03/15 11:05.
*/
'use strict';
var moment = require('moment'),
S = require('string'),
dataSrc = require('./../../config/dataSrc/dataSrc.json'),
cfg = require('./../../config/config.js');
// path to directory
var name = 'league',
srcPath = cfg.templatesDirectory + '/skeleton/',
destPath = cfg.workspaces + '/' + name + '/' + dataSrc.package_name + '/';
var
league = {
name : name,
base : {
src : [
srcPath + '.*',
srcPath + '*.*',
'!' + srcPath + 'src/',
'!' + srcPath + 'tests/'
],
fileName: false,
dest : destPath
},
src : {
src : srcPath + 'src/' + '*.stub',
fileName: S('-' + dataSrc.package_name).camelize().s + 'Class.php', // StudlyCaps,
dest : destPath + 'src/'
},
tests: {
src : srcPath + 'tests/' + '*.stub',
fileName: S('-' + dataSrc.package_name).camelize().s + 'Test.php', // StudlyCaps
dest : destPath + 'tests/'
}
};
module.exports = league;
| JavaScript | 0.000001 | @@ -152,27 +152,24 @@
quire('./../
-../
config/dataS
@@ -215,19 +215,16 @@
e('./../
-../
config/c
|
7e82a9bc25f6eb64242ecff944a2078b7a75e843 | Add test for latest version link. | tests/simple/http-api-versioning.js | tests/simple/http-api-versioning.js | /*
* Licensed to Cloudkick, Inc ('Cloudkick') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Cloudkick licenses this file to You 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.
*/
var path = require('path');
var root = path.dirname(__filename);
require.paths.unshift(path.join(root, '../'));
var assert = require('assert');
var http = require('services/http');
// test route function
(function() {
var i, expected_routes, expected_routes_len;
var api_version, version_routes, version_routes_len;
var func = function() {}
var routes = [
['PUT /foo/bar/$', '1.0', func],
['POST /foobar/$', '2.0', func],
['GET /foobar/$', '1.1', func],
['HEAD /foobar/$', '1.2', func],
['DELETE /foobar/$', '2.0', func]
]
var expected_result = {
'1.0': [ ['PUT /foo/bar/$', func] ],
'1.1': [ ['GET /foobar/$', func] ],
'1.2': [ ['HEAD /foobar/$', func] ],
'2.0': [ ['POST /foobar/$', func], ['DELETE /foobar/$', func] ]
}
clutch_routes = http.route(routes);
assert.equal(Object.keys(clutch_routes).length, 4);
for (api_version in clutch_routes) {
assert.ok(expected_result.hasOwnProperty(api_version));
version_routes = clutch_routes[api_version];
version_routes_len = version_routes.length;
expected_routes = expected_result[api_version];
expected_routes_len = expected_routes.length
assert.equal(version_routes_len, expected_routes_len);
for (i = 0; i < version_routes_len; i++) {
version_route_args = version_routes[i];
expected_routes_args = expected_routes[i];
assert.equal(version_route_args[0], expected_routes_args[0]);
assert.equal(version_route_args[1], expected_routes_args[1]);
}
}
})();
// test URL routing
(function() {
var n = 0;
assert.response(http._serverOnly('data/http_services/', [ 'test-service' ]), {
url: '/1.0/test-service/',
method: 'GET'
},
function(res) {
n++;
assert.equal(res.statusCode, 200);
var data = JSON.parse(res.body);
console.log(data)
assert.equal(data.text, 'test 1.0');
});
assert.response(http._serverOnly('data/http_services/', [ 'test-service' ]), {
url: '/2.0/test-service/',
method: 'GET'
},
function(res) {
n++;
assert.equal(res.statusCode, 202);
var data = JSON.parse(res.body);
assert.equal(data.text, 'test 2.0');
});
assert.response(http._serverOnly('data/http_services/', [ 'test-service' ]), {
url: '/5.5/test-service/',
method: 'GET'
},
function(res) {
n++;
assert.equal(res.statusCode, 404);
});
process.on('exit', function() {
assert.equal(n, 3, 'Callbacks called');
});
})();
| JavaScript | 0 | @@ -900,24 +900,74 @@
, '../'));%0A%0A
+var sprintf = require('extern/sprintf').sprintf;%0A%0A
var assert =
@@ -2414,16 +2414,46 @@
r n = 0;
+%0A var latest_version = '2.0';
%0A%0A asse
@@ -3251,16 +3251,396 @@
%0A %7D);%0A%0A
+ assert.response(http._serverOnly('data/http_services/', %5B 'test-service' %5D,%0A latest_version), %7B%0A url: '/test-service/',%0A method: 'GET'%0A %7D,%0A%0A function(res) %7B%0A n++;%0A assert.equal(res.statusCode, 202);%0A var data = JSON.parse(res.body);%0A console.log(data)%0A assert.equal(data.text, sprintf('test %25s', latest_version));%0A %7D);%0A%0A
proces
@@ -3689,9 +3689,9 @@
(n,
-3
+4
, 'C
|
5207326a5e7ddc1b68ab6df6be4ba479430d2642 | Use localIdentName to identify className on development If mode is equal development we add a hash using path + local + base64:5 eg. src-overview-results-components-__main--dzcJi | build/loaders.js | build/loaders.js | // NOTE: Loader `include` paths are relative to this module
import path from 'path'
import CssExtractPlugin from 'mini-css-extract-plugin'
import { externalTsModules } from './external'
export const threadLoader = {
loader: 'thread-loader',
options: {
poolTimeout: Infinity, // Threads won't timeout/need to be restarted on inc. builds
workers: require('os').cpus().length - 1,
},
}
export const eslintLoader = {
loader: 'eslint-loader',
options: {
cache: true,
},
}
export const babelLoader = {
loader: 'babel-loader',
}
export const tsLoader = {
loader: 'ts-loader',
options: {
happyPackMode: true,
},
}
export const coffeescriptLoader = {
loader: 'coffeescript-loader',
}
export const injectStylesLoader = {
loader: 'style-loader',
}
export const extractStylesLoader = {
loader: CssExtractPlugin.loader,
}
export const cssModulesLoader = {
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
},
}
export const cssVanillaLoader = {
loader: 'css-loader',
}
export const postcssLoader = {
loader: 'postcss-loader',
}
export const urlLoader = {
loader: 'url-loader',
options: {
limit: 8192,
},
}
export const svgLoader = {
test: /\.svg$/,
include: /node_modules/, // Only resolve SVG imports from node_modules (imported CSS) - for now
loader: 'svg-inline-loader',
}
export default ({ mode, context, isCI = false, injectStyles = false }) => {
// style-loader's general method of inserting <style> tags into the `document` doesn't
// seem to play nicely with the content_script. It would be nice to find a work-around
// later as style-loader is nicer for dev.
const styleLoader = injectStyles ? injectStylesLoader : extractStylesLoader
const main = {
test: /\.(j|t)sx?$/,
include: [
path.resolve(context, './src'),
...externalTsModules.map(mod =>
path.resolve(context, `./external/${mod}`),
),
],
use: [babelLoader, tsLoader],
}
const coffee = {
test: /\.coffee?$/,
include: path.resolve(context, './src/direct-linking'),
use: [babelLoader, coffeescriptLoader],
}
const cssModules = {
test: /\.css$/,
include: path.resolve(context, './src'),
use: [styleLoader, cssModulesLoader, postcssLoader],
}
const cssVanilla = {
test: /\.css$/,
include: path.resolve(context, './node_modules'),
use: [styleLoader, cssVanillaLoader],
}
const lint = {
test: /\.jsx?$/,
include: path.resolve(context, './src'),
use: [eslintLoader],
}
const imgLoader = {
test: /\.(png|jpg|gif|svg)$/,
include: path.resolve(context, './img'),
use: [urlLoader],
}
if (isCI) {
return [main, coffee, imgLoader, cssModules, cssVanilla]
}
if (mode !== 'production') {
main.use = [threadLoader, ...main.use]
}
return [main, coffee, imgLoader, lint, cssModules, cssVanilla]
}
| JavaScript | 0.000059 | @@ -1020,32 +1020,123 @@
s: 1,%0A %7D,%0A%7D%0A%0A
+export const localIdentName = %7B%0A localIdentName: '%5Bpath%5D__%5Blocal%5D--%5Bhash:base64:5%5D',%0A%7D%0A%0A
export const css
@@ -3137,16 +3137,142 @@
in.use%5D%0A
+ cssModulesLoader.options = Object.assign(%0A cssModulesLoader.options,%0A localIdentName,%0A )%0A
%7D%0A%0A
|
ac24ccd8464ca5606336733b9a96bf8c4fe52a81 | Add comment to postcss script | build/postcss.js | build/postcss.js | const postcss = require('postcss');
const glob = require('glob');
const fs = require('fs-extra');
const chalk = require('chalk');
const syntax = require('postcss-wee-syntax');
const paths = require('./paths');
// Config
const config = fs.readJsonSync(paths.project + '/wee.json');
const breakpoints = config.style.breakpoints;
const features = config.style.features;
const compile = config.style.compile;
const variables = require(paths.styles + '/variables.js')();
const plugins = [
require('postcss-variables')({
globals: variables
}),
require('postcss-js-mixins')({
mixins: Object.assign(require(paths.weeCore + '/styles/mixins.js')(variables), require(paths.styles + '/mixins.js')(variables))
}),
require('postcss-nested-selectors')(),
require('postcss-nested')({
bubble: Object.keys(breakpoints)
}),
require('postcss-variable-media')({
breakpoints: calcBreakpoints(breakpoints, config.style.breakpointOffset)
}),
require('autoprefixer')({
browsers: [
'last 2 versions',
'ie > 9'
]
}),
require('cssnano')({
safe: true
})
];
let ignore = [];
let result = '';
/**
* Calculate breakpoints with offset included
*
* @param {Object} breakpoints
* @param {number} offset
* @returns {Object}
*/
function calcBreakpoints(breakpoints, offset) {
for (let breakpoint in breakpoints) {
breakpoints[breakpoint] = breakpoints[breakpoint] - offset;
}
return breakpoints;
}
/**
* Change camelCase to dash-case (including numbers)
*
* @param value
* @returns {string}
*/
function convertCamelToDash(value) {
return value.replace(/([a-z])([A-Z])/g, '$1-$2')
.toLowerCase()
.replace(/([a-z])([0-9])/g, '$1-$2');
}
/**
* Find and return file(s) content
*
* @param {string} filePath
* @returns {string}
*/
function getCSS(filePath) {
let base = filePath.split('/')[0] === '.' ? paths.project : paths.styles,
result = '';
glob.sync(`${base}/${filePath}`).forEach(file => {
ignore.push(file);
result += fs.readFileSync(file, 'utf-8');
});
return result;
}
/**
* Process CSS into output
*
* @param {string} css
* @param {string} destination
*/
function processCSS(css, destination) {
postcss(plugins)
.process(css, {
syntax: syntax
})
.then(result => {
fs.writeFile(destination, result.css, err => {
if (err) {
console.log(err);
}
});
})
.catch(err => {
console.log(err);
});
}
/**
* Start of process
*/
// Make sure output directories exist
fs.mkdirsSync(paths.output.styles);
// Process compile blocks
let files = Object.keys(compile);
for (let i = 0; i < files.length; i++) {
let result = '',
block = compile[files[i]];
// Not sure how to get around using sync methods to ensure
// compilation order as designated by array compile blocks
if (Array.isArray(block)) {
block.forEach(filePath => {
// Concatenate files together
result += getCSS(filePath);
});
} else {
result += getCSS(block);
}
processCSS(result, `${paths.output.styles}/${files[i]}`);
}
// Main output file
result = '';
// Add reset and base styling
result += fs.readFileSync(paths.weeCore + '/styles/reset.pcss', 'utf-8');
result += fs.readFileSync(__dirname + '/temp/responsive.pcss', 'utf-8');
// Add features
if (features.buttons) {
result += fs.readFileSync(paths.weeCore + '/styles/components/buttons.pcss', 'utf-8');
}
if (features.code) {
result += fs.readFileSync(paths.weeCore + '/styles/components/code.pcss', 'utf-8');
}
if (features.forms) {
result += fs.readFileSync(paths.weeCore + '/styles/components/forms.pcss', 'utf-8');
}
if (features.tables) {
result += fs.readFileSync(paths.weeCore + '/styles/components/tables.pcss', 'utf-8');
}
if (features.print) {
// Add print files
result += `@media print {
${fs.readFileSync(paths.weeCore + '/styles/print.pcss')}
${getCSS('print.pcss')}
}`;
}
// Add class helpers
result += fs.readFileSync(paths.weeCore + '/styles/components/helpers.pcss', 'utf-8');
// Add breakpoint files
for (let breakpoint in breakpoints) {
let file = `${paths.styles}/breakpoints/${convertCamelToDash(breakpoint)}.pcss`;
fs.ensureFileSync(file);
ignore.push(file);
if (breakpoints[breakpoint]) {
result += `@${breakpoint} { ${fs.readFileSync(file, 'utf-8')} }`;
} else {
console.log(chalk.bgRed(`Unregistered breakpoint: ${name}`));
console.log('Check breakpoint files against registered breakpoints in wee.json');
}
}
// Add component files
glob.sync(paths.components + '/**/*.{pcss,css}').forEach(file => {
result += fs.readFileSync(file, 'utf-8');
});
// Add all build files
config.style.build.forEach(pattern => {
result += getCSS(pattern);
});
// Concatenate all other files
glob.sync(paths.styles + '**/*.{pcss,css}', {
ignore: ignore
}).forEach(file => {
result += fs.readFileSync(file, 'utf-8');
});
// Process main style file
processCSS(result, paths.output.styles + '/style.min.css'); | JavaScript | 0 | @@ -4069,16 +4069,57 @@
pcss%60;%0A%0A
+%09// Create file if not already generated%0A
%09fs.ensu
|
697249002c0ab1e4f5525ec586ac6cc56414dba2 | Update release script to skip changelog generator | build/release.js | build/release.js | /*jshint node:true */
module.exports = function( Release ) {
function today() {
return new Date().toISOString().replace(/T.+/, "");
}
// also add version property to this
Release._jsonFiles.push( "validation.jquery.json" );
Release.define({
issueTracker: "github",
changelogShell: function() {
return Release.newVersion + " / " + today() + "\n==================\n\n";
},
generateArtifacts: function( done ) {
Release.exec( "grunt release", "Grunt command failed" );
done([
"dist/additional-methods.js",
"dist/additional-methods.min.js",
"dist/jquery.validate.js",
"dist/jquery.validate.min.js"
]);
},
// disable CDN publishing
cdnPublish: false,
// disable authors check
_checkAuthorsTxt: function() {}
});
};
| JavaScript | 0 | @@ -1,8 +1,300 @@
+/* Release checklist%0A- Run %60git changelog%60 and edit to match previous output (this should make use of jquey-release instead)%0A- pull latest https://github.com/jquery/jquery-release%0A- run%0A%09node release.js --remote=jzaefferer/jquery-validation%0A- Wait a while, verify and confirm each step%0A-%0A*/%0A%0A
/*jshint
@@ -666,16 +666,53 @@
%22;%0A%09%7D,%0A%0A
+%09_generateChangelog: function() %7B%7D,%0A%0A
%09generat
|
9ca85c48435b5be2229a0868e935c6ca590a6d6d | Make sure es6 modules (like koa-router) get transpiled; re-add uglify | buildTasks/js.js | buildTasks/js.js | // take js file
// watch and rebuild it
var gulp = require('gulp');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var streamify = require('gulp-streamify');
var rev = require('gulp-rev');
var rename = require('gulp-rename');
var buffer = require('gulp-buffer');
var clean = require('gulp-rimraf');
var concat = require('gulp-concat');
var source = require('vinyl-source-stream');
var streamqueue = require('streamqueue');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var exorcist = require('exorcist');
module.exports = function buildJS(gulp, buildjs) {
function compile(watch) {
gutil.log('Starting browserify');
var entryFile = './assets/js/client.es6.js';
var bundler = browserify({
cache: {},
packageCache: {},
//fullPaths: true,
debug: true,
extensions: ['.js', '.es6.js', '.jsx'],
});
if (watch) {
bundler = watchify(bundler);
}
// Add in a few common dependencies so we don't end up browserifying
// multiple versions in dev, because `npm link` behaves really oddly at
// times
bundler
.require('moment')
.require('q')
.require('react')
.require('jquery')
.require('reddit-text-js')
//.require('snoode')
.require('superagent')
.require('./lib/snooboots/dist/js/bootstrap.js', {
expose: 'bootstrap',
depends: {
'jquery': 'jQuery'
}
});
bundler.add(entryFile);
bundler
.transform(babelify.configure({
ignore: false,
only: /.+(?:(?:\.es6\.js)|(?:.jsx))$/,
extensions: ['.js', '.es6.js', '.jsx' ],
sourceMap: true,
}), {
global: true,
});
var rebundle = function () {
var stream = bundler.bundle();
stream.on('error', function (err) { console.error(err.toString()) });
gulp.src(buildjs + '/client*.js')
.pipe(clean({force: true}));
var shims = streamqueue({ objectMode: true });
shims.queue(gulp.src('public/js/es5-shims.js'));
shims.queue(gulp.src('node_modules/babel/browser-polyfill.js'));
shims.done()
.pipe(concat('shims.js'))
.pipe(gulp.dest(buildjs));
stream
.pipe(exorcist(buildjs + '/client.js.map'))
.pipe(source(entryFile))
.pipe(rename('client.js'))
.pipe(gulp.dest(buildjs))
//.pipe(streamify(uglify()))
.pipe(rename('client.min.js'))
.pipe(buffer())
.pipe(rev())
.pipe(gulp.dest(buildjs))
.pipe(rev.manifest())
.pipe(rename('client-manifest.json'))
.pipe(gulp.dest(buildjs));
}
bundler.on('update', rebundle);
return rebundle();
}
return {
compile: compile,
};
}
| JavaScript | 0 | @@ -1611,16 +1611,19 @@
+///
only: /.
@@ -2443,18 +2443,16 @@
-//
.pipe(st
|
c6600d94e75989ec7251b3390a0a8449588a172a | Update kulikPisecny.child.js | components/animals/kulikPisecny.child.js | components/animals/kulikPisecny.child.js | import React, { Component } from 'react';
import { Text } from 'react-native';
import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';
const IMAGES = [
require('../../images/animals/kulikPisecny/01.jpg'),
require('../../images/animals/kulikPisecny/02.jpg'),
require('../../images/animals/kulikPisecny/03.jpg'),
];
const THUMBNAILS = [
require('../../images/animals/kulikPisecny/01-thumb.jpg'),
require('../../images/animals/kulikPisecny/02-thumb.jpg'),
require('../../images/animals/kulikPisecny/03-thumb.jpg'),
];
var AnimalDetail = React.createClass({
render() {
return (
<AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
<AnimalText>
Ahoj kluci a holky,
</AnimalText>
<AnimalText>
jsme kulíci píseční a do Brna jsme se už jako malí dostali v roce 2014 z německé zoo. Původně ale pocházíme ze severnějších krajů, máme totiž rádi příjemný chládek.
</AnimalText>
<AnimalText>
Vypadáme podobně jako vrabčáci, ty jste už určitě někdy viděli, ale naše peří je hnědé bez tmavších proužků a bříška máme zářivě bílá. Navíc si, stejně jako vlaštovky, každý rok rádi zaletíme na jih do teplých krajin.
</AnimalText>
<InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
<AnimalText>
Jsme starostliví rodiče, a tak jsme si na hladovce, kteří mají spadeno na naše krásná puntíkatá vajíčka, vymysleli fintu. Když se takový hamoun přiblíží k našemu hnízdu, jeden z nás začne předstírat, že ho něco bolí. Když si útočník všimne, že by mohl mít sousto větší než vajíčko, rozběhne se za námi, a když už je dost daleko od našeho hnízdečka, prostě mu frkneme. To je hezká finta, viďte, děti? Na nás si totiž žádný hamoun jen tak nepřijde.
</AnimalText>
<AnimalText>
Kluky a holky od sebe na první pohled nerozeznáte, jen my kluci občas vystavujeme své bílé peří, to když chceme na holky udělat dojem. Ale nakonec si stejně vyberou toho s nejčervenějším zobáčkem, ty se totiž kulíčím slečnám tuze líbí!
</AnimalText>
<InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
<AnimalText>
Ve výběhu nejsme sami, jsou tu s námi jespáci, tenkozobci, a dokonce jeden ústřičník. Máme totiž něco společného – všichni jsme bahňáci. Tak se nám říká, protože máme moc rádi bahnité břehy. Dokonce společně i obědváme, ale nebojte se, jídla je dost a dostane se na všechny. Chovatel nám dává moc dobré granule, ve kterých je všechno, co potřebujeme, abychom byli zdraví, a když je mezi nimi i červík nebo malá krevetka, to je teprve bašta!
</AnimalText>
<AnimalText>
Ale teď už budeme muset běžet, běháme totiž rádi a stát na místě dlouho nevydržíme.
</AnimalText>
</AnimalTemplate>
);
}
});
module.exports = AnimalDetail;
| JavaScript | 0 | @@ -1257,18 +1257,17 @@
prou%C5%BEk%C5%AF
- a
+,
b%C5%99%C3%AD%C5%A1ka
@@ -1282,16 +1282,56 @@
iv%C4%9B b%C3%ADl%C3%A1
+ a na hlav%C4%9B %C4%8Dernob%C3%ADlou kontrastn%C3%AD kresbu
. Nav%C3%ADc
@@ -2260,14 +2260,15 @@
;nej
-%C4%8Derven
+oran%C5%BEov
%C4%9Bj%C5%A1%C3%AD
|
d8d9ed641db5e924f1973b2a7ddb7864be730513 | add onFocus prop and call it when focussing the input field | components/datepicker/DatePickerInput.js | components/datepicker/DatePickerInput.js | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import Icon from '../icon';
import NavigationBar from './NavigationBar';
import WeekDay from './WeekDay';
import { convertModifiersToClassnames } from './utils';
import { IconCalendarSmallOutline, IconWarningBadgedSmallFilled } from '@teamleader/ui-icons';
import { TextSmall } from '../typography';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';
class DatePickerInput extends PureComponent {
state = {
inputHasFocus: false,
selectedDate: null,
};
static getDerivedStateFromProps(props, state) {
if (props.selectedDate !== undefined && props.selectedDate !== state.selectedDate) {
return {
selectedDate: props.selectedDate,
};
}
return null;
}
handleBlur = () => {
this.setState({ inputHasFocus: false }, () => this.props.onBlur && this.props.onBlur());
};
handleFocus = () => {
this.setState({ inputHasFocus: true });
};
handleInputDateChange = date => {
this.setState(
{
selectedDate: date,
},
() => this.props.onChange(date),
);
};
renderDayPickerInput = () => {
const { className, dayPickerProps, disabled, modifiers, readOnly, size, ...others } = this.props;
const { selectedDate } = this.state;
const dayPickerClassNames = cx(theme['date-picker'], theme[`is-${size}`], className);
const propsWithoutBoxProps = omitBoxProps(others);
const restProps = omit(propsWithoutBoxProps, ['helpText', 'onBlur', 'onChange', 'onFocus']);
return (
<DayPickerInput
classNames={theme}
dayPickerProps={{
className: dayPickerClassNames,
classNames: theme,
modifiers: convertModifiersToClassnames(modifiers, theme),
onDayClick: this.handleInputDateChange,
selectedDays: selectedDate,
navbarElement: <NavigationBar size={size} />,
weekdayElement: <WeekDay size={size} />,
...dayPickerProps,
}}
onDayChange={this.handleInputDateChange}
hideOnDayClick={false}
inputProps={{
disabled: disabled || readOnly,
onBlur: this.handleBlur,
onFocus: this.handleFocus,
}}
{...restProps}
/>
);
};
renderIcon = () => {
const { inverse } = this.props;
return (
<Icon
className={theme['input-icon']}
color={inverse ? 'teal' : 'neutral'}
tint={inverse ? 'light' : 'darkest'}
marginHorizontal={2}
>
<IconCalendarSmallOutline />
</Icon>
);
};
renderHelpText = () => {
const { helpText, inverse } = this.props;
if (helpText) {
return (
<TextSmall color={inverse ? 'white' : 'neutral'} marginTop={1} soft>
{helpText}
</TextSmall>
);
}
};
renderValidationMessage = () => {
return (
<Box marginTop={2}>
<IconWarningBadgedSmallFilled className={theme['validation-icon']} />
<TextSmall className={theme['validation-text']} element="span" marginLeft={1}>
{this.props.error}
</TextSmall>
</Box>
);
};
render() {
const { bold, disabled, error, inverse, readOnly, size, ...others } = this.props;
const { inputHasFocus } = this.state;
const boxProps = pickBoxProps(others);
const classNames = cx(theme['date-picker-input'], theme[`is-${size}`], {
[theme['is-bold']]: bold,
[theme['is-disabled']]: disabled,
[theme['is-inverse']]: inverse,
[theme['is-read-only']]: readOnly,
[theme['has-error']]: error,
[theme['has-focus']]: inputHasFocus,
});
return (
<Box className={classNames} {...boxProps}>
<div className={theme['input-wrapper']}>
{this.renderIcon()}
{this.renderDayPickerInput()}
</div>
{error ? this.renderValidationMessage() : this.renderHelpText()}
</Box>
);
}
}
DatePickerInput.propTypes = {
bold: PropTypes.bool,
className: PropTypes.string,
dayPickerProps: PropTypes.object,
disabled: PropTypes.bool,
/** The text string/element to use as error message below the input. */
error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
helpText: PropTypes.string,
inverse: PropTypes.bool,
modifiers: PropTypes.object,
onBlur: PropTypes.func,
onChange: PropTypes.func,
readOnly: PropTypes.bool,
selectedDate: PropTypes.instanceOf(Date),
size: PropTypes.oneOf(['small', 'medium', 'large']),
};
DatePickerInput.defaultProps = {
bold: false,
disabled: false,
inverse: false,
readOnly: false,
size: 'medium',
};
export default DatePickerInput;
| JavaScript | 0 | @@ -1125,16 +1125,66 @@
: true %7D
+, () =%3E this.props.onFocus && this.props.onFocus()
);%0A %7D;%0A
@@ -4604,16 +4604,43 @@
s.func,%0A
+ onFocus: PropTypes.func,%0A
readOn
|
bd536226bae14ee01ce4d347f4352e4513929170 | add DCO check logic | bot.js | bot.js | //
var http = require('http');
var createHandler = require('github-webhook-handler');
var handler = createHandler({ path: '/webhook', secret: 'sekrit' });
var host = (process.env.VCAP_APP_HOST || 'localhost');
var port = (process.env.VCAP_APP_PORT || 7777);
// Start server
http.createServer(function (req, res) {
handler(req, res, function (err) {
res.statusCode = 404
res.end('no such location');
console.log("oops?");
console.log(req.rawHeaders);
});
}).listen(port, host);
handler.on('error', function (err) {
console.error('Error:', err.message);
});
handler.on('pull_request', function (event) {
console.log('Received an %s pull_request event for %s PR #%s',
event.payload.action,
event.payload.repository.name,
event.payload.pull_request.number);
if (event.payload.pull_request.body.search(/Signed-off-by:/) > -1) {
console.log(event.payload.pull_request.body);
}
});
| JavaScript | 0 | @@ -8,24 +8,80 @@
http
- = require('http
+s = require('https');%0Avar http = require('http');%0Avar url = require('url
');%0A
@@ -196,14 +196,20 @@
t: '
-sekrit
+t34B6EKaUgyw
' %7D)
@@ -313,16 +313,1194 @@
7777);%0A
+var dco_not_found = 'Please add a comment with a DCO1.1 Signed-off-by statement in order to allow us to process your Pull Request.';%0Avar doc_found = 'DCO1.1 signed-off. Okay to process this Pull Request.';%0A%0Afunction postComment(address, comment) %7B%0A var tmp = %7B%7D;%0A tmp.body = comment;%0A tmp.in_reply_to = 1;%0A var postData = JSON.stringify(tmp);%0A var path = url.parse(address).pathname;%0A%0A var options = %7B%0A hostname: 'api.github.com',%0A port: 447,%0A path: '/upload',%0A method: 'POST',%0A headers: %7B%0A 'Content-Type': 'application/vnd.github.VERSION.text+json',%0A 'Content-Length': postData.length%0A %7D%0A %7D;%0A options.path = path;%0A%0A var req = https.request(options, function(res) %7B%0A console.log('STATUS: ' + res.statusCode);%0A console.log('HEADERS: ' + JSON.stringify(res.headers));%0A res.setEncoding('utf8');%0A res.on('data', function (chunk) %7B%0A console.log('BODY: ' + chunk);%0A %7D);%0A res.on('end', function() %7B%0A console.log('No more data in response.')%0A %7D)%0A %7D);%0A%0A req.on('error', function(e) %7B%0A console.log('unable to post comment: ' + e.message);%0A %7D);%0A%0A // write data to request body%0A req.write(postData);%0A req.end();%0A%7D
%0A// Star
@@ -2086,16 +2086,25 @@
-off-by:
+.*%3C.*@.*%3E
/) %3E -1)
@@ -2156,16 +2156,227 @@
.body);%0A
+ postComment(event.payload.pull_request.review_comments_url, doc_found);%0A %7D%0A else %7B%0A console.log('no DCO sign-off found');%0A postComment(event.payload.pull_request.review_comments_url, dco_not_found);%0A
%7D%0A%7D);%0A
|
af9307508b43a458bfb4d5e2aa8778d5bb353f93 | change !song emote | commands/radio/song.js | commands/radio/song.js | const roles = require('../../config/roles'),
axios = require('axios');
exports.run = (bot, message, args) => {
function getMetaData(callback) {
axios.get('https://www.bronyradiogermany.com/request-v2/json/v1/nowplaying/stream')
.then((res) => {
return callback(res.data.result);
})
.catch((err) => {
bot.log(err);
return callback(false);
})
}
getMetaData(result => {
let success = true;
if (!result) {
result = {};
if (bot.server.members.has(bot.config.RADIO_BOT)) {
const np = bot.server.members.get(bot.config.RADIO_BOT).user.presence.game;
const npS = np.split(' - ');
if (npS.length == 2) {
result.title = npS[1];
result.artist = npS[0];
} else {
result.title = np;
}
} else {
success = false;
}
}
if (!success) {
return bot.respond(message, 'Aktueller Song konnte nicht abgerufen werden.', true);
}
let songString, searchQuery;
if ('artist' in result) {
songString = `**${result.title}** von **${result.artist}**`;
searchQuery = result.title + ' ' + result.artist;
} else {
songString = result.title;
searchQuery = result.title;
}
let text = `🎶 Derzeit läuft ${songString} im BRG.`;
let info = '';
if ('current_event' in result) {
let preString;
if (result.current_event == 'DJ-Pony Lucy') {
preString = bot.getEmoji('brgLucy') + ' **DJ-Pony Lucy**';
} else if (result.current_event == 'DJ-Pony Mary') {
preString = bot.getEmoji('brgMary') + ' **DJ-Pony Mary**';
} else {
preString = `🔴 **${result.current_event}**`;
}
const listenerString = result.listener == 1 ? 'Zuhörer' : 'Zuhörern';
text += `\n${preString} mit ${result.listener} ${listenerString}.`;
const votes = result.upvotes - result.downvotes;
const votesEmote = votes >= 0 ? '❤' : '💔';
info = `${votes} ${votesEmote}`;
}
bot.youtube.searchVideo(searchQuery, video => {
if (video) {
if (info != '') {
info += ' | ';
}
info += 'Auf YouTube anhören: https://youtu.be/' + video.id.videoId;
}
if (info != '') {
text += '\n\n' + info;
}
bot.respond(message, text, false);
});
})
};
exports.config = {
aliases: ['nowplaying', 'np'],
cooldown: 60,
global_cooldown: true,
skip: roles.moderator
};
exports.help = {
name: 'song',
description: 'Zeigt den aktuell gespielten Track des BRG-Musikbots an.',
usage: ['!np']
}; | JavaScript | 0.000001 | @@ -1706,110 +1706,12 @@
ucy'
-) %7B%0A preString = bot.getEmoji('brgLucy') + ' **DJ-Pony Lucy**';%0A %7D else if (
+ %7C%7C
resu
@@ -1776,16 +1776,19 @@
tring =
+%60$%7B
bot.getE
@@ -1797,39 +1797,46 @@
ji('
-brgMary') + ' **DJ-Pony Mary**'
+dropit')%7D **$%7Bresult.current_event%7D**%60
;%0A
|
89afcd2e568aeced887c1d54189494d5c02f4575 | update data | js/streamgraph.js | js/streamgraph.js |
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category20();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function(d) { return x(d.yearCol); })
.y0(function(d) { return y(d.y0); })
.y1(function(d) { return y(d.y0 + d.y); });
var stack = d3.layout.stack()
.values(function(d) { return d.values; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv('Words_allyears_26oct.csv', function(error, data){
var list = ['war', 'bomb', 'blast'];
var data = $.map(data, function(element){
return ($.inArray(element.wordCol,list)>-1?element:null)
});
data.forEach(function(d){
d.countCol = +d.countCol;
d.yearCol = +d.yearCol;
});
console.log(data);
function complete(x, key){
for (i=0; i<key.length; i++){
console.log(key[i]);
tempdata = x.filter(function(d){ return d.wordCol == key[i]; });
console.log(tempdata);
yearsPresent = []
years = [];
for (i=1955; i<2010; i++){
years.push(i)
for (j=0; j<tempdata.length; j++){
if (tempdata[j].yearCol === i){
yearsPresent.push(i);
}
}
}
for (i=0; i<years.length; i++){
if (yearsPresent.indexOf(years[i]) < 0){
dict = {}
dict['countCol'] = 0;
dict['wordCol'] = tempdata[0].wordCol;
dict['yearCol'] = years[i];
data.push(dict);
}
}
}
};
complete(data, list);
/*
for (i=0; i<list.length; i++){
complete(data, list[i]);
};
complete(data, "war");
complete(data, "blast");
complete(data, "bomb");
*/
console.log(data);
/*
data = d3.nest()
.key(function(d){ return d.wordCol; })
.entries(data);
*/
})
| JavaScript | 0.000001 | @@ -1925,24 +1925,46 @@
%7D%0A %7D%0A
+ console.log(x);%0A
%7D%0A %0A
|
c0878b26fb97e1cf6307f56633452f8b5f19e438 | Add fade out of status msg | js/taskActions.js | js/taskActions.js | $(document).on("click", "#addTaskSubmit", function (event) {
// Add a task to the list
// prevent default action of form submit
event.preventDefault();
var taskName = $('#name').val();
var taskExpirationDate = $('#date-input').val();
// validate user input
var isValid = true;
var dateRegexEn = /^\d{4}(.|-|\/)\d{2}(.|-|\/)\d{2}$/;
// reset background color
$('#name').css('background-color', '');
$('#date-input').css('background-color', '');
if (taskName === "") {
$('#name').css('background-color', '#f2dede');
isValid = false;
}
if (!taskExpirationDate.match(dateRegexEn)) {
$('#date-input').css('background-color', '#f2dede');
isValid = false;
}
// send form data to server
if (isValid) {
data = {
'taskName': taskName,
'taskDate': taskExpirationDate
};
$.post('saveTask.php', data, function(data) {
// add success msg
$("#resultMsg").html('<p class="bg-success">'+data+'</p>');
// reset input fields
$('#name').val('');
$('#date-input').val('');
// reload all Tasks
updateTaskTable();
}).
fail(function(error) {
$('#resultMsg').html('<p class="bg-danger">'+error.statusText+'</p>');
});
}
});
$(document).on("click", "#updateTaskSubmit", function (event) {
// Update completed tasks
// prevent default action of form submit
event.preventDefault();
// update completed tasks
var data = $('#updateTasks').serialize();
$.post('updateTasks.php', data, function(data) {
// add success msg
$("#resultMsgTasks").html('<p class="bg-success">'+data+'</p>');
updateTaskTable();
})
.fail(function(error) {
$('#resultMsgTasks').html('<p class="bg-danger">'+error.statusText+'</p>');
});
});
function getTasks() {
// get all tasks from the database
$.get('getTasks.php', function(data) {
for(var i = 0; i < data.length; i++) {
var row = $('<tr>');
var isChecked = (Boolean(+data[i].completed)) ? 'checked' : '';
var checkbox = '<input type="checkbox" name="completed[]" value="' + data[i].taskId + '" ' + isChecked + '>';
row.append($('<td>').html(checkbox));
row.append($('<td>').html(data[i].taskName));
row.append($('<td>').html(data[i].taskExpirationDate));
$('#tasks').append(row);
}
});
}
function updateTaskTable() {
// updates the task table
$('#tasks > tbody').empty();
getTasks();
} | JavaScript | 0.000001 | @@ -937,16 +937,41 @@
+'%3C/p%3E')
+.delay(3000).fadeOut(400)
;%0A%0A%09%09%09//
@@ -1187,24 +1187,49 @@
Text+'%3C/p%3E')
+.delay(3000).fadeOut(400)
;%0A%09%09%7D);%0A%09%7D%0A%7D
@@ -1598,16 +1598,41 @@
+'%3C/p%3E')
+.delay(3000).fadeOut(400)
;%0A%09%09upda
@@ -1751,16 +1751,41 @@
+'%3C/p%3E')
+.delay(3000).fadeOut(400)
;%0A%09%7D);%0A%7D
|
f56a3e98f16dad1c94f5f33363e013eaa810eba6 | fix docs bad use of private methods to change title of our tooltips | site/static/docs/4.3/assets/js/src/application.js | site/static/docs/4.3/assets/js/src/application.js | // NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
/*!
* JavaScript for Bootstrap's docs (https://getbootstrap.com/)
* Copyright 2011-2019 The Bootstrap Authors
* Copyright 2011-2019 Twitter, Inc.
* Licensed under the Creative Commons Attribution 3.0 Unported License.
* For details, see https://creativecommons.org/licenses/by/3.0/.
*/
/* global ClipboardJS: false, anchors: false, bootstrap: false, bsCustomFileInput: false */
(function () {
'use strict'
function makeArray(list) {
return [].slice.call(list)
}
(function () {
var checkbox = document.getElementById('flexCheckIndeterminate')
if (!checkbox) {
return
}
checkbox.indeterminate = true
})()
makeArray(document.querySelectorAll('.js-sidenav-group'))
.forEach(function (sidenavGroup) {
var groupHasLinks = Boolean(sidenavGroup.querySelector('li'))
var groupLink = sidenavGroup.querySelector('a')
if (groupHasLinks) {
groupLink.addEventListener('click', function (e) {
e.preventDefault()
e.target.parentNode.classList.toggle('active')
}, true)
}
})
// Tooltip and popover demos
makeArray(document.querySelectorAll('.tooltip-demo'))
.forEach(function (tooltip) {
new bootstrap.Tooltip(tooltip, {
selector: '[data-toggle="tooltip"]',
template: '<div class="tooltip" role="tooltip">' +
'<div class="tooltip-inner"></div></div>',
container: 'body'
})
})
makeArray(document.querySelectorAll('[data-toggle="popover"]'))
.forEach(function (popover) {
new bootstrap.Popover(popover, {
template: '<div class="popover" role="tooltip">' +
'<h3 class="popover-header"></h3>' +
'<div class="popover-body"></div></div>'
})
})
makeArray(document.querySelectorAll('.toast'))
.forEach(function (toastNode) {
var toast = new bootstrap.Toast(toastNode, {
autohide: false
})
toast.show()
})
// Demos within modals
makeArray(document.querySelectorAll('.tooltip-test'))
.forEach(function (tooltip) {
new bootstrap.Tooltip(tooltip)
})
makeArray(document.querySelectorAll('.popover-test'))
.forEach(function (popover) {
new bootstrap.Popover(popover)
})
// Indeterminate checkbox example
makeArray(document.querySelectorAll('.bd-example-indeterminate [type="checkbox"]'))
.forEach(function (checkbox) {
checkbox.indeterminate = true
})
// Disable empty links in docs examples
makeArray(document.querySelectorAll('.bd-content [href="#"]'))
.forEach(function (link) {
link.addEventListener('click', function (e) {
e.preventDefault()
})
})
// Modal relatedTarget demo
var exampleModal = document.getElementById('exampleModal')
if (exampleModal) {
exampleModal.addEventListener('show.bs.modal', function (event) {
var button = event.relatedTarget // Button that triggered the modal
var recipient = button.getAttribute('data-whatever') // Extract info from data-* attributes
// Update the modal's content.
var modalTitle = exampleModal.querySelector('.modal-title')
var modalBodyInput = exampleModal.querySelector('.modal-body input')
modalTitle.innerHTML = 'New message to ' + recipient
modalBodyInput.value = recipient
})
}
// Activate animated progress bar
var btnToggleAnimatedProgress = document.getElementById('btnToggleAnimatedProgress')
if (btnToggleAnimatedProgress) {
btnToggleAnimatedProgress.addEventListener('click', function () {
btnToggleAnimatedProgress.parentNode
.querySelector('.progress-bar-striped')
.classList
.toggle('progress-bar-animated')
})
}
// Insert copy to clipboard button before .highlight
var btnHtml = '<div class="bd-clipboard"><button type="button" class="btn-clipboard" title="Copy to clipboard">Copy</button></div>'
makeArray(document.querySelectorAll('figure.highlight, div.highlight'))
.forEach(function (element) {
element.insertAdjacentHTML('beforebegin', btnHtml)
})
makeArray(document.querySelectorAll('.btn-clipboard'))
.forEach(function (btn) {
var tooltipBtn = new bootstrap.Tooltip(btn)
btn.addEventListener('mouseleave', function () {
// Explicitly hide tooltip, since after clicking it remains
// focused (as it's a button), so tooltip would otherwise
// remain visible until focus is moved away
tooltipBtn.hide()
})
})
var clipboard = new ClipboardJS('.btn-clipboard', {
target: function (trigger) {
return trigger.parentNode.nextElementSibling
}
})
clipboard.on('success', function (e) {
var tooltipBtn = bootstrap.Tooltip._getInstance(e.trigger)
e.trigger.setAttribute('title', 'Copied!')
tooltipBtn._fixTitle()
tooltipBtn.show()
e.trigger.setAttribute('title', 'Copy to clipboard')
tooltipBtn._fixTitle()
e.clearSelection()
})
clipboard.on('error', function (e) {
var modifierKey = /Mac/i.test(navigator.userAgent) ? '\u2318' : 'Ctrl-'
var fallbackMsg = 'Press ' + modifierKey + 'C to copy'
var tooltipBtn = bootstrap.Tooltip._getInstance(e.trigger)
e.trigger.setAttribute('title', fallbackMsg)
tooltipBtn._fixTitle()
tooltipBtn.show()
e.trigger.setAttribute('title', 'Copy to clipboard')
tooltipBtn._fixTitle()
})
anchors.options = {
icon: '#'
}
anchors.add('.bd-content > h2, .bd-content > h3, .bd-content > h4, .bd-content > h5')
// Wrap inner
makeArray(document.querySelectorAll('.bd-content > h2, .bd-content > h3, .bd-content > h4, .bd-content > h5'))
.forEach(function (hEl) {
hEl.innerHTML = '<span class="bd-content-title">' + hEl.innerHTML + '</span>'
})
bsCustomFileInput.init()
})()
| JavaScript | 0 | @@ -4896,32 +4896,46 @@
r.setAttribute('
+data-original-
title', 'Copied!
@@ -4941,35 +4941,8 @@
!')%0A
- tooltipBtn._fixTitle()%0A
@@ -4980,32 +4980,46 @@
r.setAttribute('
+data-original-
title', 'Copy to
@@ -5035,35 +5035,8 @@
d')%0A
- tooltipBtn._fixTitle()%0A
|
4d6adcfa326f923b7c707b14f3aaf1fcf9c8188c | Fix repl.js platformVersion must be a string for appium (#5514) | packages/wdio-cli/src/commands/repl.js | packages/wdio-cli/src/commands/repl.js | import pickBy from 'lodash.pickby'
import { remote } from 'webdriverio'
import { hasWdioSyncSupport } from '@wdio/utils'
import { getCapabilities } from '../utils'
import { CLI_EPILOGUE } from '../constants'
const IGNORED_ARGS = [
'bail', 'framework', 'reporters', 'suite', 'spec', 'exclude',
'mochaOpts', 'jasmineNodeOpts', 'cucumberOpts'
]
export const command = 'repl <option> [capabilities]'
export const desc = 'Run WebDriver session in command line'
export const cmdArgs = {
platformVersion: {
alias: 'v',
desc: 'Version of OS for mobile devices',
type: 'number',
},
deviceName: {
alias: 'd',
desc: 'Device name for mobile devices',
type: 'string',
},
udid: {
alias: 'u',
desc: 'UDID of real mobile devices',
type: 'string',
}
}
export const builder = (yargs) => {
return yargs
.options(pickBy(cmdArgs, (_, key) => !IGNORED_ARGS.includes(key)))
.example('$0 repl firefox --path /', 'Run repl locally')
.example('$0 repl chrome -u <SAUCE_USERNAME> -k <SAUCE_ACCESS_KEY>', 'Run repl in Sauce Labs cloud')
.example('$0 repl android', 'Run repl browser on launched Android device')
.example('$0 repl "./path/to/your_app.app"', 'Run repl native app on iOS simulator')
.example('$0 repl ios -v 11.3 -d "iPhone 7" -u 123432abc', 'Run repl browser on iOS device with capabilities')
.epilogue(CLI_EPILOGUE)
.help()
}
export const handler = async (argv) => {
const caps = getCapabilities(argv)
/**
* runner option required to wrap commands within Fibers context
*/
const execMode = hasWdioSyncSupport ? { runner: 'repl' } : {}
const client = await remote({ ...argv, ...caps, ...execMode })
global.$ = ::client.$
global.$$ = ::client.$$
global.browser = client
await client.debug()
return client.deleteSession()
}
| JavaScript | 0 | @@ -597,14 +597,14 @@
e: '
-number
+string
',%0A
|
2827ec0d4e1111b5ed2cd2ca9098deb8f06475a1 | Add ArrayArray typedef | tools/docs/jsdoc/typedefs/arrays.js | tools/docs/jsdoc/typedefs/arrays.js | /**
* A typed array.
*
* @typedef {(Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array)} TypedArray
*
* @see [TypedArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray}
* @see [Int8Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array}
* @see [Uint8Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array}
* @see [Uint8ClampedArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray}
* @see [Int16Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array}
* @see [Uint16Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array}
* @see [Int32Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array}
* @see [Uint32Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array}
* @see [Float32Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array}
* @see [Float64Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array}
*/
/**
* An integer typed array.
*
* @typedef {(Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array)} IntegerTypedArray
*
* @see [TypedArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray}
* @see [Int8Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array}
* @see [Uint8Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array}
* @see [Uint8ClampedArray]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray}
* @see [Int16Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array}
* @see [Uint16Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array}
* @see [Int32Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array}
* @see [Uint32Array]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array}
*/
/**
* A numeric array.
*
* @typedef {(Array<number>|TypedArray)} NumericArray
*/
/**
* An array containing only number primitives.
*
* @typedef {Array<number>} NumberArray
*/
/**
* A numeric array containing only integer values.
*
* @typedef {(Array<number>|IntegerTypedArray)} IntegerArray
*/
/**
* An integer array containing only positive integer values.
*
* @typedef {IntegerArray)} PositiveIntegerArray
*/
/**
* An integer array containing only negative integer values.
*
* @typedef {IntegerArray)} NegativeIntegerArray
*/
/**
* An integer array containing only non-positive integer values.
*
* @typedef {IntegerArray)} NonPositiveIntegerArray
*/
/**
* An integer array containing only nonnegative integer values.
*
* @typedef {IntegerArray)} NonNegativeIntegerArray
*/
/**
* An array containing only string primitives.
*
* @typedef {Array<string>} StringArray
*/
/**
* An array containing only boolean primitives.
*
* @typedef {Array<boolean>} BooleanArray
*/
/**
* An array containing only plain objects.
*
* @typedef {Array<Object>} ObjectArray
*/
/**
* An empty array.
*
* @typedef {Array} EmptyArray
*/
| JavaScript | 0.000182 | @@ -3555,32 +3555,120 @@
ObjectArray%0A*/%0A%0A
+/**%0A* An array containing only other arrays.%0A*%0A* @typedef %7BArray%3CArray%3E%7D ArrayArray%0A*/%0A%0A
/**%0A* An empty a
|
099058b8b61fa805149b80e878d25f1207f1509d | use prefix query insted of matches | src/ui/components/containers/ChatSuggestionsContainer.js | src/ui/components/containers/ChatSuggestionsContainer.js | /* @flow */
import React, { Component, PropTypes } from 'react';
import shallowEqual from 'shallowequal';
import Connect from '../../../modules/store/Connect';
import ChatSuggestions from '../views/ChatSuggestions';
type Props = {
user: string;
prefix: string;
}
type State = {
prefix: string;
}
export default class ChatSuggestionsContainer extends Component<void, Props, State> {
static propTypes = {
user: PropTypes.string,
};
state: State = {
prefix: '',
};
componentWillReceiveProps(nextProps: Props) {
if (typeof nextProps.prefix === 'string') {
this.setState({
prefix: nextProps.prefix.trim(),
});
}
}
shouldComponentUpdate(nextProps: Props): boolean {
return !shallowEqual(this.props, nextProps);
}
render() {
const {
prefix,
} = this.state;
const {
user,
} = this.props;
if (!prefix) {
return null;
}
return (
<Connect
mapSubscriptionToProps={{
data: {
key: {
slice: {
type: 'user',
filter: {
id_mts: `${prefix}%`,
},
order: 'updateTime',
},
range: {
start: -Infinity,
before: 0,
after: 5,
},
},
transform: results => results.filter(item => item.type !== 'loading' && item.id !== user),
},
}}
passProps={this.props}
component={ChatSuggestions}
/>
);
}
}
| JavaScript | 0.000001 | @@ -1017,25 +1017,20 @@
%09id_
-mts: %60$%7B
+pref:
prefix
-%7D%25%60
,%0A%09%09
|
b87595f7dbfeb7840fa0770e3c9f18808eb390f2 | Update Example | example/src/routes.js | example/src/routes.js | import path from 'path';
import express from 'express';
import React from 'react';
import { Router, Route, IndexRoute, Link, browserHistory } from 'react-router';
import { ExpressRoute } from 'express-react-router';
/*--------------------------------------------------------------------------------------------------------------------*/
// --- React Router Components ---
/*--------------------------------------------------------------------------------------------------------------------*/
const PageWrapper = React.createClass({
render: function() {
return (
<div>
<h4>{this.props.title} - {this.props.url}</h4>
<ul>
<li><Link to="/">Page One</Link></li>
<li>
<Link to="/pageTwo">Page Two</Link>
<ul>
<li><Link to="/pageTwo/subPageOne">Subpage One</Link></li>
<li><Link to="/pageTwo/subPageTwo">Subpage Two</Link></li>
<li><a href="/pageTwo/identicon.png">indenticon</a></li>
</ul>
</li>
<li><a href="/func">Func</a></li>
<li><a href="/router">Router</a></li>
<li><a href="/errorFunc">Error Func</a></li>
<li><a href="/errorRouter">Error Router</a></li>
</ul>
<div>{this.props.children}</div>
</div>
);
}
});
const PageOne = React.createClass({ render: function() { return <div>PageOne</div>; } });
const PageTwo = React.createClass({
render: function() {
return (
<div>
<div>PageTwo</div>
<div>{this.props.children}</div>
</div>
);
}
});
const SubPageOne = React.createClass({ render: function() { return <div>SubPageOne</div>; } });
const SubPageTwo = React.createClass({ render: function() { return <div>SubPageTwo</div>; } });
const NotFound = React.createClass({ render: function() { return <div>404</div>; } });
const NotFoundPageTwo = React.createClass({ render: function() { return <div>Page Two 404</div>; } });
/*--------------------------------------------------------------------------------------------------------------------*/
// --- Routers / Funcs / Files ---
/*--------------------------------------------------------------------------------------------------------------------*/
let func, router, errFunc, errRouter, appSrc, indenticonSrc, faviconSrc, filesSrc;
if(typeof window === 'undefined') { // Preform only on the server
func = function(req, res) {
res.send({ test: 'response' });
};
router = express.Router();
router.use(func);
errFunc = function(req, res) {
throw new Error('Test Error');
};
errRouter = express.Router();
errRouter.use(errFunc);
appSrc = path.join(__dirname, './app.js');
indenticonSrc = path.join(__dirname, '../public/identicon.png');
faviconSrc = path.join(__dirname, '../public/favicon.ico');
filesSrc = path.join(__dirname, '../public/');
}
/*--------------------------------------------------------------------------------------------------------------------*/
// --- Create Route ---
/*--------------------------------------------------------------------------------------------------------------------*/
export default (
<Router history={browserHistory} >
<Route path="/" component={PageWrapper}>
<IndexRoute component={PageOne} />
<Route path="pageTwo" component={PageTwo}>
<Route path="subPageOne" component={SubPageOne} />
<Route path="subPageTwo" component={SubPageTwo} />
<Route path="*" component={NotFoundPageTwo} />
<ExpressRoute path="identicon.png" src={indenticonSrc} />
</Route>
<Route path="*" component={NotFound} />
<ExpressRoute path="favicon.ico" src={faviconSrc} />
<ExpressRoute path="app.js" src={appSrc} />
<ExpressRoute path="files" src={filesSrc} />
<ExpressRoute path="func" use={func} />
<ExpressRoute path="router" use={router} />
<ExpressRoute path="errorFunc" use={errFunc} />
<ExpressRoute path="errorRouter" use={errRouter} />
</Route>
</Router>
);
| JavaScript | 0 | @@ -159,61 +159,8 @@
er';
-%0Aimport %7B ExpressRoute %7D from 'express-react-router';
%0A%0A/*
@@ -3237,32 +3237,24 @@
-
component=%7BP
@@ -3276,30 +3276,24 @@
%3CRoute
-
path=%22pageTw
@@ -3294,18 +3294,16 @@
pageTwo%22
-
comp
@@ -3329,38 +3329,32 @@
%3CRoute
-
path=%22subPageOne
@@ -3399,30 +3399,24 @@
%3CRoute
-
-
path=%22subPag
@@ -3461,38 +3461,32 @@
%3CRoute
-
-
path=%22*%22
@@ -3527,39 +3527,32 @@
/%3E%0A %3C
-Express
Route
path=%22identi
@@ -3535,24 +3535,25 @@
%3CRoute
+
path=%22identi
@@ -3615,23 +3615,16 @@
Route
-
path=%22*%22
@@ -3658,39 +3658,32 @@
ound%7D /%3E%0A %3C
-Express
Route path=%22fa
@@ -3713,39 +3713,32 @@
nSrc%7D /%3E%0A %3C
-Express
Route path=%22ap
@@ -3764,39 +3764,32 @@
pSrc%7D /%3E%0A %3C
-Express
Route path=%22fi
@@ -3817,39 +3817,32 @@
sSrc%7D /%3E%0A %3C
-Express
Route path=%22fu
@@ -3866,39 +3866,32 @@
func%7D /%3E%0A %3C
-Express
Route path=%22ro
@@ -3917,39 +3917,32 @@
uter%7D /%3E%0A %3C
-Express
Route path=%22er
@@ -3981,15 +3981,8 @@
%3C
-Express
Rout
|
65326a10745b64c6518868a83c5ce0aa7ff8097b | Add touch input to puzzle rendering function | prelim/renderPuzzle.js | prelim/renderPuzzle.js | function renderPuzzle( levelNumber, canvas, width, height ) {
document.body.appendChild(canvas);
canvas.width = width;
canvas.height = height;
canvas.style.backgroundColor = '#333333';
canvas.id = 'gameView';
var levels = new Levels( new XSPRNG(1), 70, new MonochromaticPaletteBuilder());
var level = levels.get(levelNumber);
var vc = new ViewController( level, canvas, 2, 'white' );
vc.draw();
var inputController = new InputController( vc );
var keyboardInput = new KeyboardInput(inputController);
keyboardInput.listen();
}
| JavaScript | 0 | @@ -553,24 +553,112 @@
r);%0A
-keyboard
+var touchInput = new TouchInput(inputController, canvas);%0A%0A keyboardInput.listen();%0A touch
Input.li
|
9ff10250a934a151f1eb95ca72312f9b69791be4 | fix - playlist grid would not fill the width of the whole sidebar in android | mobile/app/shared_components/songs_grid/rows.js | mobile/app/shared_components/songs_grid/rows.js | import loggerCreator from "../../utils/logger";
//noinspection JSUnresolvedVariable
var moduleLogger = loggerCreator("SongsGrid");
import React, { Component } from "react";
import { Image, StyleSheet, Text, View, Platform } from "react-native";
import { observer } from "mobx-react";
import moment from "moment";
import NormalText from "app/shared_components/text/normal_text";
import SmallText from "app/shared_components/text/small_text";
import playImage from "app/images/play.png";
import Rating from "app/shared_components/rating";
import { colors } from "app/styles/styles";
const MIN_CELL_WIDTH = 110;
const styles = StyleSheet.create({
header: {
flexDirection: "row",
flex: 1,
marginBottom: 5,
},
nameCell: {
flexGrow: 9,
flexBasis: 0,
},
headerText: {
fontWeight: "bold",
},
gridCell: {
flexGrow: 1,
minWidth: MIN_CELL_WIDTH,
flexDirection: "row",
alignItems: "center",
},
row: {
flexDirection: "row",
flex: 1,
padding: 5,
position: "relative",
},
playImage: {
width: 15,
height: 27,
resizeMode: "contain",
},
nameContainer: {
marginLeft: 5,
flexShrink: 1,
},
artistText: {
marginTop: 5,
fontWeight: "bold",
},
selectedRow: {
position: "absolute",
top: 0,
bottom: 0,
left: 0,
right: 0,
backgroundColor: colors.CYAN_DARK,
},
});
export class HeaderRow extends Component {
render() {
return (
<View style={styles.header}>
{[
<NormalText key="name" style={[styles.gridCell, styles.nameCell, styles.headerText]}>
Name
</NormalText>,
<NormalText key="rating" style={[styles.gridCell, styles.headerText]}>
Rating
</NormalText>,
<NormalText key="lastPlayed" style={[styles.gridCell, styles.headerText]}>
Last played
</NormalText>,
<NormalText key="playCount" style={[styles.gridCell, styles.headerText]}>
Play count
</NormalText>,
].slice(0, this.props.visibleColumns)}
</View>
);
}
}
HeaderRow.propTypes = {
visibleColumns: React.PropTypes.number.isRequired,
};
@observer
export class SongRow extends Component {
render() {
return (
<View style={styles.row}>
{this.props.isHighlighted ? <View style={styles.selectedRow} /> : null}
{[
<View key="name" style={[styles.gridCell, styles.nameCell]}>
<Image source={playImage} style={styles.playImage} />
<View style={styles.nameContainer}>
<SmallText>
{this.props.song.title}
</SmallText>
<SmallText style={styles.artistText}>
{this.props.song.artist}
</SmallText>
</View>
</View>,
<View key="rating" style={[styles.gridCell]}>
<Rating song={this.props.song} starSize={18} starMargin={2} canChangeRating={false} />
</View>,
<View key="lastPlayed" style={[styles.gridCell]}>
<SmallText>
{moment.unix(this.props.song.lastplayed).fromNow()}
</SmallText>
</View>,
<View key="playCount" style={[styles.gridCell]}>
<SmallText>
{this.props.song.playcount}
</SmallText>
</View>,
].slice(0, this.props.visibleColumns)}
</View>
);
}
}
SongRow.propTypes = {
visibleColumns: React.PropTypes.number.isRequired,
song: React.PropTypes.object.isRequired,
isHighlighted: React.PropTypes.bool.isRequired,
};
| JavaScript | 0 | @@ -601,17 +601,17 @@
IDTH = 1
-1
+0
0;%0A%0Acons
@@ -753,26 +753,8 @@
9,%0A
- flexBasis: 0,%0A
%7D,
@@ -838,16 +838,17 @@
-minWidth
+flexBasis
: MI
|
dd17349cedba80f8826b01cf218ffdc5b0ab69b6 | Order Status Histories Validator | src/sales/order-status-validator.js | src/sales/order-status-validator.js | require("should");
module.exports = function (data) {
data.should.not.equal(null);
data.should.instanceOf(Object);
data.should.have.property('salesContractNo');
data.code.should.instanceOf(String);
data.should.have.property('deliveryDateCorrection');
data.deliveryDateCorrection.should.instanceOf(Date);
data.should.have.property('reason');
data.name.should.instanceOf(String);
}; | JavaScript | 0.000001 | @@ -181,12 +181,23 @@
ata.
-code
+salesContractNo
.sho
|
610edae1109edce6c7657732736c3f012fda39da | fix the compare problem on facet | store/search/store.js | store/search/store.js | //Dependencies.
var CoreStore = require('../CoreStore');
var assign = require('object-assign');
var AppDispatcher = require('../../dispatcher');
var keys = require('lodash/object/keys');
var intersection = require('lodash/array/intersection');
var Immutable = require('immutable');
var isArray = require('lodash/lang/isArray');
/**
* Default configuration of the search.
* @type {Object}
*/
/*var defaultSearchConfig = {
facet:"facet",
list:"list",
pageInfos: "pageInfos"
};*/
class SearchStore extends CoreStore {
constructor(conf){
var config = assign({}, {definitionPath: "search"}, conf);
super(config);
}
get(){
return this.data.toJS();
}
/**
* Update all the data from the search.
* @return {}
*/
update(newData){
var previousData = this.data.toJS();
var processedData = assign({},previousData,newData);
if(this._isSameSearchContext(previousData, newData)){
processedData.list = previousData.list.concat(newData.list);
}
//add calculated fields on data
if(processedData.pageInfos.totalRecords && processedData.pageInfos.perPage && processedData.pageInfos.perPage!=0){
processedData.pageInfos.totalPages = Math.ceil(processedData.pageInfos.totalRecords / processedData.pageInfos.perPage);
}
var data = {};
for(var key in processedData){
data[key] = Immutable[isArray(processedData[key]) ? "List" : "Map"](processedData[key]);
}
this.data = Immutable.Map(data);
this.emit('search:change');
}
/**
* Check if the search need to concat the nexData with the previous data (infinite scrol case).
*/
_isSameSearchContext(previousData, newData) {
var isSameSearchContext = false;
if(previousData.searchContext) {
var isSameScope = previousData.searchContext.scope === newData.searchContext.scope;
var isSameQuery = previousData.searchContext.query === newData.searchContext.query;
isSameSearchContext = isSameScope && isSameQuery;
}
return isSameSearchContext && previousData.facet === newData.facet;
}
/**
* Add a listener on the global change on the search store.
* @param {Function} cb [description]
*/
addSearchChangeListener(cb){
this.addListener('search:change', cb);
}
removeSearchChangeListener(cb){
this.removeListener('search:change', cb);
}
/**
* The store registrer itself on the dispatcher.
*/
registerDispatcher(){
var currentStore = this;
this.dispatch = AppDispatcher.register(function(transferInfo) {
var defKeys = keys(currentStore.definition); //TODO: a sub part of the keys may be needed.
var dataKeys = keys(transferInfo.action.data);
var intersectKeys = intersection(defKeys, dataKeys);
if(intersectKeys.length === defKeys.length){
currentStore.update(transferInfo.action.data);
}
});
}
}
module.exports = SearchStore;
| JavaScript | 0.001031 | @@ -233,24 +233,70 @@
rsection');%0A
+var isEqual = require('lodash/lang/isEqual');%0A
var Immutabl
@@ -2026,40 +2026,35 @@
%7D%0A
-%0A
-return
+var
isSame
-Search
+Facet
Context
&& p
@@ -2049,19 +2049,32 @@
Context
-&&
+= false;%0A if(
previous
@@ -2087,25 +2087,139 @@
acet
- === newData.face
+)%7B%0A isSameFacetContext = isEqual(previousData.facet,newData.facet);%0A %7D%0A%0A return isSameSearchContext && isSameFacetContex
t;%0A
@@ -2415,16 +2415,97 @@
);%0A %7D%0A%0A
+ /**%0A * Remove listener on search change event.%0A * @param cb callback%0A */%0A
remove
|
0e43e42153332b2d512df8a93f1d6a38f3e61bda | Use addClassName/removeClassName instead of setting the class name directly, in order to avoid overwriting previously set class names | fan/views/Editable.js | fan/views/Editable.js | jsio('from shared.javascript import Class, bind')
jsio('import fan.views.Value')
jsio('import fan.ui.textViewEdit')
exports = Class(fan.views.Value, function(supr) {
this._className += ' Editable'
this._padding = 4
this._border = 2
this._createContent = function() {
supr(this, '_createContent')
this._on('click', bind(this, '_onClick'))
this._makeFocusable()
}
this.handleKeyboardSelect = function() {
this._onClick()
}
this._onClick = function() {
var input = fin.createView('Input', this._itemId, this._property),
inputEl = input.getElement()
this._input = input
inputEl.style.position = 'absolute'
inputEl.style.overflow = 'hidden'
inputEl.style.padding = this._padding + 'px'
inputEl.style.paddingRight = 0 // so that the text inside the input box doesn't wrap around by hitting the end of the input box
inputEl.style.fontSize = this.getStyle('font-size');
inputEl.style.fontFamily = this.getStyle('font-family');
inputEl.style.fontWeight = this.getStyle('font-weight');
inputEl.style.lineHeight = this.getStyle('line-height');
fin.focus(this._itemId, this._property, bind(this, '_onBlur'))
input.subscribe('Blur', bind(this, '_onBlur'))
this._resizeInput()
input.appendTo(document.body)
input.focus()
}
this.createDelayedMethod('_onBlur', function() {
this._input.release()
this._input.remove()
})
this.setValue = function(value) {
supr(this, 'setValue', arguments)
if (!value) {
this._element.innerHTML = 'Click to edit ' + this._property
this._element.className = this._className + ' defaultValue'
}
this._resizeInput()
}
this._resizeInput = function() {
if (!this._input) { return; }
var layout = this.getLayout()
layout.left -= (this._padding + this._border)
layout.top -= (this._padding + this._border)
layout.height += this._padding * 2 + this._border * 2
layout.width += this._padding * 2 + this._border * 2 + 5
this._input.layout(layout)
}
}) | JavaScript | 0.000001 | @@ -1548,44 +1548,71 @@
his.
-_element.className = this._c
+addClassName('defaultValue')%0A%09%09%7D else %7B%0A%09%09%09this.removeC
lassName
+ '
@@ -1611,13 +1611,10 @@
Name
- + '
+('
defa
@@ -1622,16 +1622,17 @@
ltValue'
+)
%0A%09%09%7D%0A%09%09%0A
|
abe3dd7e1f68f9e59656155f87bf78c0a4e0571f | fix binarycookie | frida/binarycookie.js | frida/binarycookie.js | const NSHTTPCookieStorage = ObjC.classes.NSHTTPCookieStorage;
const store = NSHTTPCookieStorage.sharedHTTPCookieStorage();
const jar = store.cookies();
function str(obj, def) {
return obj ? obj.toString() : (def || 'N/A');
}
module.exports = function() {
let cookies = []
for (let i = 0; i < jar.count(); i++) {
let cookie = jar.objectAtIndex_(i);
let item = {
version: cookie.version().toString(),
name: cookie.name().toString(),
value: cookie.value().toString(),
expiresDate: str(cookie.expiresDate()),
created: cookie.created().toString(),
sessionOnly: str(cookie.sessionOnly(), false),
domain: cookie.domain().toString(),
partition: str(cookie.partition()),
path: cookie.path().toString(),
isSecure: str(cookie.isSecure(), 'false')
}
cookies.push(item)
}
return cookies
} | JavaScript | 0.000028 | @@ -1,13 +1,15 @@
const
+ %7B
NSHTTPC
@@ -20,16 +20,18 @@
eStorage
+ %7D
= ObjC.
@@ -41,29 +41,8 @@
sses
-.NSHTTPCookieStorage;
%0A%0Aco
@@ -98,17 +98,16 @@
torage()
-;
%0Aconst j
@@ -126,18 +126,16 @@
ookies()
-;%0A
%0A%0Afuncti
@@ -199,17 +199,16 @@
%7C 'N/A')
-;
%0A%7D%0A%0Amodu
@@ -333,17 +333,16 @@
ndex_(i)
-;
%0A let
@@ -483,226 +483,41 @@
-expiresDate: str(cookie.expiresDate()),%0A created: cookie.created().toString(),%0A sessionOnly: str(cookie.sessionOnly(), false),%0A domain: cookie.domain().toString(),%0A partition: str(cookie.partition()
+domain: cookie.domain().toString(
),%0A
|
3be732bb22f02f18842e8c197dac4d9a8db0448f | Change sides for menu | public/js/components/MenuBurger.js | public/js/components/MenuBurger.js | var React = require('react');
var rB = require('react-bootstrap');
var cE = React.createElement;
var rbm = require('react-burger-menu');
var AppActions = require('../actions/AppActions');
var REMOVE_KEY = 1;
var ADD_KEY = 2;
var DROPDOWN_KEY = 3;
var REGISTER_KEY = 4;
var styles = {
bmBurgerButton: {
position: 'fixed',
width: '36px',
height: '30px',
right: '36px',
top: '36px'
},
bmBurgerBars: {
// background: '#373a47',
background: '#8B0000'
},
bmCrossButton: {
height: '24px',
width: '24px'
},
bmCross: {
background: '#bdc3c7'
},
bmMenu: {
background: '#373a47',
padding: '1.5em 1.0em 0',
fontSize: '1.10em'
},
bmMorphShape: {
fill: '#373a47'
},
bmItemList: {
color: '#b8b7ad',
padding: '0.8em',
'overflowY': 'auto'
},
bmItem: {
display: 'block',
margin: '10px'
},
bmOverlay: {
background: 'rgba(0, 0, 0, 0.3)'
}
};
class MenuBurger extends React.Component {
constructor(props) {
super(props);
this.state = {
menuOpen: false
};
}
handleSelect(selectedKey, pending) {
if (selectedKey === REMOVE_KEY) {
this.closeMenu();
AppActions.changeRemoveModal(this.props.ctx, this.props.current,
true);
} else if (selectedKey === ADD_KEY) {
this.closeMenu();
AppActions.changeAddModal(this.props.ctx, this.props.current, true);
} else if (selectedKey === REGISTER_KEY) {
this.closeMenu();
AppActions.changeRegisterModal(this.props.ctx, true);
} else if (pending) {
this.closeMenu();
AppActions.setCurrent(this.props.ctx, {
url : this.props.current.url,
target: this.props.current.target,
pending: pending
});
} else {
console.log('Ignoring ' + selectedKey + ' target:' + pending);
}
}
addApp(event) {
event.preventDefault();
this.handleSelect(ADD_KEY);
}
removeApp(event) {
event.preventDefault();
this.handleSelect(REMOVE_KEY);
}
registerApp(event) {
event.preventDefault();
this.handleSelect(REGISTER_KEY);
}
switchApp(event) {
event.preventDefault();
this.handleSelect(DROPDOWN_KEY, event.target.id);
}
stateChange(state) {
this.setState({menuOpen: state.isOpen});
}
closeMenu () {
this.setState({menuOpen: false});
}
render() {
// var navBrand = 'root-launcher';
var navBrand = '#';
if (this.props.login) {
navBrand = navBrand + this.props.login.caOwner +
'-' + this.props.login.caLocalName;
}
var apps = Object.keys(this.props.apps || {});
return cE(rbm.scaleDown, {styles: styles, right: true,
width: 375,
pageWrapId: 'page-wrap',
outerContainerId: 'outer-container',
isOpen: this.state.menuOpen,
onStateChange: this.stateChange.bind(this)
},
[
cE('a', {
className: 'menu-heading-item',
key: 9883347
}, navBrand),
cE('hr', {key: 53434}),
cE('a', {
className: 'menu-add-item',
key: 12114,
onClick: this.addApp.bind(this)
}, cE('span', {
className: 'glyphicon glyphicon-plus text-success'
}), cE('span', null, ' Add CA')),
cE('a', {
className: 'menu-register-item',
key: 121424,
onClick: this.registerApp.bind(this)
}, cE('span', {
className: 'glyphicon glyphicon-pencil text-success'
}), cE('span', null, ' Register App')),
cE('a', {
className: 'menu-remove-item',
key: 3312114,
onClick: this.removeApp.bind(this)
}, cE('span', {
className: 'glyphicon glyphicon-remove text-danger'
}), cE('span', null, ' Remove CA')),
cE('hr', {key: 43434})
].concat(
apps.map((x, i) => cE('a', {
className: 'menu-item',
id: x,
key: i*83347 +12934,
onClick: this.switchApp.bind(this)
}, x))
)
);
}
}
module.exports = MenuBurger;
| JavaScript | 0.000001 | @@ -383,20 +383,19 @@
-righ
+lef
t: '36px
@@ -412,17 +412,17 @@
top: '3
-6
+0
px'%0A
@@ -3065,19 +3065,20 @@
right:
-tru
+fals
e,%0A
|
bd4c1fea0bc529862bf074a8dad1686f260a73b5 | change html file dest | gulp/configs/index.js | gulp/configs/index.js | var taskName = 'index';
var fileName = taskName + '.jsx';
var dest = './www';
var src = './src';
var webpack = require('webpack');
module.exports = {
taskName : taskName,
js: {
src: src + '/js/**/*',
dest: dest + '/assets/js',
uglify: false
},
sass: {
src: src + '/sass/**!(_)*.sass',
dest: dest + '/assets/css',
cssnext: {
browsers: ['last 2 versions']
},
minify: false
},
jade: {
src: src + '/jade/**/!(_)*.jade',
dest: dest,
options: {pretty: true}
},
copy: {
src: src + '/assets/**/*',
dest: dest + '/assets'
},
webpack: {
entry: src + '/js/' + fileName,
output: {
filename: 'bundle.js',
},
resolve: {
extensions: ['', '.js', '.jsx'],
modulesDirectories: ['node_modules', 'bower_components'],
alias: {
}
},
devtool: 'source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.ProvidePlugin({
jQuery: 'jquery',
jquery: 'jquery',
$: 'jquery'
})
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
}
| JavaScript | 0.000001 | @@ -484,16 +484,26 @@
st: dest
+ + '/html'
,%0A op
|
b73c061be7146ab67750301495d2a3f16f9d586b | Update aliases.js | gulp/tasks/aliases.js | gulp/tasks/aliases.js | var gulp = require('gulp');
gulp.task('default', ['less', 'js', 'watch']); | JavaScript | 0.000001 | @@ -1,8 +1,23 @@
+'use strict';%0A%0A
var gulp
@@ -83,8 +83,9 @@
atch'%5D);
+%0A
|
de54880d4ef939358cba6687a109b792475e03d0 | Add tweet and like interval | conf/server.js | conf/server.js | // This module is the server of my site.
// Require external dependecies.
var http = require('http');
var filed = require('filed');
var path = require('path');
var readFile = require('fs').readFile;
var publish = require('./publish');
// Start the site.
module.exports = function (config) {
var isInvalid
= !config || !config.port || !config.input || !config.output;
if (isInvalid) {
throw new Error('Invalid configuration');
}
// Create and start the server.
http.createServer(function (req, resp) {
var file = path.resolve(config.output + req.url);
var ext = file.split('.')[1];
var isPublish = req.url === config.hook;
if (isPublish) {
return publish(config, req, resp, function (err) {
console.log(err || 'Published on %s', new Date());
});
}
if (req.url != '/' && !ext) {
file += '.html';
} else if (!ext) {
file += '/';
}
req.pipe(filed(file)).pipe(resp);
}).listen(config.port, config.ip);
};
| JavaScript | 0.000013 | @@ -228,16 +228,50 @@
blish');
+%0Avar bake = require('blake').bake;
%0A%0A// Sta
@@ -1022,13 +1022,369 @@
fig.ip);
-
+%0A%0A // Retrieve latest tweet and instapaper likes.%0A var tweet = path.resolve(config.input, 'data', 'tweet.json');%0A var likes = path.resolve(config.input, 'data', 'likes.json');%0A%0A setInterval(function () %7B%0A bake(config.input, config.output, tweet, likes, function (err) %7B%0A console.log('Published tweet and likes on %25s', new Date());%0A %7D);%0A %7D, 3600000);
%0A%7D;%0A
|
bc2f83fcd74e6a7a576e1c2af1102dcf9fcb2a09 | change hostname | conf/server.js | conf/server.js | 'use strict';
/**
* Define server configuration
* @type {{host: string, port: string, protocol: string, url: module.exports.url}}
*/
module.exports = {
host : 'localhost',
port : '3000',
protocol : 'http',
url : function(){
return this.protocol + '://' + this.host +':' + this.port;
}
}; | JavaScript | 0.000228 | @@ -177,17 +177,17 @@
: '
-localhost
+127.0.0.1
',%0A
|
efe4a55bfc1ab3650d56cc213b594b84a90ce82d | fix some naming | game-of-life-react/src/components/GameOfLife.js | game-of-life-react/src/components/GameOfLife.js | import React, {Component} from 'react';
import Grid from '../game-logic/Grid';
export default class GameOfLife extends Component {
constructor(props) {
super(props);
this.state = {
alreadyGoing: false,
startStopText: 'Start',
gridSize: 10,
speed: 1,
grid: new Grid(10, [
{
row: 5,
col: 5
},
{
row: 5,
col: 6
},
{
row: 5,
col: 7
},
{
row: 6,
col: 5
},
{
row: 6,
col: 6
},
{
row: 6,
col: 7
},
{
row: 6,
col: 8
},
]),
speedOptions: [
1000,
500,
250,
200,
150,
100,
50
]
}
}
componentDidMount() {
this.interval = setInterval(() => {
console.log("GOOP")
if(this.state.alreadyGoing) {
let newCells = this.state.grid.nextGeneration();
let newGrid = this.state.grid;
newGrid.cells = newCells;
this.setState({
grid: newGrid
});
}
}, (500 * this.state.speed));
}
componentWillUnmount() {
clearInterval(this.interval);
}
showGrid = () => {
return <table className="grid-holder">
<tbody className="grid">
{
this.state.grid.cells.map((curRow, rowNum) => {
return (
<tr className="cell-row">
{this.showRow(curRow, rowNum)}
</tr>
)
})
}
</tbody>
</table>
}
showRow = (row, rowNum) => {
return row.map((curCell, colNum) => {
return (
<td className={this.cellType(curCell)} onClick={() => {this.clickCell(rowNum, colNum)}}>
</td>
)
});
}
cellType = (cell) => {
if(cell.alive) {
return "live-cell";
}
return "dead-cell";
}
clickCell = (rowNum, colNum) => {
if(this.state.alreadyGoing) {
return;
}
let newGrid = this.state.grid;
newGrid.cells[rowNum][colNum].alive = !newGrid.cells[rowNum][colNum].alive;
this.setState({
grid: newGrid
});
}
startStopGenerations = () => {
let stillGoing = !this.state.alreadyGoing;
let newStartStopText = '';
if(stillGoing) {
newStartStopText = 'Stop';
}else {
newStartStopText = 'Start';
}
this.setState({
alreadyGoing: stillGoing,
startStopText: newStartStopText
});
}
sizeChange = (event) => {
let newSize = event.target.value;
let oldGrid = this.state.grid.cells;
let living = [];
oldGrid.forEach((curRow, rowNum) => {
curRow.forEach((curCol, colNum) => {
if(oldGrid[rowNum][colNum].alive) {
living.push({row: rowNum, col: colNum});
}
});
});
let newGrid = new Grid(newSize, living);
this.setState({
grid: newGrid,
gridSize: newSize
});
}
speedChange = (event) => {
let newSpeed = event.target.value;
console.log(newSpeed);
clearInterval(this.interval);
this.interval = setInterval(() => {
if(this.state.alreadyGoing) {
let newCells = this.state.grid.nextGeneration();
let newGrid = this.state.grid;
newGrid.cells = newCells;
this.setState({
grid: newGrid
});
}
}, (this.state.speedOptions[newSpeed]));
this.setState({
speed: newSpeed
});
}
render() {
return (
<section className="grid-holder-ultimate">
{this.showGrid()}
<button id="start-stop-button" onClick={this.startStopGenerations}>{this.state.startStopText}</button>
<span id="size-input-holder">
<lable htmlFor={'size-input'}>Grid Size</lable>
<input id="size-input" type="number" min="2" max="41" onChange={this.sizeChange} value={this.state.gridSize}></input>
</span>
<span id="size-input-holder">
<lable htmlFor={'speed-input'}>Generation Speed</lable>
<input id="speed-input" type="number" min="0" max="6" onChange={this.speedChange} value={this.state.speed}></input>
</span>
</section>
);
}
} | JavaScript | 0.000088 | @@ -1339,43 +1339,8 @@
%7B%0D%0A
- console.log(%22GOOP%22)%0D%0A%0D%0A
@@ -1655,14 +1655,8 @@
%7D, (
-500 *
this
@@ -1667,16 +1667,26 @@
te.speed
+Options%5B1%5D
));%0D%0A
@@ -4028,40 +4028,8 @@
ue;%0D
-%0A console.log(newSpeed);%0D
%0A%0D%0A
|
7675e140987da389882b865023ede18a537a6e57 | Disable the mouse move error on the congratulations screen. | voiceover-voyageur/activity.js | voiceover-voyageur/activity.js | var questions = [
{
question: 'Use VoiceOver and press the hidden button below.',
inputGroup: 'question-1',
inputs: {}
},
{
question: 'Find the button labeled "The Go Button" and press it.',
inputGroup: 'question-2',
inputs: {}
},
{
question: 'Enter your name into the input field.',
inputGroup: 'question-3',
inputs: {
name: /.+/
}
},
{
question: 'Count the number of items in the list and enter the total below.',
inputGroup: 'question-4',
inputs: {
total: 14
}
},
{
question: 'Press the image of the dinosaur.',
inputGroup: 'question-5',
inputs: {},
onstart: function () {
document.getElementById('question-title').className += ' visually-hidden';
}
},
{
question: 'Press the H5 tag.',
inputGroup: 'question-6',
inputs: {}
},
{
question: 'Check the checkbox',
inputGroup: 'question-7',
inputs: {
dino: true
},
onstart: function () {
document.getElementById('dino').addEventListener('change', function (e) {
if (document.getElementById('dino').checked) activity.advanceOrFail('yes');
});
}
},
{
question: 'Press the button inside column “C”, row “4”.',
inputGroup: 'question-8',
inputs: {}
},
{
question: 'Press the green button.',
inputGroup: 'question-9',
inputs: {}
},
{
question: 'Go to the primary navigation, find the finish link.',
inputGroup: 'question-10',
inputs: {}
}
];
var
form = document.getElementById('question-form'),
runner = ActivityRunner(),
activity,
resetBtns = document.querySelectorAll('[type="reset"]'),
i = 0, t = resetBtns.length
;
for (i; i<t; i++) {
resetBtns[i].addEventListener('click', function (e) {
activity.advanceOrFail('no');
});
}
document.addEventListener('keydown', function (e) {
switch (e.target.className) {
case 'right':
e.preventDefault();
if (e.keyCode == 13 || e.keyCode == 32) activity.advanceOrFail('yes');
break;
case 'wrong':
e.preventDefault();
if (e.keyCode == 13 || e.keyCode == 32) activity.advanceOrFail('no');
break;
}
});
var fatalMouseMove = function (e) {
runner.send('fatal-error', null, {
image: '/images/mouse.svg',
message: 'Don’t use your mouse.'
});
document.removeEventListener('mousemove', fatalMouseMove);
};
runner.listen('start', function () {
document.addEventListener('mousemove', fatalMouseMove);
});
activity = FormValidator(runner, questions);
| JavaScript | 0 | @@ -2491,16 +2491,117 @@
);%0A%7D);%0A%0A
+runner.listen('end', function () %7B%0A document.removeEventListener('mousemove', fatalMouseMove);%0A%7D);%0A%0A
activity
|
dcbf9fc97884bb0b56a74571b1086c58fbd61fda | Use `win32` instead of `windows` for skipping the shebang tests | test/abs-shebang.js | test/abs-shebang.js | var path = require('path')
var fs = require('fs')
var spawn = require('child_process').spawn
var t = require('tap')
var node = process.execPath
var wrap = require.resolve('./fixtures/wrap.js')
var rimraf = require('rimraf')
var mkdirp = require('mkdirp')
var fs = require('fs')
if (process.platform === 'windows') {
t.plan(0, 'No proper shebang support on windows, so skip this')
process.exit(0)
}
var expect =
'before in shim\n' +
'shebang main\n' +
'after in shim\n' +
'before in shim\n' +
'shebang main\n' +
'after in shim\n'
var fixdir = path.resolve(__dirname, 'fixtures', 'shebangs')
t.test('setup', function (t) {
rimraf.sync(fixdir)
mkdirp.sync(fixdir)
t.end()
})
t.test('absolute', function (t) {
var file = path.resolve(fixdir, 'absolute.js')
runTest(file, process.execPath, t)
})
t.test('env', function (t) {
var file = path.resolve(fixdir, 'env.js')
runTest(file, '/usr/bin/env node', t)
})
function runTest (file, shebang, t) {
var content = '#!' + shebang + '\nconsole.log("shebang main")\n'
fs.writeFileSync(file, content, 'utf8')
fs.chmodSync(file, '0755')
var child = spawn(node, [wrap, file])
var out = ''
var err = ''
child.stdout.on('data', function (c) {
out += c
})
child.stderr.on('data', function (c) {
err += c
})
child.on('close', function (code, signal) {
t.equal(code, 0)
t.equal(signal, null)
t.equal(out, expect)
// console.error(err)
t.end()
})
}
t.test('cleanup', function (t) {
rimraf.sync(fixdir)
t.end()
})
| JavaScript | 0.000001 | @@ -301,20 +301,18 @@
=== 'win
-dows
+32
') %7B%0A t
|
002c4280197be4655dcc55409c26db97ff68d82f | remove h2b | test/base58check.js | test/base58check.js | var assert = require('assert')
var base58check = require('../src/base58check')
var fixtures = require('./fixtures/base58check.json')
function h2b(h) { return new Buffer(h, 'hex') }
describe('base58check', function() {
describe('decode', function() {
fixtures.valid.forEach(function(f) {
it('can decode ' + f.string, function() {
var actual = base58check.decode(f.string)
var expected = h2b(f.payload)
assert.deepEqual(actual, expected)
})
})
fixtures.invalid.forEach(function(f) {
it('throws on ' + f, function() {
assert.throws(function() {
base58check.decode(f)
}, /Invalid checksum/)
})
})
})
describe('encode', function() {
fixtures.valid.forEach(function(f) {
it('can encode ' + f.string, function() {
var actual = base58check.encode(h2b(f.payload))
var expected = f.string
assert.strictEqual(actual, expected)
})
})
})
})
| JavaScript | 0.999441 | @@ -132,57 +132,8 @@
')%0A%0A
-function h2b(h) %7B return new Buffer(h, 'hex') %7D%0A%0A
desc
@@ -341,45 +341,23 @@
ing)
-%0A var expected = h2b(f.payload
+.toString('hex'
)%0A%0A
@@ -374,13 +374,9 @@
ert.
-deepE
+e
qual
@@ -376,39 +376,40 @@
t.equal(actual,
-expecte
+f.payloa
d)%0A %7D)%0A
@@ -782,55 +782,37 @@
ode(
-h2b(f.payload))%0A var expected = f.string
+new Buffer(f.payload, 'hex'))
%0A%0A
@@ -848,16 +848,16 @@
al,
-expected
+f.string
)%0A
|
07db72fa5b5c63b923bfa72e72d95f47f7f1ed37 | Rename the variable at first test of case 7 | test/case7/case7.js | test/case7/case7.js | ;((rc) => {
'use strict';
var tagContent = 'router2-content';
var div = document.createElement('div');
div.innerHTML = `
<${tagContent} id="case7-1" hash="case(\\d+)">
Case 7 via RegExp
<${tagContent} id="case7-11" hash="case(\\d+)">
Nested param
<${tagContent} id="case7-111" hash="case(\\w+)-(\\d+)">
Very interesting test
</${tagContent}>
</${tagContent}>
</${tagContent}>
`;
var async1 = async_test('Case 7: hash changed to content[hash="case(\\d+)"]');
//var async2 = async_test('Case 7: hash changed to content[hash="case(\\d+)/case(\\d+)"]');
//var async3 = async_test('Case 7; hash changed to content[hash="case(\\d+)/case(\\d+)/case(\\w+)-(\\d+)"] in order to reset last state');
async1.next = async1.step_func(_ => {
window.location.hash = '';
var content1 = document.querySelector('#case7-1');
var order = [];
var expected = '123';
var check_show = async1.step_func((e) => {
order.push(e.type);
content1.removeEventListener(e.type, check_show);
assert_false(content1.hidden);
assert_equals(e.detail.param1, expected);
assert_equals(e.detail.router, content1);
//window.location.hash = '';
});
var check_hide = async1.step_func((e) => {
order.push(e.type);
content1.removeEventListener(e.type, check_hide);
assert_true(content1.hidden);
assert_equals(e.detail.param1, expected);
assert_equals(e.detail.router, content1);
assert_array_equals(order, ['show', 'hide']);
document.body.removeChild(div);
async1.done();
rc.next();
});
content1.addEventListener('show', check_show);
content1.addEventListener('hide', check_hide);
window.location.hash = "case" + expected;
});
rc.push(_ => {
async1.step(_ => {
document.body.appendChild(div);
async1.next();
});
})
})(window.routeCases);
| JavaScript | 0.000361 | @@ -897,24 +897,22 @@
var
-expected
+param1
= '123'
@@ -1114,32 +1114,30 @@
ail.param1,
-expected
+param1
);%0A ass
@@ -1423,24 +1423,22 @@
param1,
-expected
+param1
);%0A
@@ -1760,16 +1760,14 @@
%22 +
-expected
+param1
;%0A
|
91985283b30b153adf3a107b0785942cb028b60f | change to query | test/int/indexer.js | test/int/indexer.js | // Tests for configured indexer (ElasticQuery)
/*jslint node: true */
/* global describe,it */
'use strict';
var expect = require("expect.js");
var annotations = require('../../lib/annotations.js'), testApp = require('../lib/test-app.js'), utils = require('../../lib/utils.js');
describe('Indexer', function(done) {
it('should reset test app', function(done) {
testApp.start(function(err, ok) {
expect(err).to.be(undefined);
done();
});
});
// partial functions
it('should save a record', function(done) {
var saveRecord = GLOBAL.svc.indexer.saveRecord('testRecord', function(data) { return data.testField; });
var testRecord = { member: 'test', testField: 72};
saveRecord(testRecord, function(err, res) {
expect(err).to.be(null);
done();
});
});
it('should wait a second for indexing', function(done) {
utils.indexDelay(function() {
done();
});
});
it('should retrieve a record', function(done) {
var retrieveRecord = GLOBAL.svc.indexer.retrieveRecords('testRecord', ['testField']);
retrieveRecord('test', function(err, res) {
expect(err).to.be(null);
expect(res.hits.total).to.be(1);
expect(res.hits.hits[0]._source.testField).to.be(72);
done();
});
});
it('should index a page', function(done) {
var cItem = annotations.createContentItem({title: 'test title', uri: GLOBAL.testing.uniqURI, content: 'test content ' + GLOBAL.testing.uniq});
cItem.visitors = { member: GLOBAL.testing.uniqMember};
cItem.text = cItem.content;
GLOBAL.svc.indexer.saveContentItem(cItem, function(err, res) {
expect(err).to.be(null);
expect(res._id).to.not.be(null);
done();
});
});
it('should wait a second for indexing', function(done) {
utils.indexDelay(function() {
done();
});
});
it('should retrieve by URI', function(done) {
GLOBAL.svc.indexer.retrieveByURI(GLOBAL.testing.uniqURI, function(err, r) {
expect(err).to.be(null);
expect(r).to.not.be(undefined);
expect(r._source.uri).to.be(GLOBAL.testing.uniqURI);
done();
});
});
it('should form search', function(done) {
// delay for ElasticSearch refresh delay
GLOBAL.svc.indexer.formQuery({}, function(err, res) {
expect(err).to.be(null);
expect(res.hits.total).to.be(1);
done();
});
});
it('should form search by member', function(done) {
var found = { member: GLOBAL.testing.uniqMember, annotationState: utils.states.content.visited };
GLOBAL.svc.indexer.formQuery(found, function(err, res) {
expect(err).to.be(null);
expect(res.hits.total).to.be(1);
done();
});
});
it('should return no results for form search by non-member', function(done) {
var notFound = { member: GLOBAL.testing.uniqMember + 'nonense', annotationState: utils.states.content.visited };
GLOBAL.svc.indexer.formQuery(notFound, function(err, res) {
expect(err).to.be(null);
expect(res.hits.total).to.be(0);
done();
});
});
it('should form search by terms', function(done) {
var found = { terms: GLOBAL.testing.uniq };
GLOBAL.svc.indexer.formQuery(found, function(err, res) {
expect(err).to.be(null);
expect(res.hits.total).to.be(1);
done();
});
});
/*
it('should return no results for non-terms', function(done) {
var notFound = { terms: uniq + 'nonsense' }
indexer.formQuery(notFound, function(err, res) {
expect(err).to.be.null;
expect(res.hits.total).to.be(0);
done();
});
});
it('should form search by date range', function(done) {
var e = { from: '2013-10-04T19:51:15.963Z', to: '2013-10-07T19:51:15.963Z' }
indexer.formQuery(e, function(err, res) {
expect(err).to.be.null;
expect(res.hits.total).to.be(1);
done();
});
});
it('should form search by combination', function(done) {
var e = { terms: uniq, from: '2013-10-04T19:51:15.963Z', to: '2013-10-07T19:51:15.963Z', member: uniqMember };
indexer.formQuery(e, function(err, res) {
done();
});
});
it('should save search', function(done) {
indexer.saveScrape({ name : uniq, tags : 'test tags',
startingPage: uniqURI, continueFinding: 'within 2',
scanEvery: '5 hours', isSyndication: 'no', contentLocation: '' }, function(err, res) {
expect(err).to.be.null;
done();
});
});
it('should search searchs', function(done) {
indexer.searchQuery(uniq, function(err, res) {
expect(err).to.be.null;;;;
expect(res.hits.total).to.be(1);
done();
});
});
*/
});
| JavaScript | 0.000251 | @@ -2145,22 +2145,21 @@
ld form
-search
+query
', funct
@@ -2382,30 +2382,29 @@
should form
-search
+query
by member',
@@ -2720,30 +2720,29 @@
ts for form
-search
+query
by non-memb
@@ -3057,30 +3057,29 @@
should form
-search
+query
by terms',
|
a2a2f73ba281b85ba83fa14c1601958e11f9605b | Improve integration tests, especially on Windows | test/integration.js | test/integration.js | 'use strict';
var expect = require('expect');
var fs = require('fs');
var path = require('path');
var vinyl = require('vinyl-fs');
var jshint = require('gulp-jshint');
var spawn = require('child_process').spawn;
var once = require('once');
var aOnce = require('async-once');
var del = require('del');
var through = require('through2');
var Undertaker = require('../');
describe('integrations', function() {
var taker;
beforeEach(function(done) {
taker = new Undertaker();
done();
});
it('should handle vinyl streams', function(done) {
taker.task('test', function() {
return vinyl.src('./fixtures/test.js', { cwd: __dirname })
.pipe(vinyl.dest('./fixtures/out', { cwd: __dirname }));
});
taker.parallel('test')(done);
});
it('should exhaust vinyl streams', function(done) {
taker.task('test', function() {
return vinyl.src('./fixtures/test.js', { cwd: __dirname });
});
taker.parallel('test')(done);
});
it('should lints all piped files', function(done) {
taker.task('test', function() {
return vinyl.src('./fixtures/test.js', { cwd: __dirname })
.pipe(jshint());
});
taker.parallel('test')(done);
});
it('should handle a child process return', function(done) {
taker.task('test', function() {
return spawn('ls', ['-lh', __dirname]);
});
taker.parallel('test')(done);
});
it('should run dependencies once', function(done) {
var count = 0;
taker.task('clean', once(function() {
count++;
return del(['./fixtures/some-build.txt'], { cwd: __dirname });
}));
taker.task('build-this', taker.series('clean', function(cb) {
cb();
}));
taker.task('build-that', taker.series('clean', function(cb) {
cb();
}));
taker.task('build', taker.series(
'clean',
taker.parallel(['build-this', 'build-that'])
));
taker.parallel('build')(function(err) {
expect(count).toEqual(1);
done(err);
});
});
it('should run dependencies once', function(done) {
var count = 0;
taker.task('clean', aOnce(function(cb) {
cb();
count++;
del(['./fixtures/some-build.txt'], { cwd: __dirname }, cb);
}));
taker.task('build-this', taker.series('clean', function(cb) {
cb();
}));
taker.task('build-that', taker.series('clean', function(cb) {
cb();
}));
taker.task('build', taker.series(
'clean',
taker.parallel(['build-this', 'build-that'])
));
taker.parallel('build')(function(err) {
expect(count).toEqual(1);
done(err);
});
});
it('can use lastRun with vinyl.src `since` option', function(done) {
var count = 0;
var filepath = path.join(__dirname, './fixtures/tmp/testMore.js');
function setup() {
return vinyl.src('./fixtures/test*.js', { cwd: __dirname })
.pipe(vinyl.dest('./fixtures/tmp', { cwd: __dirname }));
}
// Some built
taker.task('build', function() {
return vinyl.src('./fixtures/tmp/*.js', { cwd: __dirname })
.pipe(vinyl.dest('./fixtures/out', { cwd: __dirname }));
});
function userWait(cd) {
setTimeout(cd, 1100);
}
function userEdit(cb) {
fs.appendFile(filepath, ' ', cb);
}
function cleanup(cb) {
fs.unlink(filepath, cb);
}
function countEditedFiles() {
return vinyl.src('./fixtures/tmp/*.js', { cwd: __dirname, since: taker.lastRun('build') })
.pipe(through.obj(function(file, enc, cb) {
count++;
cb();
}));
}
taker.series(setup, 'build', userWait, userEdit, countEditedFiles, cleanup, function(cb) {
expect(count).toEqual(1);
cb();
})(done);
});
});
| JavaScript | 0 | @@ -37,24 +37,48 @@
'expect');%0A%0A
+var os = require('os');%0A
var fs = req
@@ -390,16 +390,197 @@
../');%0A%0A
+var isWindows = (os.platform() === 'win32');%0A%0Afunction cleanup() %7B%0A return del(%5B%0A path.join(__dirname, './fixtures/out/'),%0A path.join(__dirname, './fixtures/tmp/'),%0A %5D);%0A%7D%0A%0A
describe
@@ -695,32 +695,78 @@
done();%0A %7D);%0A%0A
+ beforeEach(cleanup);%0A afterEach(cleanup);%0A%0A
it('should han
@@ -1544,32 +1544,133 @@
', function() %7B%0A
+ if (isWindows) %7B%0A return spawn('cmd', %5B'/c', 'dir'%5D).on('error', console.log);%0A %7D%0A%0A
return spa
@@ -3050,92 +3050,46 @@
-var count = 0;%0A var filepath = path.join(__dirname, './fixtures/tmp/testMore.js')
+this.timeout(5000);%0A%0A var count = 0
;%0A%0A
@@ -3244,24 +3244,84 @@
%7D));%0A %7D%0A%0A
+ function delay(cb) %7B%0A setTimeout(cb, 2000);%0A %7D%0A%0A
// Some
@@ -3524,180 +3524,94 @@
user
-Wait(cd) %7B%0A setTimeout(cd, 1100);%0A %7D%0A%0A function userEdit(cb) %7B%0A fs.appendFile(filepath, ' ', cb);%0A %7D%0A%0A function cleanup(cb) %7B%0A fs.unlink(filepath
+Edit(cb) %7B%0A fs.appendFile(path.join(__dirname, './fixtures/tmp/testMore.js'), ' '
, cb
@@ -3881,16 +3881,23 @@
s(setup,
+ delay,
'build'
@@ -3902,16 +3902,13 @@
d',
-userWait
+delay
, us
@@ -3935,19 +3935,10 @@
iles
-, cleanup,
+)(
func
@@ -3934,34 +3934,35 @@
Files)(function(
-cb
+err
) %7B%0A expect
@@ -3983,27 +3983,32 @@
l(1);%0A
-cb(
+done(err
);%0A %7D)(do
@@ -4004,22 +4004,16 @@
;%0A %7D)
-(done)
;%0A %7D);%0A
|
4018d39199a59bb6da06084c82a52abc7e9a1f3d | Add a 'connect' server integration test | test/integration.js | test/integration.js | const expect = require('chai').expect;
process.env.TESTING='testing';
describe("These integration tests", function() {
var server, request;
beforeEach(function (done) {
var codeObjects = {
aPlayground: {
object1: '// code1',
object2: '// code2'
}
}
server = require('../app')(codeObjects);
request = require('supertest')(server);
server.listen(0, done);
});
afterEach(function(done) {
server.close(done);
});
it("may launch a server", function() {
return request
.get('/list')
.expect(200)
.expect(/aPlayground/);
});
describe("has client-server scenarios where", function() {
var programmer, renderer;
beforeEach(function (done) {
const serverUrl = 'http://127.0.0.1:' + server.address().port;
var doneWhenCalledTwice = callWhenCalledTimes(done,2);
renderer = require('socket.io-client')(serverUrl, {
forceNew: true,
query: { playgroundId: 'here', client: 'renderer' }
});
renderer.on('connect', doneWhenCalledTwice);
programmer = require('socket.io-client')(serverUrl, {
forceNew: true,
query: { playgroundId: 'here', client: 'programmer' }
});
programmer.on('connect', doneWhenCalledTwice);
});
afterEach(function() {
programmer.disconnect();
renderer.disconnect();
});
it("renderer receives objects list when programmer updates code", function(done) {
renderer.on('objects list', function(data) {
expect(data.objectIds).to.deep.equal(['creature']);
done();
});
var data = {
objectId: "creature",
source: 'dummy source',
};
programmer.emit('code update', data);
});
});
});
function callWhenCalledTimes(callback,times) {
return function() {
times--;
if (times == 0) callback();
};
};
| JavaScript | 0.000017 | @@ -604,16 +604,555 @@
%0A %7D);%0A%0A
+ it(%22sends all codeObjects when a renderer connects%22, function(done) %7B%0A const serverUrl = 'http://127.0.0.1:' + server.address().port;%0A var renderer = require('socket.io-client')(serverUrl, %7B%0A forceNew: true,%0A query: %7B playgroundId: 'aPlayground', client: 'renderer' %7D%0A %7D);%0A renderer.on('connect', function() %7B%0A renderer.on('playground full update', function(data) %7B%0A expect(data).to.deep.equal(%7Bobject1: '// code1', object2: '// code2'%7D);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A
descri
|
88fc03b52e89ba519cacb9a93a0ced0b66ca8614 | Clarify newListener triggering * test. | test/newlistener.js | test/newlistener.js | /*jslint node: true */
"use strict";
var H = require('../index').EventEmitter;
var _ = require('lodash');
var assert = require('assert');
describe('HevEmitter newlistener', function () {
describe('on events', function () {
it('should be triggered when a listener is added to a "name" event', function (done) {
var h = new H();
h.on(['newListener'], function () {
done();
});
h.on(['star'], function () {});
});
it('should *NOT* trigger * listeners', function (done) {
var h = new H();
h.on(['*'], function () {
done(true);
});
h.on(['newListener'], function () {
done();
});
h.on(['star'], function () {});
h.emit(['newListener']);
});
it('should *NOT* trigger ** listeners', function (done) {
var h = new H();
h.on(['**'], function () {
done(true);
});
h.on(['newListener'], function () {
done();
});
h.on(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data', function (done) {
var h = new H();
h.on(['newListener'], function (data) {
assert(data);
done();
});
h.on(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data.event equal to the listened to event', function (done) {
var h = new H();
h.on(['newListener'], function (data) {
assert.deepEqual(data.event, ['star']);
done();
});
h.on(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data.listener equal to the listener function', function (done) {
var h = new H();
var listener = function () {};
h.on(['newListener'], function (data) {
assert.equal(data.listener, listener);
done();
});
h.on(['star'], listener);
});
});
describe('once events', function () {
it('should be triggered when a listener is added to a "name" event', function (done) {
var h = new H();
h.on(['newListener'], function () {
done();
});
h.once(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data', function (done) {
var h = new H();
h.on(['newListener'], function (data) {
assert(data);
done();
});
h.once(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data.event equal to the listened to event', function (done) {
var h = new H();
h.on(['newListener'], function (data) {
assert.deepEqual(data.event, ['star']);
done();
});
h.once(['star'], function () {});
});
it('should be triggered when a listener is added to a "name" event, with data.listener equal to the listener function', function (done) {
var h = new H();
var listener = function () {};
h.on(['newListener'], function (data) {
assert.equal(data.listener, listener);
done();
});
h.once(['star'], listener);
});
});
describe('on sub events', function () {
it('should be triggered when a listener is added to a "newlistener/route" event', function (done) {
var h = new H();
h.on(['newListener', 'powersurge'], function () {
done(true);
});
h.on(['newListener', 'alright'], function () {
done();
});
h.on(['alright'], function () {});
});
});
});
| JavaScript | 0 | @@ -605,16 +605,21 @@
h.on(%5B
+'*',
'*'%5D, fu
@@ -810,45 +810,8 @@
%7D);%0A
- h.emit(%5B'newListener'%5D);%0A
|
03d00ec53114f74f6e82a6ea7ac1fdb61f2b863b | add an even simpler test that actually works | test/player_test.js | test/player_test.js | var assert = require("assert")
var player = require('../player')
var game_state_sample = require("./data/game-state-example.json")
describe("player", function() {
describe("#bet_request", function() {
it("should return a number", function() {
assert.equal(
typeof(player.bet_request(JSON.parse( game_state_sample )).toString()),
"number"
)
})
})
})
| JavaScript | 0.000008 | @@ -153,24 +153,193 @@
unction() %7B%0A
+ describe(%22#version%22, function() %7B%0A it(%22should return something%22, function() %7B%0A assert.equal( typeof(player.VERSION), %22string%22 )%0A %7D)%0A %7D)%0A%0A
describe
|
9d2100058687a53f45ba06ce3c045a65639ca0bf | Update unit tests | test/satang.test.js | test/satang.test.js | import { values } from 'lodash';
import Satang, { Currencies, CurrencyData } from '../src';
test('it throws an error when initialized with unsupported currency', () => {
const baseCurrency = 'thb';
expect(() => new Satang('thb', 1000))
.toThrowError(`Unrecognized currency: ${baseCurrency}. Only ${values(Currencies).join(',')} are supported`);
});
test('it throws an error is money is not a number', () => {
expect(() => new Satang(Currencies.THB, '100')).toThrowError('Money is not a number');
expect(() => new Satang(Currencies.THB, NaN)).toThrowError('Money is not a number');
expect(() => new Satang(Currencies.THB, Infinity)).toThrowError('Get out');
});
test('it throws an error when initialized with the money under 0', () => {
expect(() => new Satang(Currencies.THB, -10)).toThrowError('Minimum money value is 0');
});
test('it sets information correctly', () => {
const productPriceInThb = new Satang(Currencies.THB, 100000);
const productPriceInUsd = new Satang(Currencies.USD, 100000);
expect(productPriceInThb.money).toBe(100000);
expect(productPriceInThb.baseCurrency).toBe(CurrencyData[Currencies.THB]);
expect(productPriceInUsd.money).toBe(100000);
expect(productPriceInUsd.baseCurrency).toBe(CurrencyData[Currencies.USD]);
});
test('it displays satang information properly', () => {
const productPrice = new Satang(Currencies.THB, 100020);
const productPriceRepresentation = productPrice.display();
expect(typeof productPriceRepresentation).toBe('string');
expect(productPriceRepresentation).toBe('฿1,000.20');
});
test('it throws an error when adding an object that\'s not a Satang', () => {
const productOnePrice = new Satang(Currencies.THB, 100020);
const productTwoPrice = new Satang(Currencies.THB, 140020);
expect(() => productOnePrice.add('productTwoPrice')).toThrowError('Only a satang can be added to a satang');
});
test('it throws an error when adding a Satang with different base currencies', () => {
const productOnePrice = new Satang(Currencies.THB, 100020);
const productTwoPrice = new Satang(Currencies.USD, 140020);
expect(() => productOnePrice.add(productTwoPrice)).toThrowError('Satangs should be setup with same base currencies if they are to be added');
});
test('it can be manipulated by adding a satang', () => {
const productOnePrice = new Satang(Currencies.THB, 100020);
const productTwoPrice = new Satang(Currencies.THB, 140020);
const cartPrice = new Satang(Currencies.THB, 0);
cartPrice.add(productOnePrice).add(productTwoPrice);
expect(cartPrice.money).toBe(240040);
});
test('it returns an array of supported currency info', () => {
const productPrice = new Satang(Currencies.THB, 100020);
const expectedValue = values(CurrencyData);
expect(productPrice.supportedCurrencies()).toEqual(expectedValue);
});
| JavaScript | 0 | @@ -1,37 +1,4 @@
-import %7B values %7D from 'lodash';%0A
impo
@@ -22,28 +22,29 @@
encies,
-CurrencyData
+ThaiBaht, USD
%7D from
@@ -136,38 +136,8 @@
%3E %7B%0A
- const baseCurrency = 'thb';%0A
ex
@@ -202,16 +202,21 @@
ognized
+base
currency
@@ -217,18 +217,16 @@
rrency:
-$%7B
baseCurr
@@ -233,61 +233,78 @@
ency
-%7D. Only $%7Bvalues(Currencies).join(',')%7D are supported
+ should be an instance of Currency class. Check the docs for more info
%60);%0A
@@ -394,30 +394,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, '100')
@@ -477,30 +477,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, NaN)).
@@ -558,30 +558,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, Infini
@@ -710,30 +710,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, -10)).
@@ -854,38 +854,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 100000);%0A
@@ -912,35 +912,24 @@
new Satang(
-Currencies.
USD, 100000)
@@ -1006,185 +1006,30 @@
ceIn
-Thb.baseCurrency).toBe(CurrencyData%5BCurrencies.THB%5D);%0A%0A expect(productPriceInUsd.money).toBe(100000);%0A expect(productPriceInUsd.baseCurrency).toBe(CurrencyData%5BCurrencies.USD%5D
+Usd.money).toBe(100000
);%0A%7D
@@ -1118,38 +1118,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 100020);%0A
@@ -1434,38 +1434,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 100020);%0A
@@ -1490,38 +1490,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 140020);%0A%0A
@@ -1750,38 +1750,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 100020);%0A
@@ -1810,27 +1810,16 @@
Satang(
-Currencies.
USD, 140
@@ -2064,38 +2064,32 @@
new Satang(
-Currencies.THB
+ThaiBaht
, 100020);%0A
@@ -2124,30 +2124,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, 140020
@@ -2174,30 +2174,24 @@
Satang(
-Currencies.THB
+ThaiBaht
, 0);%0A%0A
@@ -2356,67 +2356,8 @@
%3E %7B%0A
- const productPrice = new Satang(Currencies.THB, 100020);%0A
co
@@ -2376,16 +2376,23 @@
Value =
+Object.
values(C
@@ -2401,13 +2401,11 @@
renc
-yData
+ies
);%0A%0A
@@ -2413,28 +2413,22 @@
expect(
-productPrice
+Satang
.support
|
af49c7d9e7ae11ff13914ab3f23b247554a4e0cb | add global.pi to spec helper | test/spec_helper.js | test/spec_helper.js | var psc = require('primus-sinon-chai');
global.expect = psc.chai.expect;
global.sinon = psc.sinon;
| JavaScript | 0 | @@ -92,8 +92,42 @@
.sinon;%0A
+global.pi = !!process.env.NOS_PI;%0A
|
45531e2e61abee4b4983fa0d5c0ac9613c84e734 | Add sequential synchronous functions counter example. | test/synchronous.js | test/synchronous.js | /*jslint node: true */
"use strict";
var H = require('../index').EventEmitter;
var _ = require('underscore');
var assert = require('assert');
describe('HevEmitter on synchronous listener ', function () {
it('should trigger synchronous ** events synchronously', function () {
var h = new H();
var called = false;
h.on(['**'], function () {
called = true;
});
h.emit(['ventaxi']);
assert(called);
});
it('should trigger synchronous * events synchronously', function () {
var h = new H();
var called = false;
h.on(['*'], function () {
called = true;
});
h.emit(['bridge']);
assert(called);
});
it('should trigger synchronous "name" events synchronously', function () {
var h = new H();
var called = false;
h.on(['laforge'], function () {
called = true;
});
h.emit(['laforge']);
assert(called);
});
it('should trigger synchronous */"name" events synchronously', function () {
var h = new H();
var called = false;
h.on(['*', 'worf'], function () {
called = true;
});
h.emit(['data', 'worf']);
assert(called);
});
it('should trigger synchronous */** events synchronously', function () {
var h = new H();
var called = false;
h.on(['*', '**'], function () {
called = true;
});
h.emit(['klingon', 'clansmen', 'culture']);
assert(called);
});
it('should trigger synchronous */* events synchronously', function () {
var h = new H();
var called = false;
h.on(['*', '*'], function () {
called = true;
});
h.emit(['well', 'done']);
assert(called);
});
it('should trigger synchronous */"name" events synchronously', function () {
var h = new H();
var called = false;
h.on(['*', 'shuttle'], function () {
called = true;
});
h.emit(['enterprise', 'shuttle']);
assert(called);
});
it('should trigger synchronous "name"/** events synchronously', function () {
var h = new H();
var called = false;
h.on(['come', '**'], function () {
called = true;
});
h.emit(['come', 'in', 'enterprise']);
assert(called);
});
it('should trigger synchronous "name"/* events synchronously', function () {
var h = new H();
var called = false;
h.on(['locate', '*'], function () {
called = true;
});
h.emit(['locate', '*']);
assert(called);
});
it('should trigger synchronous "name"/"name" events synchronously', function () {
var h = new H();
var called = false;
h.on(['jump', 'particle'], function () {
called = true;
});
h.emit(['*', '*']);
assert(called);
});
});
| JavaScript | 0 | @@ -3017,13 +3017,373 @@
%7D);%0A%0A
+ it('should trigger sequential synchronous %22name%22 events synchronously', function () %7B%0A var h = new H();%0A var called = 0;%0A h.on(%5B'laforge'%5D, function () %7B%0A called++; %0A %7D);%0A h.on(%5B'laforge'%5D, function () %7B%0A called++;%0A %7D);%0A h.emit(%5B'laforge'%5D);%0A assert.equal(2, called);%0A %7D);%0A%0A%0A
%0A%7D);%0A
|
aec1d3e260e3a9793456e53516463cbe897f4e17 | add tests | test/test-fluxex.js | test/test-fluxex.js | 'use strict';
var assert = require('chai').assert,
fluxex = require('..');
describe('fluxex', function () {
it('can be constructed by undefined', function (done) {
var F = new fluxex();
done();
});
it('can be constructed by null', function (done) {
var F = new fluxex(null);
done();
});
it('can be constructed by number', function (done) {
var F = new fluxex(123);
done();
});
it('can be constructed by an object', function (done) {
var F = new fluxex({a: 1, b: 2});
assert.equal(1, F.a);
assert.equal(2, F.b);
done();
});
});
| JavaScript | 0 | @@ -636,13 +636,279 @@
%0A %7D);
+%0A%0A describe('.toString()', function () %7B%0A it('will not include prototype methods', function (done) %7B%0A var F = new fluxex(%7Ba: 1, b: 2%7D);%0A%0A assert.equal(undefined, F.toString().match(/toString/));%0A done();%0A %7D);%0A %7D);
%0A%7D);%0A
|
77ee555a7cb7fdbed11fc19b30f1ae59cb9d175d | Add test where localStorage quota triggers a trim | test/tests/quota.js | test/tests/quota.js | describe('after filling localStorage quota', () => {
const key = 'playbyplay_trash_K79kxaC%I8HrRGDoousr';
let tooLong;
beforeEach(done => {
tooLong = 'startups would kill to grow this fast';
while (true) { // eslint-disable-line no-constant-condition
tooLong += tooLong;
try {
localStorage[key] = tooLong;
} catch(e) {
break;
}
}
done();
});
it('should return a quota error on save', () =>
expect(playbyplay.save(tooLong, {maxBytes: Infinity})).to.be.rejectedWith(Error,
`Could not save run of length ${tooLong.length + 4}, exceeds localStorage quota`)
);
after(async () => {
localStorage.removeItem(key);
await playbyplay.clear();
});
});
| JavaScript | 0 | @@ -13,45 +13,115 @@
ter
-filling localStorage quota', () =%3E %7B%0A
+clearing', () =%3E %7B%0A let tooLong;%0A let halfTooLong1;%0A let halfTooLong2;%0A%0A function init() %7B%0A
@@ -176,52 +176,8 @@
sr';
-%0A%0A let tooLong;%0A%0A beforeEach(done =%3E %7B
%0A
@@ -479,15 +479,308 @@
-done();
+localStorage.removeItem(key);%0A%0A halfTooLong1 = tooLong.substring(0, tooLong.length / 2);%0A halfTooLong2 = halfTooLong1.substring(0, halfTooLong1.length - 1) + '$';%0A %7D%0A%0A beforeEach(async () =%3E %7B%0A await playbyplay.clear();%0A if (!tooLong) %7B%0A init();%0A %7D
%0A
@@ -825,14 +825,56 @@
ror
-o
+whe
n sav
+ing a run that cannot fit in localStorag
e',
@@ -1078,63 +1078,186 @@
-after(async () =%3E %7B%0A localStorage.removeItem(key
+describe('and saving two runs that cannot both fit in localStorage', () =%3E %7B%0A beforeEach(async () =%3E %7B%0A await playbyplay.save(halfTooLong1, %7BmaxBytes: Infinity%7D
);%0A
@@ -1255,32 +1255,36 @@
nity%7D);%0A
+
+
await playbyplay
@@ -1288,22 +1288,242 @@
lay.
-clear();%0A %7D
+save(halfTooLong2, %7BmaxBytes: Infinity%7D);%0A %7D);%0A%0A it('should load the last run only', () =%3E%0A expect(playbyplay.load()).to.eventually.deep.equal(%5BhalfTooLong2%5D)%0A );%0A %7D);%0A%0A afterEach(playbyplay.clear
);%0A%7D
|
961a93020b91e56a24100562dd65c46977b60a4c | Comment fixes | test/unit/finish.js | test/unit/finish.js |
console.log();
console.log('-------------------------------');
console.log(' TESTING COMPLETED');
console.log('-------------------------------');
console.log('Total Tests: ' + assert.count);
-- ANY ERRORS?
if (assert.fail.count) {
console.API.color('red', 'Total Failed: ' + assert.fail.count);
console.log();
-- RETURN ERROR
phantom.exit(1);
}
else {
-- ALL GOOD!
console.API.color('green', 'Total Passed: ' + assert.pass.count);
console.log();
phantom.exit(0);
}
| JavaScript | 0 | @@ -188,18 +188,18 @@
ount);%0A%0A
---
+//
ANY ERR
@@ -312,18 +312,18 @@
log();%0A%09
---
+//
RETURN
@@ -357,18 +357,18 @@
lse %7B %0A%09
---
+//
ALL GOO
|
a1c4f147b1858601570d4ef294e2a441cf6ac3ed | add test case for object | test/unit/object.js | test/unit/object.js | module('fobject');
var FObject = FIRE.FObject;
test('basic test', function () {
var obj = new FObject();
strictEqual(obj.__classname__, 'FIRE.FObject', 'class name');
strictEqual(obj.isValid, true, 'valid');
});
test('destroyImmediate', function () {
expect(2);
var obj = new FObject();
obj._onPreDestroy = function () {
ok(true, 'destroy callback called');
}
obj._destroyImmediate();
strictEqual(obj.isValid, false, 'destroyed');
obj._onPreDestroy = function () {
ok(false, 'can only destroyed once');
}
var error = console.error;
console.error = function () {} // forbid error
obj._destroyImmediate();
console.error = error;
});
test('FObject.isValid', function () {
var obj = new FObject();
strictEqual(FObject.isValid(obj), true, 'valid');
obj._destroyImmediate();
strictEqual(FObject.isValid(obj), false, 'destroyed');
delete obj;
strictEqual(FObject.isValid(), false, 'undefined return false 1');
strictEqual(FObject.isValid(obj), false, 'undefined return false 2');
strictEqual(FObject.isValid(null), false, 'null return false');
});
test('deferred destroy', function () {
var obj = new FObject();
obj._onPreDestroy = function () {
ok(false, 'should not callback');
}
obj.destroy();
// frame 1
strictEqual(obj.isValid, true, 'still available in frame 1');
strictEqual(FObject.isValid(obj), true, 'still available in frame 1');
obj._onPreDestroy = function () {
ok(true, 'should callback');
}
FObject._deferredDestroy();
strictEqual(obj.isValid, false, 'deleted at the end of frame 1');
strictEqual(FObject.isValid(obj), false, 'deleted at the end of frame 1');
obj._onPreDestroy = function () {
ok(false, 'should not callback anymore');
}
// frame 2
var obj2 = new FObject();
obj2.destroy();
strictEqual(obj2.isValid, true, 'still available in frame 2');
FObject._deferredDestroy();
strictEqual(obj2.isValid, false, 'deleted at the end of frame 2');
});
test('multiply deferred destroy', function () {
var obj1 = new FObject();
var obj2 = new FObject();
obj1.destroy();
obj2.destroy();
strictEqual(obj1.isValid, true, 'still available in this frame');
strictEqual(obj2.isValid, true, 'still available in this frame');
obj2._onPreDestroy = function () {
ok(true, 'should callback');
}
FObject._deferredDestroy();
strictEqual(obj1.isValid, false, 'deleted at the end of frame');
strictEqual(obj2.isValid, false, 'deleted at the end of frame');
});
| JavaScript | 0.000027 | @@ -2640,16 +2640,818 @@
of frame');%0A%7D);%0A
+%0Atest('destroy other at destroy callback', function () %7B%0A expect(3);%0A%0A var obj1 = new FObject();%0A var obj2 = new FObject();%0A%0A obj1.destroy();%0A%0A obj2._onPreDestroy = function () %7B%0A ok(false, 'other should not destroyed this frame');%0A %7D%0A%0A obj1._onPreDestroy = function () %7B%0A obj2.destroy();%0A strictEqual(obj2.isValid, true, 'other is valid until the end of next frame');%0A %7D%0A%0A FObject._deferredDestroy();%0A%0A obj1._onPreDestroy = function () %7B%0A ok(false, 'should not destroyed again');%0A %7D%0A obj2._onPreDestroy = function () %7B%0A ok(true, %22should called other's destroy callback at the end of next frame%22);%0A %7D%0A%0A FObject._deferredDestroy();%0A%0A strictEqual(obj2.isValid, false, 'other should destroyed at the end of next frame');%0A%7D);%0A
|
dc6273d9840f9d3a63783c78739af137364dc986 | Add tests for disabling slides. | tests/pat/slides.js | tests/pat/slides.js | define(["pat/slides"], function(pattern) {
describe("Slides pattern", function() {
beforeEach(function() {
$("<div/>", {id: "lab"}).appendTo(document.body);
});
afterEach(function() {
$("#lab").remove();
});
describe("init", function() {
it("Return result from _hook", function() {
spyOn(pattern, "_hook").andCallFake(function() {
return "jq";
});
expect(pattern.init("jq")).toBe("jq");
expect(pattern._hook).toHaveBeenCalledWith("jq");
});
});
describe("_hook", function() {
it("Return jQuery object", function() {
var jq = jasmine.createSpyObj("jQuery", ["off", "on"]);
jq.off.andReturn(jq);
jq.on.andReturn(jq);
expect(pattern._hook(jq)).toBe(jq);
});
});
describe("_collapse_ids", function() {
it("Single id", function() {
expect(pattern._collapse_ids(["foo"])).toEqual(["foo"]);
});
it("Comma-separated list of ids", function() {
expect(pattern._collapse_ids(["foo,bar"])).toEqual(["foo", "bar"]);
});
it("Skip empty ids", function() {
expect(pattern._collapse_ids(["foo,,bar"])).toEqual(["foo", "bar"]);
});
it("Parameter without value", function() {
expect(pattern._collapse_ids([null])).toEqual([]);
});
it("Parameter with empty value", function() {
expect(pattern._collapse_ids([""])).toEqual([]);
});
it("Multiple parameters", function() {
expect(pattern._collapse_ids(["foo", "bar"])).toEqual(["foo", "bar"]);
});
});
});
});
| JavaScript | 0 | @@ -1872,24 +1872,1481 @@
%0A %7D);
+%0A%0A describe(%22_disable_slides%22, function() %7B%0A it(%22Remove slides from DOM%22, function() %7B%0A var $show = $(%22%3Cdiv/%3E%22, %7B%22class%22: %22pat-slides%22%7D);%0A for (var i=1; i%3C=4; i++)%0A $(%22%3Cdiv/%3E%22, %7B%22class%22: %22slide%22, id: %22slide%22+i%7D).appendTo($show);%0A pattern._disable_slides($show, %5B%22slide1%22, %22slide3%22%5D);%0A var ids = $.makeArray($show.find(%22.slide%22).map(function(idx, el) %7B return el.id;%7D));%0A expect(ids).toEqual(%5B%22slide1%22, %22slide3%22%5D);%0A %7D);%0A%0A it(%22Trigger reset when removing slides%22, function() %7B%0A var $show = $(%22%3Cdiv/%3E%22, %7B%22class%22: %22pat-slides%22%7D);%0A for (var i=1; i%3C=4; i++)%0A $(%22%3Cdiv/%3E%22, %7B%22class%22: %22slide%22, id: %22slide%22+i%7D).appendTo($show);%0A spyOn(pattern, %22_reset%22);%0A pattern._disable_slides($show, %5B%22slide1%22, %22slide3%22%5D);%0A expect(pattern._reset).toHaveBeenCalled();%0A %7D);%0A%0A it(%22Do not trigger reset when not doing anything%22, function() %7B%0A var $show = $(%22%3Cdiv/%3E%22, %7B%22class%22: %22pat-slides%22%7D);%0A for (var i=1; i%3C=2; i++)%0A $(%22%3Cdiv/%3E%22, %7B%22class%22: %22slide%22, id: %22slide%22+i%7D).appendTo($show);%0A spyOn(pattern, %22_reset%22);%0A pattern._disable_slides($show, %5B%22slide1%22, %22slide2%22%5D);%0A expect(pattern._reset).not.toHaveBeenCalled();%0A %7D);%0A %7D);
%0A %7D);%0A%7D);
|
8f89c947b4d12ddc7222843c0fc60300df96e72f | FIX Fix test to match production code | tests/util-tests.js | tests/util-tests.js | var util = require('../js/util');
var assert = require('assert');
describe('Hello World function', function() {
it('should always fail', function() {
assert.equal(false, false);
});
it('should just say hello', function() {
var answer = util.helloWorld();
assert.equal('Hello World\n', answer);
});
}); | JavaScript | 0 | @@ -313,16 +313,35 @@
lo World
+, wie geht es euch?
%5Cn', ans
|
e0bcc0e07324fc686c98d0b0851c6ef61181feaf | Rename files from js to jsx | cli/wildcat-codemod.js | cli/wildcat-codemod.js | #! /usr/bin/env babel-node
import {echo, exit} from "shelljs";
import nomnom from "nomnom";
import fs from "fs";
import path from "path";
import {exec} from "child_process";
const transformBasePath = path.join(__dirname, "..", "transforms");
const runFirst = [
"resolve-relative-imports.js"
];
const runLast = [
"remove-stilr.js",
"convert-to-radium.js"
];
const {src, all, single} = nomnom.options({
src: {
position: 0,
help: "Source directory to run the transforms against"
},
all: {
flag: true,
abbr: "A",
help: "Run all transforms in transforms folder"
},
single: {
help: "Run single transform",
abbr: "S"
}
}).parse();
if (!src) {
echo("src option is required");
exit(1);
}
const buildCMD = (filePath, file) => {
return `jscodeshift -t ${filePath} ${file} --extensions "jsx,js"`;
};
const applyTransform = (transforms) => {
if (!transforms.length) {
return;
}
const transform = transforms.shift();
const transformFilePath = path.join(transformBasePath, transform);
const cmd = buildCMD(transformFilePath, src);
echo("Applying transform", transform);
exec(cmd, (err, stout) => {
echo(stout);
applyTransform(transforms);
});
};
if (all) {
const transforms = fs.readdirSync(transformBasePath)
.filter(fileName => fileName.match(".js$"))
.filter(filename => runFirst.indexOf(filename) === -1)
.filter(filename => runLast.indexOf(filename) === -1);
const orderedTransforms = [...runFirst, ...transforms, ...runLast];
applyTransform(orderedTransforms);
}
if (single) {
const transformFilePath = path.join(transformBasePath, single);
const cmd = buildCMD(transformFilePath, src);
exec(cmd, (err, stout) => {
echo(err);
echo(stout);
});
}
| JavaScript | 0.000007 | @@ -39,16 +39,26 @@
ho, exit
+, find, mv
%7D from %22
@@ -63,24 +63,24 @@
%22shelljs%22;%0A
-
import nomno
@@ -903,16 +903,262 @@
%22%60;%0A%7D;%0A%0A
+const renameFiles = (cb) =%3E %7B%0A echo(%22Renaming files from .jsx to .js%22);%0A%0A find(src)%0A .filter(file =%3E %7B%0A return file.match(/%5C.jsx$/);%0A %7D).map(file =%3E %7B%0A mv(file, file.replace(%22jsx%22, %22js%22));%0A %7D);%0A%7D%0A%0A
const ap
@@ -1846,16 +1846,16 @@
== -1);%0A
-
cons
@@ -1917,16 +1917,36 @@
unLast%5D;
+%0A%0A renameFiles();
%0A app
|
1e669c1c4ec970388606918c2277767a043861cf | add global _ template helper | client/helpers/i18n.js | client/helpers/i18n.js | import { Template } from 'meteor/templating'
import i18next from 'i18next'
import SystemLanguages from '../../imports/framework/Constants/SystemLanguages'
Template.registerHelper('langTag', () => i18next.language)
Template.registerHelper('getLanguages', () => SystemLanguages.allowedValues)
| JavaScript | 0.000001 | @@ -286,8 +286,81 @@
Values)%0A
+%0ATemplate.registerHelper('_', (key, options) =%3E i18next.t(key, options))%0A
|
88a77a297890a1372fc1e32c0d5a933c6fc65fb1 | Work index page accounts for no homework | client/js/workindex.js | client/js/workindex.js | function workindex() {
if(!$("#upcoming").length)
return;
var date = moment().format("YYYY-MM-DD");
// DUE TODAY
$.get("/work/"+date+"/all", function(data){
if(data){
console.log(data);
if(data.error){
console.log(data.error);
$("#due-today").hide();
return;
}
if(data.success){
$("#due-today small").text(data.hwItems.length+" items");
var courses = [];
var total = data.hwItems.length;
var doneC = 0;
data.hwItems.forEach(function(item) {
if(item.completed)
doneC += 1;
if(courses.indexOf(item.course.title) == -1)
courses.push(item.course.title);
});
$("#due-today p").html("<a data-toggle='tooltip' title='"+courses.join(', ')+"' class='undecorated' href='/work/"+date+"'><b>"+data.hwItems.length+"</b> Homework items <b>"+Math.round((doneC/total)*1000)/10+"%</b> completed.</a>");
}
}
});
// CLOSEST DAY DUE
$.get("/work/"+$("#upcoming").data("closest")+"/all", function(data){
if(data){
console.log(data);
if(data.error){
console.log(data.error);
$("#closest").hide();
return;
}
if(data.success){
$("#upcoming small").text(data.hwItems.length+" items");
var courses = [];
var total = data.hwItems.length;
var doneC = 0;
data.hwItems.forEach(function(item) {
if(item.completed)
doneC += 1;
if(courses.indexOf(item.course.title) == -1)
courses.push(item.course.title);
});
$("#upcoming p").html("<a data-toggle='tooltip' title='"+courses.join(', ')+"' class='undecorated' href='/work/"+$("#upcoming").data("closest")+"'><b>"+data.hwItems.length+"</b> Homework items <b>"+Math.round((doneC/total)*1000)/10+"%</b> completed.</a>");
}
}
});
}
| JavaScript | 0 | @@ -281,19 +281,21 @@
today%22).
-hid
+remov
e();%0A
@@ -332,32 +332,71 @@
(data.success)%7B%0A
+ if(data.hwItems.length %3E 0)%7B%0A
$(%22#due-
@@ -445,32 +445,34 @@
tems%22);%0A
+
var courses = %5B%5D
@@ -465,32 +465,34 @@
r courses = %5B%5D;%0A
+
var tota
@@ -508,32 +508,34 @@
hwItems.length;%0A
+
var done
@@ -541,32 +541,34 @@
eC = 0;%0A
+
data.hwItems.for
@@ -581,32 +581,34 @@
unction(item) %7B%0A
+
if(ite
@@ -624,32 +624,34 @@
ed)%0A
+
doneC += 1;%0A
@@ -648,32 +648,34 @@
+= 1;%0A
+
+
if(courses.index
@@ -707,32 +707,34 @@
-1)%0A
+
courses.push(ite
@@ -750,36 +750,40 @@
title);%0A
+
%7D);%0A
+
$(%22#due-
@@ -998,32 +998,93 @@
mpleted.%3C/a%3E%22);%0A
+ %7Delse%7B%0A $(%22#due-today%22).remove();%0A %7D%0A
%7D%0A %7D%0A
@@ -1301,11 +1301,13 @@
t%22).
-hid
+remov
e();
@@ -1348,32 +1348,71 @@
(data.success)%7B%0A
+ if(data.hwItems.length %3E 0)%7B%0A
$(%22#upco
@@ -1460,32 +1460,34 @@
tems%22);%0A
+
var courses = %5B%5D
@@ -1488,32 +1488,34 @@
s = %5B%5D;%0A
+
+
var total = data
@@ -1523,32 +1523,34 @@
hwItems.length;%0A
+
var done
@@ -1556,32 +1556,34 @@
eC = 0;%0A
+
data.hwItems.for
@@ -1596,32 +1596,34 @@
unction(item) %7B%0A
+
if(ite
@@ -1639,32 +1639,34 @@
ed)%0A
+
doneC += 1;%0A
@@ -1663,32 +1663,34 @@
+= 1;%0A
+
+
if(courses.index
@@ -1722,32 +1722,34 @@
-1)%0A
+
courses.push(ite
@@ -1765,36 +1765,40 @@
title);%0A
+
%7D);%0A
+
$(%22#upco
@@ -2042,24 +2042,83 @@
ted.%3C/a%3E%22);%0A
+ %7Delse%7B%0A $(%22#closest%22).remove();%0A %7D%0A
%7D%0A
|
43552829f0f2a5bd7a8bee1602a181aa19bd5419 | Fix bootstrap tour | IPython/html/static/notebook/js/tour.js | IPython/html/static/notebook/js/tour.js | //----------------------------------------------------------------------------
// Copyright (C) 2011 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// Tour of IPython Notebok UI (with Bootstrap Tour)
//============================================================================
var tour_steps = [
{
title: "Welcome to the Notebook Tour",
placement: 'bottom',
orphan: true,
content: "This tour will take 2 minutes.",
}, {
element: "#notebook_name",
title: "Filename",
placement: 'bottom',
content: "Click here to change the filename for this notebook."
}, /*{
element: "#checkpoint_status",
title: "Checkpoint Status",
placement: 'bottom',
content: "Information about the last time this notebook was saved."
},*/ {
element: $("#menus").parent(),
placement: 'bottom',
backdrop: true,
title: "Notebook Menubar",
content: "The menubar has menus for actions on the notebook, its cells, and the kernel it communicates with."
}, {
element: "#maintoolbar",
placement: 'bottom',
backdrop: true,
title: "Notebook Toolbar",
content: "The toolbar has buttons for the most common actions. Hover your mouse over each button for more information."
}, {
element: "#modal_indicator",
title: "Mode Indicator",
placement: 'bottom',
content: "The Notebook has two modes: Edit Mode and Command Mode. In this area, an indicator can appear to tell you which mode you are in.",
onShow: function(tour) { command_icon_hack(); }
}, {
element: "#modal_indicator",
title: "Command Mode",
placement: 'bottom',
onShow: function(tour) { IPython.notebook.command_mode(); command_icon_hack(); },
onNext: function(tour) { edit_mode(); },
content: "Right now you are in Command Mode, and many keyboard shortcuts are available. In this mode, no icon is displayed in the indicator area."
}, {
element: "#modal_indicator",
title: "Edit Mode",
placement: 'bottom',
onShow: function(tour) { edit_mode(); },
content: "Pressing <code>Enter</code> or clicking in the input text area of the cell switches to Edit Mode."
}, {
element: '.selected',
title: "Edit Mode",
placement: 'bottom',
onShow: function(tour) { edit_mode(); },
content: "Notice that the border around the currently active cell changed color. Typing will insert text into the currently active cell."
}, {
element: '.selected',
title: "Back to Command Mode",
placement: 'bottom',
onShow: function(tour) { IPython.notebook.command_mode(); },
content: "Pressing <code>Esc</code> or clicking outside of the input text area takes you back to Command Mode."
}, {
element: '#keyboard_shortcuts',
title: "Keyboard Shortcuts",
placement: 'bottom',
onShow: function(tour) { $('#help_menu').parent().addClass('open'); },
onHide: function(tour) { $('#help_menu').parent().removeClass('open'); },
content: "You can click here to get a list of all of the keyboard shortcuts."
}, {
element: "#kernel_indicator",
title: "Kernel Indicator",
placement: 'bottom',
onShow: function(tour) { $([IPython.events]).trigger('status_idle.Kernel');},
content: "This is the Kernel indicator. It looks like this when the Kernel is idle.",
}, {
element: "#kernel_indicator",
title: "Kernel Indicator",
placement: 'bottom',
onShow: function(tour) { $([IPython.events]).trigger('status_busy.Kernel'); },
content: "The Kernel indicator looks like this when the Kernel is busy.",
}, {
element: ".icon-stop",
placement: 'bottom',
title: "Interrupting the Kernel",
onHide: function(tour) { $([IPython.events]).trigger('status_idle.Kernel'); },
content: "To cancel a computation in progress, you can click here."
}, {
element: "#notification_kernel",
placement: 'bottom',
onShow: function(tour) { $('.icon-stop').click(); },
title: "Notification Area",
content: "Messages in response to user actions (Save, Interrupt, etc) appear here."
}, {
title: "Fin.",
placement: 'bottom',
orphan: true,
content: "This concludes the IPython Notebook User Interface Tour. Happy hacking!",
}
];
var tour_style = "<div class='popover tour'>\
<div class='arrow'></div>\
<div style='position:absolute; top:7px; right:7px'>\
<button class='btn btn-default btn-sm icon-remove' data-role='end'></button></div>\
<h3 class='popover-title'></h3>\
<div class='popover-content'></div>\
<div class='popover-navigation'>\
<button class='btn btn-default icon-step-backward' data-role='prev'></button>\
<button class='btn btn-default icon-step-forward pull-right' data-role='next'></button>\
<button id='tour-pause' class='btn btn-sm btn-default icon-pause' data-resume-text='' data-pause-text='' data-role='pause-resume'></button>\
</div>\
</div>";
var command_icon_hack = function() {$('#modal_indicator').css('min-height', 20);}
var toggle_pause_play = function () { $('#tour-pause').toggleClass('icon-pause icon-play'); };
var edit_mode = function() {
IPython.notebook.focus_cell();
IPython.notebook.edit_mode();
;}
IPython = (function (IPython) {
"use strict";
var NotebookTour = function () {
this.step_duration = 0;
this.tour_steps = tour_steps ;
this.tour_steps[0].content = "You can use the left and right arrow keys to go backwards and forwards.";
this.tour = new Tour({
//orphan: true,
storage: false, // start tour from beginning every time
//element: $("#ipython_notebook"),
debug: true,
reflex: true, // click on element to continue tour
//backdrop: true, // show dark behind popover
animation: false,
duration: this.step_duration,
onStart: function() { console.log('tour started'); },
// TODO: remove the onPause/onResume logic once pi's patch has been
// merged upstream to make this work via data-resume-class and
// data-resume-text attributes.
onPause: toggle_pause_play,
onResume: toggle_pause_play,
steps: this.tour_steps,
template: tour_style,
orphan: true
});
};
NotebookTour.prototype.start = function () {
console.log("let's start the tour");
this.tour.init();
this.tour.start();
if (this.tour.ended())
{
this.tour.restart();
}
};
// Set module variables
IPython.NotebookTour = NotebookTour;
return IPython;
}(IPython));
| JavaScript | 0.000002 | @@ -2840,32 +2840,112 @@
mand_mode(); %7D,%0A
+ onHide: function(tour) %7B $('#help_menu').parent().children('a').click(); %7D,%0A
content: %22Pr
@@ -3143,36 +3143,36 @@
'bottom',%0A on
-Show
+Hide
: function(tour)
@@ -3203,101 +3203,28 @@
t().
-addClass('open'); %7D,%0A onHide: function(tour) %7B $('#help_menu').parent().removeClass('open'
+children('a').click(
); %7D
|
57f1146ed50c5a72ff810c86ee7abb388f299e2f | fix case where the keyevent is 0 | client/keyshortcuts.js | client/keyshortcuts.js | /*
This file is part of rhizi, a collaborative knowledge graph editor.
Copyright (C) 2014-2015 Rhizi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define(['jquery', 'rz_core', 'view/selection'],
function($, rz_core, selection) {
function get_graph_view(element)
{
var dict = rz_core.root_element_id_to_graph_view;
while (undefined !== element && null !== element && undefined === dict[element.id]) {
element = element.parentElement;
}
return element !== undefined && element !== null ? dict[element.id] : undefined;
}
function install() {
document.body.onkeydown = function(e) {
var key = ((e.key && String(e.key))
|| (e.charCode && String.fromCharCode(e.charCode))
|| (e.which && String.fromCharCode(e.which))).toLowerCase(),
handled = false,
graph_view = get_graph_view(e.target);
if (e.altKey && e.ctrlKey && 'i' === key) {
$('#textanalyser').focus();
}
if (e.ctrlKey && '9' === key) {
rz_core.main_graph_view.nodes__user_visible(selection.related_nodes(), true);
handled = true;
}
if (e.ctrlKey && '0' === key) {
if (!selection.is_empty()) {
rz_core.main_graph_view.zen_mode__toggle();
}
handled = true;
}
if (e.altKey && e.ctrlKey && 'o' === key) {
search.focus();
handled = true;
}
if (e.ctrlKey && 'a' === key && e.target === document.body) {
selection.select_nodes(rz_core.main_graph.nodes());
handled = true;
}
if (e.ctrlKey && 'z' === key && e.target.nodeName !== 'INPUT') {
// TODO: rz_core.main_graph.undo();
}
// SVG elements cannot handle any keys directly - pass the key to them in this case
if (undefined !== graph_view) {
graph_view.keyboard_handler(e);
}
if (handled) {
e.preventDefault();
e.stopPropagation();
}
};
}
return {
install: install
};
}
);
| JavaScript | 0.998987 | @@ -829,16 +829,17 @@
tion'%5D,%0A
+%0A
function
@@ -865,16 +865,31 @@
ion) %7B%0A%0A
+%22use strict%22;%0A%0A
function
@@ -1275,16 +1275,20 @@
var key
+Base
= ((e.k
@@ -1442,16 +1442,51 @@
which)))
+,%0A key = (keyBase %7C%7C %22%22)
.toLower
|
dd8d9ffad7f8f1d3e1358ec2ccd28c0d0a103cd3 | test 15 | complete/6-10/index.js | complete/6-10/index.js | (function($) {
$.extend($.expr[":"], {
hasValue: function(a) {
return $(a).val() !== "";
}
});
})(jQuery);
$(function() {
$("input").keyup(function() {
var count = $("input:hasValue").length;
$("#show").html("目前有" + count + "個欄位有值").show();
count >= 3 ? $("button").show() : $("button").hide();
});
}); | JavaScript | 0 | @@ -21,44 +21,27 @@
$.ex
-tend($.expr%5B%22:%22%5D, %7B%0A
+pr.filters.
hasValue
: fu
@@ -36,17 +36,18 @@
hasValue
-:
+ =
functio
@@ -61,20 +61,16 @@
-
-
return $
@@ -95,21 +95,9 @@
- %7D%0A %7D);
+%7D
%0A%7D)(
|
bdb16301cd2ca49527ccb4dcd736cd2a724394b4 | fix path | client/src/Gulpfile.js | client/src/Gulpfile.js | 'use strict';
//should correspond to what's in package.json
var gulp = require('gulp'),
gutil = require('gulp-util'),
jslint = require('gulp-jslint'),
sass = require('gulp-sass'),
jade = require('gulp-jade'),
notify = require('gulp-notify'),
autoprefixer = require('gulp-autoprefixer'),
include = require('gulp-include'),
connect = require('gulp-connect'),
concat = require('gulp-concat'),
changed = require('gulp-changed'),
plumber = require('gulp-plumber');
gulp.task('lint', function() {
gulp.src('./js/*.js')
.pipe(jslint())
.pipe(jslint.reporter('default'));
});
gulp.task('scripts', function() {
gulp.src(['./js/main.js','./components/**/*.js'])
.pipe(plumber())
.pipe(include())
.pipe(concat('main.js'))
.pipe(gulp.dest('../build/js'));
});
gulp.task('styles', function() {
gulp.src(['./scss/style.scss','./components/**/*.scss'])
.pipe(sass({onError: function(e) { console.log(e); } }))
.pipe(autoprefixer('last 2 versions', '> 1%', 'ie 8'))
.pipe(concat('style.css'))
.pipe(gulp.dest('../build/styles'))
.pipe(connect.reload());
});
//pretty : true for non-minified html output
gulp.task('markup', function() {
gulp.src(['./templates/pages/**/*.jade','./templates/*.jade'])
.pipe(plumber())
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('../build/html'))
.pipe(connect.reload());
});
gulp.task('server', function() {
connect.server({
livereload: true,
root: '../build'
});
});
gulp.task('copy-data', function() {
gulp.src('./data/*.json')
.pipe(changed('./data/*.json'))
.pipe(gulp.dest('../build/data'));
});
gulp.task('copy-lib', function() {
gulp.src('./js/lib/*.js')
.pipe(changed('./js/lib/*.js'))
.pipe(gulp.dest('../build/js/lib'));
});
gulp.task('copy-media', function() {
gulp.src('./media/**/*')
.pipe(changed('./media/**/*'))
.pipe(gulp.dest('../build/media'));
});
gulp.task('watch', function() {
gulp.watch('./components/**/*.jade', ['markup']);
gulp.watch('./templates/**/*.jade', ['markup']);
gulp.watch('./templates/pages/index.jade', ['markup']);
gulp.watch('./templates/pages/**/*.jade', ['markup']);
gulp.watch('./templates/layouts/*.jade', ['markup']);
//style sheets
gulp.watch('./scss/*.scss', ['styles']);
gulp.watch('./components/**/*.scss', ['styles']);
//plain old copy stuff over
gulp.watch('./scripts/lib/*.js', ['copy-lib']);
gulp.watch('./data/*.json', ['copy-data']);
//scripts
gulp.watch('./js/*.js', ['scripts']);
gulp.watch('./components/**/*.js', ['scripts']);
gulp.watch('./templates/pages/**/*.js', ['scripts']);
});
gulp.task('default', ['scripts', 'styles', 'markup', 'server', 'copy-data', 'copy-lib', 'copy-media', 'watch' ]);
| JavaScript | 0.000017 | @@ -2441,22 +2441,17 @@
atch('./
-script
+j
s/lib/*.
|
05a07c5823da70e151efe51cfa976fbccdfaa020 | Remove versionComparator util | client/src/js/utils.js | client/src/js/utils.js | import Numeral from "numeral";
import { sampleSize, get, startCase, capitalize } from "lodash";
export const taskDisplayNames = {
nuvs: "NuVs",
pathoscope_bowtie: "PathoscopeBowtie",
pathoscope_snap: "PathoscopeSNAP"
};
export const getTaskDisplayName = (taskPrefix) => get(taskDisplayNames, taskPrefix, startCase(taskPrefix));
export const numberDictionary = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine"
};
const alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
export const createRandomString = (length=8) => {
return sampleSize(alphanumeric, length).join("")
};
export const numberToWord = (number) => numberDictionary[Number(number)] || number;
export const byteSize = bytes => Numeral(bytes).format("0.0 b");
export const toScientificNotation = (number) => {
if (number < 0.01 || number > 1000) {
const split = number.toExponential().split("e");
const exponent = split[1].replace("+", "");
return Numeral(split[0]).format("0.00") + "ₑ" + exponent;
}
return Numeral(number).format("0.000");
};
export const formatIsolateName = (isolate) => {
if (
isolate.source_type && isolate.source_type !== "unknown" ||
isolate.sourceType && isolate.sourceType !== "unknown"
) {
return (
capitalize(isolate.source_type || isolate.sourceType) + " "
+ (isolate.source_name || isolate.sourceName)
);
}
return "Unnamed";
};
export const followDownload = (path) => {
const a = document.createElement("A");
a.href = path;
a.download = path.substr(path.lastIndexOf("/") + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
export const followDynamicDownload = (filename, text) => {
const a = document.createElement("a");
a.href = `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`;
a.download = filename;
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
export const versionComparator = (a, b) => {
let splitA = a.replace("v", "").split("-")[0];
let splitB = b.replace("v", "").split("-")[0];
if (splitA === splitB) {
return 0;
}
splitA = splitA.split(".");
splitB = splitB.split(".");
for (let i = 0; i < 3; i++) {
if (splitA[i] > splitB[i]) {
return 1;
}
if (splitA[i] < splitB[i]) {
return -1;
}
}
throw("Could not compare versions");
};
| JavaScript | 0 | @@ -2152,497 +2152,4 @@
%0A%7D;%0A
-%0Aexport const versionComparator = (a, b) =%3E %7B%0A let splitA = a.replace(%22v%22, %22%22).split(%22-%22)%5B0%5D;%0A let splitB = b.replace(%22v%22, %22%22).split(%22-%22)%5B0%5D;%0A%0A if (splitA === splitB) %7B%0A return 0;%0A %7D%0A%0A splitA = splitA.split(%22.%22);%0A splitB = splitB.split(%22.%22);%0A%0A for (let i = 0; i %3C 3; i++) %7B%0A if (splitA%5Bi%5D %3E splitB%5Bi%5D) %7B%0A return 1;%0A %7D%0A%0A if (splitA%5Bi%5D %3C splitB%5Bi%5D) %7B%0A return -1;%0A %7D%0A %7D%0A%0A throw(%22Could not compare versions%22);%0A%7D;%0A
|
f344cb2aea5c3d435519c3cd2a8b541ef733a60a | Move propTypes inside component | components/ChatList.js | components/ChatList.js | import React, { Component } from 'react';
import { graphql, gql } from 'react-apollo'
import moment from 'moment'
import { N_CHATROOMS_FIRSTLOAD, N_CHATROOMS_LOADMORE } from '../constants'
import Page from '../layouts/main'
import ChatListItem from './ChatListItem'
import Colors from '../utils/Colors';
// Change number of chats first load/ loadmore in constants.js
class ChatList extends Component {
render() {
const { loading, error, allChatrooms, _allChatroomsMeta, onClickChatroom, loadMoreEntries, noMore, currentRoomId } = this.props;
if (loading) return <div>Loading</div>
if (error) return <div>Error: {error}</div>
if (allChatrooms) {
if (allChatrooms.length === 0) return <div>No chats yet 😂</div>
return (
<div>
<ul style={{ listStyle: 'none', padding: 0 }}>
{allChatrooms.map((chat, index) => {
return (
<div key={chat.id}>
<li className="main" onClick={() => onClickChatroom(chat.id)}>
<ChatListItem
id={chat.id}
title={chat.title}
count={chat._messagesMeta.count}
createdAt={chat.createdAt}
active={chat.id === currentRoomId}
/>
</li>
<style jsx>{`
.main {
cursor: pointer;
background-color: white;
}
.main:hover {
background-color: ${Colors.lightGrey};
}
`}</style>
</div>
)
})}
</ul>
{!noMore ?
<div onClick={loadMoreEntries} style={{ color: 'blue', textAlign: 'center', cursor: 'pointer' }}>load more</div>
:
<div style={{ color: 'gray', textAlign: 'center', fontSize: '14px', marginTop: '20px' }}>{_allChatroomsMeta.count} chats</div>}
</div>
)
}
return <div>Something wrong, this shouldn't show.</div>
}
}
export const FIRSTLOAD_CHATROOMS_QUERY = gql`
query allChatrooms {
allChatrooms(
first: ${N_CHATROOMS_FIRSTLOAD},
orderBy: createdAt_DESC,
) {
id
title
createdAt
_messagesMeta {
count
}
}
_allChatroomsMeta {
count
}
}
`
const MORE_CHATROOMS_QUERY = gql`
query moreChatrooms($after: String!) {
allChatrooms(
first: ${N_CHATROOMS_LOADMORE},
after: $after,
orderBy: createdAt_DESC,
) {
id
title
createdAt
_messagesMeta {
count
}
}
}
`
ChatList.propTypes = {
onClickChatroom: React.PropTypes.func.isRequired,
};
export default graphql(FIRSTLOAD_CHATROOMS_QUERY, {
props({ data: { loading, error, allChatrooms, _allChatroomsMeta, fetchMore } }) {
// Transform props
// ---------------
// The return props will be the available props.
// (this is called everytime data is changed, so allChatrooms might be undefined at first load)
let cursor;
let noMore = false;
if (allChatrooms) {
cursor = allChatrooms.length > 0 ? allChatrooms[allChatrooms.length-1].id : null
noMore = allChatrooms.length === _allChatroomsMeta.count
}
return {
loading,
allChatrooms,
_allChatroomsMeta,
error,
noMore: noMore,
loadMoreEntries: () => {
return fetchMore({
query: MORE_CHATROOMS_QUERY,
variables: {
after: cursor,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousChatrooms = previousResult.allChatrooms
const newChatrooms = fetchMoreResult.allChatrooms
const count = newChatrooms.length
const newCursor = noMore ? fetchMoreResult.allChatrooms[count - 1].id : cursor
return {
cursor: newCursor,
allChatrooms: [...previousChatrooms, ...newChatrooms],
_allChatroomsMeta: previousChatrooms._allChatroomsMeta, // use static count of chatrooms for now
}
}
})
}
}
}
})(ChatList)
| JavaScript | 0 | @@ -399,16 +399,99 @@
nent %7B%0A%0A
+ static propTypes = %7B%0A onClickChatroom: React.PropTypes.func.isRequired,%0A %7D;%0A%0A
render
@@ -2797,88 +2797,8 @@
%7D%0A%60%0A
-%0AChatList.propTypes = %7B%0A onClickChatroom: React.PropTypes.func.isRequired,%0A%7D;%0A%0A
expo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.