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
|
---|---|---|---|---|---|---|---|
e8593945b0aeb79e1ecc3ed2a0d83bbd3227a091 | Update js | folke-ko-localization.js | folke-ko-localization.js | define(["require", "exports", "res/default", "knockout"], function (require, exports, default_1, ko) {
exports.text = default_1["default"];
exports.keys = {};
for (var key in exports.text) {
var mod = exports.text[key];
for (var sub in mod) {
var line = mod[sub];
exports.keys[key + '.' + sub] = line;
}
}
// A binding handler that set the text content with a format ({n} is replaced by the nth parameter)
ko.bindingHandlers['locf'] = {
update: function (element, valueAccessor) {
var parameters = valueAccessor();
var text = exports.keys[parameters[0]];
for (var i = 1; i < parameters.length; i++) {
text = text.replace('{' + (i - 1) + '}', ko.unwrap(parameters[i]));
}
element.innerHTML = text;
}
};
// A binding handler to set attribute values
ko.bindingHandlers['loca'] = {
update: function (element, valueAccessor) {
var parameters = valueAccessor();
for (var key in parameters) {
var value = parameters[key];
element.setAttribute(key, exports.keys[value]);
}
}
};
ko.bindingProvider.instance['preprocessNode'] = function (node) {
if (node.nodeType === node.ELEMENT_NODE) {
var element = node;
for (var i = 0; i < element.attributes.length; i++) {
var attribute = element.attributes[i];
var value = attribute.value;
if (value.indexOf("{{") == 0) {
value = value.substr(2, value.length - 4);
element.removeAttribute(attribute.name);
if (element.hasAttribute('data-bind')) {
element.attributes.getNamedItem('data-bind').value += ',loca: {' + attribute.name + ':"' + value + '"}';
}
else {
element.setAttribute('data-bind', 'loca: {' + attribute.name + ':"' + value + '"}');
}
}
}
}
if (node.nodeType === 3) {
if (node.nodeValue && node.nodeValue.indexOf('{{nohtml|') !== -1) {
node.nodeValue = node.nodeValue.replace(/{{nohtml\|(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
return [node];
}
else if (node.nodeValue && node.nodeValue.indexOf('{{') !== -1) {
if (node.nodeValue.indexOf(',') !== -1) {
var newElement = document.createElement('span');
var value = node.nodeValue.match(/{{(.*?)}}/)[1];
var parameters = value.split(',');
parameters[0] = "'" + parameters[0] + "'";
newElement.setAttribute('data-bind', 'locf: [' + parameters.join(',') + ']');
node.parentNode.replaceChild(newElement, node);
return [newElement];
}
else {
var newElement = document.createElement('span');
newElement.innerHTML = node.nodeValue.replace(/{{(.*?)}}/, function (match, id) { return exports.keys[id] || id; });
node.parentNode.replaceChild(newElement, node);
return [newElement];
}
}
}
};
});
| JavaScript | 0 | @@ -128,19 +128,16 @@
lt_1
-%5B%22
+.
default
-%22%5D
;%0A
|
f871a57e5803109dd3d573c66e07b722ec052f69 | Improve order of operations | src/notificationStack.js | src/notificationStack.js | /* eslint-disable react/jsx-no-bind */
import React, { PropTypes } from 'react';
import StackedNotification from './stackedNotification';
function defaultStyleFactory(index, style) {
return Object.assign(
{},
style,
{ bottom: `${2 + index * 4}rem` }
);
}
/**
* The notification list does not have any state, so use a
* pure function here. It just needs to return the stacked array
* of notification components.
*/
const NotificationStack = props => (
<div className="notification-list">
{props.notifications.map((notification, index) => {
const dismissAfter = notification.dismissAfter || props.dismissAfter;
const isLast = index === 0 && props.notifications.length === 1;
const dismissNow = isLast || !props.dismissInOrder;
const barStyle = props.barStyleFactory(index, notification.barStyle);
const activeBarStyle = props.activeBarStyleFactory(index, notification.activeBarStyle);
return (
<StackedNotification
{...notification}
key={notification.key}
isLast={isLast}
action={notification.action || props.action}
dismissAfter={dismissNow ? dismissAfter : dismissAfter + (index * 1000)}
onDismiss={props.onDismiss.bind(this, notification)}
activeBarStyle={activeBarStyle}
barStyle={barStyle}
/>
);
})}
</div>
);
/* eslint-disable react/no-unused-prop-types, react/forbid-prop-types */
NotificationStack.propTypes = {
activeBarStyleFactory: PropTypes.func,
barStyleFactory: PropTypes.func,
dismissInOrder: PropTypes.bool.isRequired,
notifications: PropTypes.array.isRequired,
onDismiss: PropTypes.func.isRequired
};
NotificationStack.defaultProps = {
activeBarStyleFactory: defaultStyleFactory,
barStyleFactory: defaultStyleFactory,
dismissInOrder: true,
dismissAfter: 1000
};
/* eslint-enable no-alert, no-console */
export default NotificationStack;
| JavaScript | 0.028775 | @@ -241,16 +241,17 @@
%60$%7B2 +
+(
index *
@@ -251,16 +251,17 @@
ndex * 4
+)
%7Drem%60 %7D%0A
|
566dbc6654775877fb170a1559b646a384593850 | change velocity in character | src/objects/Character.js | src/objects/Character.js | class Character extends Phaser.Sprite {
constructor(game, x, y, key, frame) {
super(game, x, y, key, frame);
//Enable physics on the player
game.physics.arcade.enable(this);
this.body.bounce.x = this.body.bounce.y = 0;
this.cursor = game.input.keyboard.createCursorKeys();
this.body.gravity.y = 500;
this.direction = 1;
}
update() {
if (this.cursor.left.isDown) {
this.body.velocity.x = -200;
this.direction = -1;
}
else if (this.cursor.right.isDown) {
this.body.velocity.x = 200;
this.direction = 1;
}
if (this.cursor.up.isDown) {
this.body.velocity.y = -270;
}
}
isDeath() {
if (!this.body) {
return false;
}
}
}
export default Character; | JavaScript | 0.000008 | @@ -649,9 +649,85 @@
= -2
-7
+00;%0A %7D else if (this.cursor.down.isDown) %7B%0A this.body.velocity.y = 20
0;%0A
|
966cb6496ae308348d6da14c008accedd68fe804 | Remove unused rq.createFunction function | src/api.js | src/api.js | /*
* This file contains the rq Javascript API implementation. It's used by for example `prelude.js`.
*/
/**
* The `rq` namespace, containing the `rq` API.
*
* @namespace
*/
var rq = rq || {};
/**
* The type of `this` for all of the rq stream processing functions (defined for example in
* `prelude.js`)
*
* @param {rq.Logger} log The logger to use in this context.
* @constructor
*/
rq.Context = function Context(log) {
/**
* A logger object that can be used to send log messages to the user.
*
* @type {rq.Logger}
*/
this.log = log; // Writable because Process overwrites it.
/**
* The current value from the input value stream. Will be `undefined` until {@link
* rq.Context#pull} has been called and returned `true`.
*/
this.value = undefined;
/**
* Pulls the next value in the input value stream, storing it into `this.value`.
*
* @return {boolean} Whether there was another value in the stream.
*/
this.pull = function* pull() {
var result = yield {type: 'await'};
if (result.hasNext) {
this.value = result.next;
return true;
} else {
return false;
}
};
/**
* Pushes a value into the output value stream.
*
* @param {*} value The value to push.
*/
this.push = function* push(value) {
yield {type: 'emit', value: value};
};
/**
* Collects all values from the input stream, consuming it fully.
*
* @returns {Array} The values that were in the input stream.
*/
this.collect = function* collect() {
var result = [];
while (yield* this.pull()) {
result.push(this.value);
}
return result;
};
/**
* Spreads the specified values into the output stream, pushing each of them in order.
*
* @param {Array} values The values to push to the output stream.
*/
this.spread = function* spread(values) {
for (var i = 0; i < values.length; i++) {
yield* this.push(values[i]);
}
};
Object.seal(this);
};
/**
* A logger that can be used to log messages.
*
* @param {string} name The name of the logger.
* @constructor
*/
rq.Logger = function Logger(name) {
/**
* Logs something at the trace level.
*
* @param {...*} args Arbitrary values to log.
*/
this.trace = function trace(args) {
rq.native.log(0, name, ...arguments);
};
/**
* Logs something at the debug level.
*
* @param {...*} args Arbitrary values to log.
*/
this.debug = function debug(args) {
rq.native.log(1, name, ...arguments);
};
/**
* Logs something at the info level.
*
* @param {...*} args Arbitrary values to log.
*/
this.info = function info(args) {
rq.native.log(2, name, ...arguments);
};
/**
* Logs something at the warning level.
*
* @param {...*} args Arbitrary values to log.
*/
this.warn = function warn(args) {
rq.native.log(3, name, ...arguments);
};
/**
* Logs something at the error level.
*
* @param {...*} args Arbitrary values to log.
*/
this.error = function error(args) {
rq.native.log(4, name, ...arguments);
};
Object.freeze(this);
};
/**
* Utility functions used by many rq processes.
*
* @namespace
*/
rq.util = {};
/**
* The log object used by this module.
*
* @type {rq.Logger}
*/
Object.defineProperty(rq.util, 'log', {value: new rq.Logger('rq.util')});
/**
* A lens that can be used to interact with some encapsulated value.
*
* @param {function(): *} get The getter for the value.
* @param {function(*)} set The setter for the value.
* @constructor
*/
rq.util.Lens = function Lens(get, set) {
/**
* Gets the encapsulated value.
* @return {*} The current value.
*/
this.get = get;
/**
* Sets the encapsulated value.
* @param {*} value The new value to set.
*/
this.set = set;
Object.freeze(this);
};
/**
* Evaluates a path into an object, returning an array of `Lens`es with the targets of the path.
*
* The supported path syntaxes include [JSONPath][1] and [JSON pointers][2].
*
* [1]: https://github.com/dchester/jsonpath
* [2]: https://tools.ietf.org/html/rfc6901
*
* @param {(Object|Array)} obj The object to traverse.
* @param {string} path The path into the object.
* @return {Array<rq.util.Lens>} A lens that can be used to manipulate the targeted values.
*/
rq.util.path = function path(obj, path) {
if (typeof path === 'string' && path.length > 0) {
if (path.charAt(0) === '/') {
// Assume it's a JSON pointer
var elems = path.substring(1).split(/\//).map(function unescape(elem) {
return elem.replace(/~1/g, '/').replace(/~2/g, '~');
});
if (elems.length === 0) {
throw new Error(`Path projection is empty: ${JSON.stringify(path)}`);
}
var last = elems.pop();
elems.forEach(function(elem) {
if (obj && elem in obj) {
obj = obj[elem];
} else {
obj = undefined;
}
});
if (obj && last in obj) {
return [new rq.util.Lens(function get() {
return obj[last];
}, function set(v) {
obj[last] = v;
})];
} else {
return [];
}
} else if (path.charAt(0) == '$') {
// Assume it's a JSON path
var jp = require('jsonpath');
return jp.paths(obj, path).map(function(innerPath) {
return new rq.util.Lens(function get() {
return jp.value(obj, innerPath);
}, function set(v) {
jp.value(obj, innerPath, v);
});
});
} else {
throw new Error(`Unrecognized path syntax: ${JSON.stringify(path)}`);
}
} else {
throw new Error(`Cannot be used as a path: ${JSON.stringify(path)}`);
}
};
Object.freeze(rq.util);
/**
* An rq process that encapsulates a coroutine. It's probably not a good idea to construct an
* instance of this manually.
*
* @constructor
*/
rq.Process = function Process(fn) {
var ctx = new rq.Context(new rq.Logger(fn.name));
var generator = undefined;
this.resume = function resume(params) {
switch (params.type) {
case 'start': {
// Replace logger by more detailed one
var name = `${fn.name}(${params.args.map(JSON.stringify).join(', ')})`;
ctx.log = new rq.Logger(name);
generator = fn.apply(ctx, params.args);
break;
}
case 'pending': {
return generator.next().value;
}
case 'await': {
return generator.next(params).value;
}
default:
throw Error(`Unrecognized resume type ${params.type}`);
}
};
Object.freeze(this);
};
rq.createFunction = function createFunction(args, body) {
return require('minieval').createFunction(body, args);
};
Object.freeze(rq);
| JavaScript | 0.000006 | @@ -6569,127 +6569,8 @@
%7D;%0A%0A
-rq.createFunction = function createFunction(args, body) %7B%0A return require('minieval').createFunction(body, args);%0A%7D;%0A%0A
Obje
|
f4ecd0d648a10cabc7cc28868e17523a59485790 | add missing flow annotation to api._get | src/api.js | src/api.js | /* @flow */
import https from 'https'
import Debug from 'debug'
const debug = Debug('crypto-exchange-api:api')
export class API {
/**
* Store and check per-second rate limits
*
* @private
*/
_checkRateLimit (ts: number, limit: number, rates: number[]) {
rates.push(ts)
let edge = rates.find((d) => ts - 1000 < d)
if (edge) rates.splice(0, rates.indexOf(edge))
return rates.length <= limit
}
/**
* Parse https.request responses
*
* @private
*/
_resJsonParse (response: { statusCode: number, data: string }) {
let resObj
try {
resObj = JSON.parse(response.data)
debug('Successful response %o', response)
} catch (e) {
debug('Response error %o', response)
throw new Error(`HTTP ${response.statusCode} Returned error: ${response.data}`)
}
if (resObj.error) {
debug('Response error %o', response)
throw new Error(`HTTP ${response.statusCode} Returned error: ${resObj.error}`)
}
return resObj
}
/**
* Execute https.request(s)
*
* @private
*/
_httpsRequest (options: {}, body?: string) {
return new Promise((resolve, reject) => {
debug(`sending https request with body: %o and options:\n%O`, body, options)
let req : https.ClientRequest = https.request(options, (res: https.IncomingMessage) => {
let rawData: string = ''
res.on('data', (chunk) => { rawData += chunk })
res.on('end', () => {
return resolve({ statusCode: res.statusCode, data: rawData })
})
})
req.on('error', reject)
if (body) {
req.write(body)
}
req.end()
})
}
}
| JavaScript | 0.000001 | @@ -1108,16 +1108,28 @@
string)
+: Promise%3C*%3E
%7B%0A r
|
165330ee29baee2dae25537a411c2858c73b4a68 | test new api | src/api.js | src/api.js | const axios = require('axios')
let { repo, sha, ci } = require('ci-env')
const { warn } = require('prettycli')
const token = require('./token')
const debug = require('./debug')
const url = 'https://bundlesize-store.now.sh/values'
let enabled = false
if (repo && token) enabled = true
else if (ci) {
warn(`github token not found
You are missing out on some cool features.
Read more here: https://github.com/siddharthkp/bundlesize#2-build-status
`)
}
debug('api enabled', enabled)
const get = () => {
debug('fetching values', '...')
repo = repo.replace(/\./g, '_')
return axios
.get(`${url}?repo=${repo}&token=${token}`)
.then(response => {
const values = {}
if (response && response.data && response.data.length) {
response.data.map(file => (values[file.path] = file.size))
}
debug('master values', values)
return values
})
.catch(error => {
debug('fetching failed', error.response.data)
console.log(error)
})
}
const set = values => {
if (repo && token) {
repo = repo.replace(/\./g, '_')
debug('saving values')
axios
.post(url, { repo, token, sha, values })
.catch(error => console.log(error))
}
}
const api = { enabled, set, get }
module.exports = api
| JavaScript | 0 | @@ -209,16 +209,27 @@
ze-store
+-oeurqgwjlz
.now.sh/
|
c48cc3c85a4d653fecb5c08f96f65939ae815c33 | Handle errors during preview | forum/static/js/forum.js | forum/static/js/forum.js | $(function(){
$('.dropdown-submenu a.dropdown-toggle').click(function(e){
$(this).next('ul').toggle();
$(this).parent().toggleClass('submenu-open');
e.stopPropagation();
e.preventDefault();
});
$('textarea[data-provide=markdown]').markdown({
onPreview: function (e, previewContainer) {
$.ajax({ method: "POST", url: "/forum/preview", data: $('#post-form').serialize() })
.then(function (result) {
previewContainer.html(result);
});
return "Formatting...";
}
});
});
| JavaScript | 0 | @@ -268,17 +268,16 @@
function
-
(e, prev
@@ -301,36 +301,13 @@
%09%09$.
-ajax(%7B method: %22POST%22, url:
+post(
%22/fo
@@ -323,14 +323,8 @@
ew%22,
- data:
$('
@@ -351,20 +351,18 @@
ze()
- %7D
)%0A%09%09%09.
-then
+done
(fun
@@ -366,17 +366,16 @@
function
-
(result)
@@ -412,16 +412,153 @@
esult);%0A
+%09%09%09%7D)%0A%09%09%09.fail(function() %7B%0A%09%09%09%09previewContainer.text('Oops! Something went wrong; preview is not available at the moment. Sorry. :-(');%0A
%09%09%09%7D);%0A%0A
|
27a01ed63f452131aad2aa09204af84d2ef6fe19 | Fix the coffee task | tasks/coffee.js | tasks/coffee.js | module.exports = function (grunt) {
var path = require('path');
var fs = require('fs');
var coffee = require('coffee-script');
grunt.registerMultiTask('coffee', 'Compile CoffeeScript files', function () {
var src = this.data.src,
dest = this.data.dest;
var filepaths = grunt.file.expandFiles(path.join(src, '/**/*.coffee'));
grunt.file.clearRequireCache(filepaths);
grunt.file.expandFiles(path.join(dest, '/**/*.js')).forEach(function (filepath) {
srcpath = filepath.replace(dest, src).replace(/\.js$/, '.coffee');
if (!fs.existsSync(srcpath)) {
grunt.helper('coffee-delete', filepath);
}
});
filepaths.forEach(function (filepath) {
destpath = filepath.replace(src, dest).replace(/\.coffee$/, '.js');
grunt.helper('coffee', filepath, destpath);
});
if (grunt.task.current.errorCount) {
return false;
}
grunt.log.ok('Compiling complete');
});
grunt.registerHelper('coffee-delete', function (filepath) {
if (fs.existsSync(filepath)) {
fs.unlinkSync(filepath);
grunt.log.writeln('Deleted "' + filepath + '"');
}
});
grunt.registerHelper('coffee', function (src, dest) {
options = grunt.config.get('options.coffee') || {};
if (options.bare !== false) {
options.bare = true;
}
try {
var js = coffee.compile(grunt.file.read(src), options);
grunt.file.write(dest, js);
grunt.log.writeln('Compiled "' + src + '" -> "' + dest + '"');
} catch (e) {
grunt.log.error("Error in " + src + ":\n" + e);
return false;
}
});
};
| JavaScript | 0.999999 | @@ -1257,25 +1257,20 @@
%7B%7D;%0A
-%0A
-if (
options.
bare
@@ -1269,58 +1269,23 @@
ons.
-bare !== false) %7B%0A options.bare = true;%0A %7D
+filename = src;
%0A%0A
|
a212dba8bb07f8bfe516ba6b53c9e02ba12b8f1f | Enable the additional validation methods. | src/patterns/validate.js | src/patterns/validate.js | define([
'require',
'../../lib/jquery.validate',
'../logging'
], function(require) {
var log = require('../logging').getLogger('validate');
var init = function($el, opts) {
var rules = $el.find('[data-required-if]').toArray().reduce(function(acc, el) {
var $el = $(el),
id = $el.attr('id');
if (!id) {
log.error('Element needs id, skipping:', $el);
return acc;
}
acc[id] = {required: $el.data('required-if')};
return acc;
}, {});
log.debug('rules:', rules);
// ATTENTION: adding the debug option to validate, disables
// form submission
$el.validate({rules: rules});
return $el;
};
var pattern = {
markup_trigger: 'form.validate',
register_jquery_plugin: false,
init: init
};
return pattern;
}); | JavaScript | 0 | @@ -46,24 +46,88 @@
.validate',%0A
+ '../../lib/jquery-validation-1.9.0/additional-methods.min',%0A
'../logg
@@ -979,8 +979,9 @@
ern;%0A%7D);
+%0A
|
d512bfc77467b5762900db9776e10707b431deb2 | fix indentation | tasks/cssmin.js | tasks/cssmin.js | /*
* grunt-contrib-cssmin
* http://gruntjs.com/
*
* Copyright (c) 2012 Tim Branyen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var helper = require('grunt-lib-contrib').init(grunt);
var path = require('path');
grunt.registerMultiTask('cssmin', 'Minify CSS files', function() {
var options = this.options({
report: false
});
this.files.forEach(function(f) {
var valid = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
});
var max = valid
.map(grunt.file.read)
.join(grunt.util.normalizelf(grunt.util.linefeed));
var min = valid.map(function(f) {
options.relativeTo = path.dirname(f);
return minifyCSS(grunt.file.read(f), options);
})
.join('');
if (min.length < 1) {
grunt.log.warn('Destination not written because minified CSS was empty.');
} else {
if ( options.banner ) {
min = options.banner + grunt.util.linefeed + min;
}
grunt.file.write(f.dest, min);
grunt.log.writeln('File ' + f.dest + ' created.');
if(options.report) {
helper.minMaxInfo(min, max, options.report);
}
}
});
});
var minifyCSS = function(source, options) {
try {
return require('clean-css').process(source, options);
} catch (e) {
grunt.log.error(e);
grunt.fail.warn('css minification failed.');
}
};
};
| JavaScript | 0.000358 | @@ -790,18 +790,16 @@
d%0A
-
.map(gru
@@ -812,18 +812,16 @@
e.read)%0A
-
.j
|
473b2f18ae38264c55a5ecd54926b62a6064a2c4 | enhance code style | tasks/deploy.js | tasks/deploy.js | module.exports = function(grunt) {
'use strict';
grunt.config.merge({
concat: {
ui: {
src: ['dist/**/*.js'],
dest: 'dist/caoutchouc-min.js',
},
},
});
grunt.config.merge({
clean: {
js: {
src: ['dist/**/*', '!dist/skin', '!dist/caoutchouc-min.js']
}
}
});
grunt.config.merge({
requirejs: {
ui: {
options: {
//optimize: 'none',
preserveLicenseComments: false,
baseUrl: 'Source',
//appDir: 'Source',
dir: 'dist',
paths: {
UI: './'
},
/**
* @ignore
*/
onBuildWrite: function(name, path, contents) {
//console.log('Writing: ' + name);
/*if (name === 'UI') {
contents = contents.replace('define(', "define('" + name + "', ");
} else {
contents = contents.replace('define(', "define('UI/" + name + "', ");
}*/
contents = contents.replace('define(', "define('UI/" + name + "', ");
return contents;
},
}
}
}
});
grunt.registerTask('deploy', ['requirejs:ui', 'concat:ui', 'clean:js', 'less']);
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-clean');
};
| JavaScript | 0.000001 | @@ -148,17 +148,16 @@
-min.js'
-,
%0A%09%09%09%7D,%0A%09
|
99e4e616cec2a57e5a3c7fb57801dc83cb625f13 | Copy in vendored js dependencies | tasks/deploy.js | tasks/deploy.js | const gulp = require('gulp');
const runSequence = require('run-sequence');
const {spawn} = require('child_process');
gulp.task('push', (callback) => {
spawn('cf', ['push'], {stdio: 'inherit', env: process.env}).once('close', callback);
});
gulp.task('copy-staticfile', () => {
return gulp.src('Staticfile').pipe(gulp.dest('public'));
});
gulp.task('deploy', (done) => {
const {NODE_ENV: env} = process.env;
process.env.NODE_ENV = 'production';
runSequence('assets', 'copy-staticfile', 'push', () => {
process.env.NODE_ENV = env;
done();
});
});
| JavaScript | 0 | @@ -330,32 +330,130 @@
public'));%0A%7D);%0A%0A
+gulp.task('copy-vendor', () =%3E %7B%0A return gulp.src('vendor/*.js').pipe(gulp.dest('public'));%0A%7D);%0A%0A
gulp.task('deplo
@@ -588,16 +588,31 @@
icfile',
+ 'copy-vendor',
'push',
|
5900f2c85217c281a73c7f89e05ffd68032f7e2c | rename eslint:validate | tasks/eslint.js | tasks/eslint.js | 'use strict';
// Eslint validation
// For more information about Grunt ESLint, have a look at https://www.npmjs.com/package/grunt-eslint
module.exports = {
// Validate the whole project
validate: {
src: [
'index.js',
'conf.js',
'Gruntfile.js',
'install.js',
'flightplan.js',
'tasks/**/*.js',
'tests/**/*.js',
'app/**/*.js',
'migrations/**/*.js'
]
}
};
| JavaScript | 0.000281 | @@ -185,23 +185,21 @@
oject%0A
-validat
+manag
e: %7B%0A
|
cf962a3ed947e3de1315af7eb34adb30b7687c17 | update usemin | tasks/usemin.js | tasks/usemin.js | import gulp from 'gulp';
import config from '../config';
import plumber from 'gulp-plumber';
import flatmap from 'gulp-flatmap';
import usemin from 'gulp-usemin';
import cssnano from 'gulp-cssnano';
import uglify from 'gulp-uglify';
import gulpif from 'gulp-if';
import notify from 'gulp-notify';
import htmlmin from 'gulp-htmlmin';
gulp.task('usemin', () => {
return gulp
.src(`${config.html.build}/**/*.html`)
.pipe(
flatmap((stream) => {
return stream
.pipe(
plumber({
errorHandler: notify.onError('Error: <%= error.message %>'),
})
)
.pipe(
gulpif(
config.production,
usemin({
// see https://www.npmjs.com/package/gulp-usemin
css: [cssnano()],
js: [uglify()],
html: [htmlmin({
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
keepClosingSlash: true,
minifyCSS: true,
minifyJS: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
})],
})
)
)
.pipe(gulp.dest(config.html.build));
})
)
.pipe(
gulpif(
config.enable.notify,
notify({
title: config.notify.title,
message: 'Usemin task complete',
onLast: true,
})
)
);
});
| JavaScript | 0 | @@ -1205,27 +1205,28 @@
buteQuotes:
-tru
+fals
e,%0A
|
7d87ab75c3539fba8c78c2d39af4e82bc6a9b16e | change name of autocomplete suggestion class | src/pipeline/Response.js | src/pipeline/Response.js | import React from 'react'
import State from './state'
import { Results as RawResults } from 'sajari-react/ui/Results'
const getState = (namespace) => {
return {
searchResponse: State.ns(namespace).getResults() || {}
}
};
class Response extends React.Component {
constructor(props) {
super(props)
this.state = getState(this.props.namespace)
this.onValuesChange = this.onValuesChange.bind(this)
}
_state() {
return State.ns(this.props.namespace);
}
componentDidMount() {
this._state().registerResultsListener(this.onValuesChange);
}
componentWillUnmount() {
this._state().unregisterResultsListener(this.onValuesChange);
}
onValuesChange() {
this.setState(this._state().getResults() || {});
}
render() {
const { children } = this.props;
const error = this._state().getError();
const time = this.state.time;
let values = this._state().getValues();
const text = values["q.used"] || values["q"]
if (!text || !time && !error) {
return null;
}
return (
<div>
{React.Children.map(children, c => {
if (c === null) {
return c
}
return React.cloneElement(c, {
...this.state,
error
});
})}
</div>
);
}
}
class Results extends React.Component {
render() {
if (this.props.results || this.props.error) {
return (
<RawResults
data={{ searchResponse: this.props }}
resultClicked={State.ns(this.props.namespace).resultClicked}
/>
);
}
return null;
}
}
Results.defaultProps = {
namespace: 'default'
}
Response.defaultProps = {
namespace: 'default',
}
function queryTimeToSeconds(t="") {
const parseAndFormat = x => (parseFloat(t) / x).toFixed(5) + 's'
if (t.indexOf('ms') >= 0) {
return parseAndFormat(1000)
}
if (t.indexOf('µs') >= 0) {
return parseAndFormat(1000000)
}
return t
}
class Summary extends React.Component {
constructor(props) {
super(props)
this.onValuesChange = this.onValuesChange.bind(this)
this._state = this._state.bind(this)
}
_state() {
return State.ns(this.props.namespace);
}
componentDidMount() {
this._state().registerResultsListener(this.onValuesChange);
}
componentWillUnmount() {
this._state().unregisterResultsListener(this.onValuesChange);
}
onValuesChange() {
this.setState(getState(this.props.namespace));
}
render() {
let values = this._state().getValues();
const { time, totalResults, error } = this.props;
const text = values["q.used"] || values["q"]
if (error) {
return null;
}
const page = parseInt(values.page, 10);
const pageNumber = page && page > 1 ? `Page ${page} of ` : "";
const runOverride = e => {
e.preventDefault();
this._state().setValues({ q: values["q"], "q.override": "true" }, true);
};
const override = values["q.used"] && values["q.used"] !== values["q"]
? <span className="sj-summary-override">
{`search instead for `}
<a onClick={runOverride} href=""> {values["q"]} </a>
</span>
: null;
return (
<div className="sj-result-summary">
<span className="sj-summary-results">
{`${pageNumber}${totalResults} results for `}
"<strong>{text}</strong>"
{" "}
</span>
<span className="sj-query-time">{`(${time}) `}</span>
{override}
</div>
)
}
}
Summary.defaultProps = {
namespace: 'default'
}
const pageNumbers = (page, totalPages) => {
const pages = []
let i = 2
while (i >= 0) {
if (page - i > 0) {
pages.push(page-i)
}
i--
}
i = 1
while (pages.length < 5 && page + i <= totalPages) {
pages.push(page+i)
i++
}
i = 3
while (pages.length < 5 && page - i > 0) {
pages.unshift(page-i)
i++
}
return pages
}
const RawPaginator = ({ resultsPerPage, page, totalResults, setPage, pageFn }) => {
if (totalResults <= resultsPerPage) {
return null
}
const totalPages = Math.ceil(totalResults/resultsPerPage)
if (totalPages === 0) {
return null
}
const pages = pageNumbers(page, totalPages).map(p =>
<Page key={p} page={p} currentPage={page} setPage={setPage}>{p}</Page>
)
const prevPage = () => {
if (page === 1) {
return
}
setPage(page-1)
}
const nextPage = () => {
if (page === totalPages) {
return
}
setPage(page+1)
}
return (
<div className='sj-paginator'>
<div className={page === 1 ? 'disabled' : undefined} onClick={prevPage}><</div>
{pages}
<div className={page === totalPages ? 'disabled' : undefined} onClick={nextPage}>></div>
</div>
)
}
RawPaginator.propTypes = {
resultsPerPage: React.PropTypes.number.isRequired,
page: React.PropTypes.number.isRequired,
totalResults: React.PropTypes.number.isRequired
}
const Page = ({ currentPage, page, setPage, children }) => (
<div className={currentPage === page ? 'current' : null} onClick={() => setPage(page)}>{ children }</div>
)
class Paginator extends React.Component {
render() {
if (this.props.error) {
return null;
}
const _state = State.ns(this.props.namespace);
const setPage = (page) => {
window.scrollTo(0, 0);
_state.setValues({page: ""+page}, true);
}
const values = _state.getValues();
const page = values.page ? parseInt(values.page, 10) : 1;
const resultsPerPage = parseInt(values.resultsPerPage, 10)
const totalResultsInt = parseInt(this.props.totalResults, 10)
return <RawPaginator setPage={setPage} page={page} resultsPerPage={resultsPerPage} totalResults={totalResultsInt} />
}
}
Paginator.defaultProps = {
namespace: 'default'
}
export { Response, Summary, Results, Paginator };
| JavaScript | 0.000001 | @@ -3047,16 +3047,29 @@
summary-
+autocomplete-
override
|
e4c8a91bc8b6e271b7db87275f8f6f5e05acab78 | add default behavior to simplify usage | src/app.js | src/app.js | #!/usr/bin/env node
'use strict'
const fs = require('fs')
const templates = require('./templates.js');
const log = (...args) => {console.log(...args)}
const logError = (...args) => {console.error(...args)}
const handleFileWritingErr = (err) => {
switch (err.code) {
case 'EEXIST':
logError(`A file named ${err.path} already exists!`)
break
default:
logError(err)
}
}
const main = (args) => {
if (!args || args.length < 3) {
return printUsage()
}
switch (args[2]) {
case 'g': case 'generate':
generate(args.slice(3))
break
default:
printUsage()
}
}
const printUsage = () => {
log('I should explain usage here')
}
const generate = (args) => {
if (!args || args.length < 2) {
return printUsage()
}
switch(args[0]) {
case 'component': case 'c':
generateComponents(args.slice(1))
break
default:
printUsage()
}
}
const generateComponents = (components) => {
components.forEach(c => {
fs.writeFile(
`${c.toLowerCase()}.component.jsx`,
templates.component(c),
{ flag: 'wx' },
(err) => {
if (err) {
return handleFileWritingErr(err);
}
log(`Component ${c} created`);
}
)
})
}
main(process.argv)
| JavaScript | 0.000001 | @@ -552,32 +552,107 @@
reak%0A%09%09default:%0A
+%09%09%09if (args.length == 3) %7B%0A%09%09%09%09generateComponents(%5Bargs%5B2%5D%5D);%0A%09%09%09%7D else %7B%0A%09
%09%09%09printUsage()%0A
@@ -643,32 +643,37 @@
%09%09%09printUsage()%0A
+%09%09%09%7D%0A
%09%7D%0A%7D%0A%0Aconst prin
|
2b46fc16e18c29fc6193f05cc960d4a75850cf7b | Fix Heroku | src/app.js | src/app.js | //import proper libraries
var path = require('path');
var express = require('express');
var compression = require('compression');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var dbURL = process.env.MONGOLAB_URI || "mongodb://localhost/DomoMaker";
var db = mongoose.connect(dbURL, function(err){
if (err){
console.log("Could not connect to database");
throw err;
}
});
//pull routes
var router = require('./router.js');
var port = process.env.PORT || process.env.NODE_PORT || 3000;
var app = express();
app.use('/assets', express.static(path.resolve(__dirname+'../../client/')));
app.use(compression());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
key: "sessionid",
secret: 'Domo Arigato',
resave: true,
saveUninitialized: true
}))
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(favicon(__dirname + '/../client/img/favicon.png'));
app.use(cookieParser());
router(app);
app.listen(port, function(err){
if (err){
throw err;
}
console.log('Listening to port ' + port);
});
| JavaScript | 0.998876 | @@ -727,19 +727,16 @@
ame+'../
-../
client/'
|
8812e2aa9883ecbc2b9de88945fccfeb54d3e38f | Clear pending AJAX request if error occurs on page chooser | wagtail/admin/static_src/wagtailadmin/js/page-chooser-modal.js | wagtail/admin/static_src/wagtailadmin/js/page-chooser-modal.js | PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = {
'browse': function(modal, jsonData) {
/* Set up link-types links to open in the modal */
$('.link-types a', modal.body).on('click', function() {
modal.loadUrl(this.href);
return false;
});
/*
Set up submissions of the search form to open in the modal.
FIXME: wagtailadmin.views.chooser.browse doesn't actually return a modal-workflow
response for search queries, so this just fails with a JS error.
Luckily, the search-as-you-type logic below means that we never actually need to
submit the form to get search results, so this has the desired effect of preventing
plain vanilla form submissions from completing (which would clobber the entire
calling page, not just the modal). It would be nice to do that without throwing
a JS error, that's all...
*/
modal.ajaxifyForm($('form.search-form', modal.body));
/* Set up search-as-you-type behaviour on the search box */
var searchUrl = $('form.search-form', modal.body).attr('action');
/* save initial page browser HTML, so that we can restore it if the search box gets cleared */
var initialPageResultsHtml = $('.page-results', modal.body).html();
var request;
function search() {
var query = $('#id_q', modal.body).val();
if (query != '') {
request = $.ajax({
url: searchUrl,
data: {
q: query,
results_only: true
},
success: function(data, status) {
request = null;
$('.page-results', modal.body).html(data);
ajaxifySearchResults();
}
});
} else {
/* search box is empty - restore original page browser HTML */
$('.page-results', modal.body).html(initialPageResultsHtml);
ajaxifyBrowseResults();
}
return false;
}
$('#id_q', modal.body).on('input', function() {
if(request) {
request.abort();
}
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 200);
$(this).data('timer', wait);
});
/* Set up behaviour of choose-page links in the newly-loaded search results,
to pass control back to the calling page */
function ajaxifySearchResults() {
$('.page-results a.choose-page', modal.body).on('click', function() {
var pageData = $(this).data();
modal.respond('pageChosen', $(this).data());
modal.close();
return false;
});
/* pagination links within search results should be AJAX-fetched
and the result loaded into .page-results (and ajaxified) */
$('.page-results a.navigate-pages', modal.body).on('click', function() {
$('.page-results', modal.body).load(this.href, ajaxifySearchResults);
return false;
});
/* Set up parent navigation links (.navigate-parent) to open in the modal */
$('.page-results a.navigate-parent', modal.body).on('click',function() {
modal.loadUrl(this.href);
return false;
});
}
function ajaxifyBrowseResults() {
/* Set up page navigation links to open in the modal */
$('.page-results a.navigate-pages', modal.body).on('click', function() {
modal.loadUrl(this.href);
return false;
});
/* Set up behaviour of choose-page links, to pass control back to the calling page */
$('a.choose-page', modal.body).on('click', function() {
var pageData = $(this).data();
pageData.parentId = jsonData['parent_page_id'];
modal.respond('pageChosen', $(this).data());
modal.close();
return false;
});
}
ajaxifyBrowseResults();
/*
Focus on the search box when opening the modal.
FIXME: this doesn't seem to have any effect (at least on Chrome)
*/
$('#id_q', modal.body).trigger('focus');
},
'email_link': function(modal, jsonData) {
$('p.link-types a', modal.body).on('click', function() {
modal.loadUrl(this.href);
return false;
});
$('form', modal.body).on('submit', function() {
modal.postForm(this.action, $(this).serialize());
return false;
});
},
'external_link': function(modal, jsonData) {
$('p.link-types a', modal.body).on('click', function() {
modal.loadUrl(this.href);
return false;
});
$('form', modal.body).on('submit', function() {
modal.postForm(this.action, $(this).serialize());
return false;
});
},
'external_link_chosen': function(modal, jsonData) {
modal.respond('pageChosen', jsonData['result']);
modal.close();
}
};
| JavaScript | 0 | @@ -1839,32 +1839,135 @@
earchResults();%0A
+ %7D,%0A error: function() %7B%0A request = null;%0A
|
ca0ce5c4a79acace9a0850400a7f335354aacdbb | Add id | walk-in-interview/src/main/webapp/business-jobs-list/script.js | walk-in-interview/src/main/webapp/business-jobs-list/script.js | /**
* This file is specific to show-job-posts-made.html
*/
// TODO(issue/21): get the language from the browser
const CurrentLocale = 'en';
/**
* Import statements are static so its parameters cannot be dynamic.
* TODO(issue/22): figure out how to use dynamic imports
*/
import {AppStrings} from '../strings.en.js';
import {JOB_ID_PARAM, DEFAULT_PAGE_SIZE,
setErrorMessage, getRequirementsList} from '../common-functions.js';
import {API} from '../apis.js';
const STRINGS = AppStrings['business-jobs-list'];
const JOB_STRINGS = AppStrings['job'];
const JOB_DETAILS_PATH = '../job-details/index.html';
const HOMEPAGE_PATH = '../index.html';
// TODO(issue/34): implement pagination for job listings
window.onload = () => {
loadAndDisplayJobListings();
}
/**
* Add the list of jobs made.
*/
async function loadAndDisplayJobListings() {
const backButton = document.getElementById('back');
backButton.innerText = STRINGS['back'];
backButton.addEventListener('click', (_) => {
window.location.href = HOMEPAGE_PATH;
});
const jobListingsTitle =
document.getElementById('job-listings-title');
jobListingsTitle.innerText = STRINGS['job-listings-title'];
const jobPageData =
await getJobsMade(DEFAULT_PAGE_SIZE, /* pageIndex= */ 0)
.catch((error) => {
console.error('error fetching job listings', error);
setErrorMessage(/* errorMessageElementId= */ 'error-message',
/* msg= */ STRINGS['get-jobs-error-message'],
/* include default msg= */ false);
});
displayJobListings(jobPageData);
}
/**
* Makes GET request to retrieve all the job posts made
* by the current business user.
* This function is called when the interest page is loaded.
*
* @param {int} pageSize The number of jobs for one page.
* @param {int} pageIndex The page index (starting from 0).
* @return {Object} The data returned from the servlet.
*/
function getJobsMade(pageSize, pageIndex) {
// Checks input type
const pageSizeParam = parseInt(pageSize);
const pageIndexParam = parseInt(pageIndex);
if (Number.isNaN(pageSizeParam) || Number.isNan(pageIndexParam)) {
throw new Error('Illegal pagination param');
}
const params = `pageSize=${pageSizeParam}&pageIndex=${pageIndexParam}`;
fetch(`${API['business-jobs-list']}?${params}`, {
method: 'GET',
headers: {'Content-Type': 'application/json'},
})
.then((response) => response.json())
.then((data) => {
console.log('data', data);
// Resets the error (there might have been an error msg from earlier)
setErrorMessage(/* errorMessageElementId= */ 'error-message',
/* msg= */ '', /* includesDefaultMsg= */ false);
return data;
});
}
/**
* This will add all the job listings onto the page.
*
* @param {Object} jobPageData The details to be shown on the page.
*/
function displayJobListings(jobPageData) {
const jobListingsElement = document.getElementById('job-listings');
const jobShowing = document.getElementById('job-listings-showing');
/* reset the list so we don't render the same jobs twice */
jobListingsElement.innerHTML = '';
jobShowing.innerHTML = '';
if (jobPageData === undefined ||
!jobPageData.hasOwnProperty('jobList') ||
jobPageData['jobList'].length === 0) {
setErrorMessage(/* errorMessageElementId= */ 'error-message',
/* msg= */ STRINGS['no-jobs-error-message'],
/* includesDefaultMsg= */ false);
return;
}
const jobListings = jobPageData['jobList'];
jobListings.forEach((job) => {
jobListingsElement.appendChild(buildJobElement(job));
});
jobShowing.innerText = JOB_STRINGS['jobShowing']
.replace('{MINIMUM}', jobPageData['range'].minimum)
.replace('{MAXIMUM}', jobPageData['range'].maximum)
.replace('{TOTAL_COUNT}', jobPageData['totalCount']);
}
/**
* Builds the job element given the job details from the servlet response.
*
* @param {Object} job The job to be displayed.
* @return {Element} The job listing element.
*/
function buildJobElement(job) {
const jobPostPreviewTemplate =
document.getElementById('job-listing-template');
const jobPost =
jobPostPreviewTemplate.cloneNode( /* and child elements */ true);
jobPost.setAttribute('id', job['jobId']);
const jobTitle = jobPost.children[0];
jobTitle.innerText = job['jobTitle'];
const jobAddress = jobPost.children[1];
const location = job['jobLocation'];
jobAddress.innerText = JOB_STRINGS['jobAddressDescription']
.replace('{ADDRESS}', location['address'])
.replace('{POSTAL_CODE}', location['postalCode']);
const jobPay = jobPost.children[2];
const pay = job['jobPay'];
jobPay.innerText = JOB_STRINGS['jobPayDescription']
.replace('{MIN_PAY}', pay['min'])
.replace('{MAX_PAY}', pay['max'])
.replace('{CURRENCY}', JOB_STRINGS['sgd'])
.replace('{FREQUENCY}', JOB_STRINGS['pay-frequency'][pay['paymentFrequency']]);
const requirementsList = jobPost.children[3];
const fullRequirementsList = getRequirementsList();
const requirementsArr = [];
const jobRequirements = job['requirements'];
for (const key in jobRequirements) {
if (jobRequirements.hasOwnProperty(key)) {
if (jobRequirements[key] === true) {
requirementsArr.push(fullRequirementsList[key]);
}
}
}
requirementsList.innerText = JOB_STRINGS['requirementsDescription']
.replace('{REQUIREMENTS_LIST}', requirementsArr.join(', '));
const detailsForm = jobPost.children[4];
detailsForm.method = 'GET';
detailsForm.action = JOB_DETAILS_PATH;
const jobIdElement = jobPost.children[4].children[0];
jobIdElement.setAttribute('type', 'hidden');
jobIdElement.setAttribute('name', JOB_ID_PARAM);
const jobId = job[JOB_ID_PARAM];
jobIdElement.setAttribute('value', jobId);
jobPost.addEventListener('click', (_) => {
if (jobId === '') {
throw new Error('jobId should not be empty');
}
detailsForm.submit();
});
return jobPost;
}
| JavaScript | 0.000003 | @@ -4272,16 +4272,36 @@
te('id',
+ 'job-listing-id-' +
job%5B'jo
|
392c01b967dd3861cd3c6494906cdd656ef47e10 | fix size of the paddle | src/pong/object/Paddle.js | src/pong/object/Paddle.js | import { WidthPaddle, HeightPaddle } from "../constants";
const LineWidthPaddle = 5;
function createBmp(game, direction, color) {
const bmd = direction === "horizontal" ?
game.add.bitmapData(WidthPaddle + 2 * LineWidthPaddle, HeightPaddle + 2 * LineWidthPaddle) :
game.add.bitmapData(HeightPaddle + 2 * LineWidthPaddle, WidthPaddle + 2 * LineWidthPaddle);
bmd.ctx.beginPath();
bmd.ctx.lineWidth = LineWidthPaddle;
bmd.ctx.strokeStyle= "#FFFFFF";
if (direction === "horizontal") {
bmd.ctx.rect(LineWidthPaddle, LineWidthPaddle, WidthPaddle, HeightPaddle);
} else {
bmd.ctx.rect(LineWidthPaddle, LineWidthPaddle, HeightPaddle, WidthPaddle);
}
bmd.ctx.stroke();
bmd.ctx.fillStyle = color;
bmd.ctx.fill();
return bmd;
}
class Paddle extends Phaser.Sprite {
constructor(game, x, y, orientation = "horizontal", color = "green") {
const bmd = createBmp(game, orientation, color);
super(game, x, y, bmd);
game.physics.enable(this, Phaser.Physics.ARCADE);
this.anchor.set(0.5, 0.5);
this.body.immovable = true;
}
}
export default Paddle; | JavaScript | 0.000001 | @@ -212,60 +212,16 @@
ddle
- + 2 * LineWidthPaddle, HeightPaddle + 2 * LineWidth
+, Height
Padd
@@ -270,54 +270,10 @@
ddle
+,
-+ 2 * LineWidthPaddle, WidthPaddle + 2 * Line
Widt
@@ -450,32 +450,36 @@
(LineWidthPaddle
+ / 2
, LineWidthPaddl
@@ -475,24 +475,28 @@
eWidthPaddle
+ / 2
, WidthPaddl
@@ -492,32 +492,68 @@
WidthPaddle
-, Height
+ - LineWidthPaddle, HeightPaddle - LineWidth
Paddle);%0A
@@ -598,16 +598,20 @@
thPaddle
+ / 2
, LineWi
@@ -611,32 +611,36 @@
LineWidthPaddle
+ / 2
, HeightPaddle,
@@ -629,34 +629,70 @@
2, HeightPaddle
-,
+- LineWidthPaddle, WidthPaddle - Line
WidthPaddle);%0A
|
792535f8cb9fab02aa83556ce6d9982c62be1e91 | Revert "Updating Jade to pug" | src/app.js | src/app.js | // Todo App
var DocumentDBClient = require('documentdb').DocumentClient;
var config = require('./config');
var TaskList = require('./routes/tasklist');
var TaskDao = require('./models/taskDao');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Todo App
var docDbClient = new DocumentDBClient(config.host, {
masterKey: config.authKey
});
var taskDao = new TaskDao(docDbClient, config.databaseId, config.collectionId);
var taskList = new TaskList(taskDao);
taskDao.init(function(err) { if(err) throw err; });
app.get('/', taskList.showTasks.bind(taskList));
app.post('/addtask', taskList.addTask.bind(taskList));
app.post('/completetask', taskList.completeTask.bind(taskList));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| JavaScript | 0 | @@ -610,11 +610,12 @@
', '
-pug
+jade
');%0A
|
2b8df63ff919f3127d0f906970ff002f2df70b47 | use environment variable to control PORT | src/app.js | src/app.js | var express = require('express');
var swig = require('swig');
var routes = require('./routes');
var app = express();
app.set('views', __dirname + '/templates');
app.set('view engine', 'html');
app.engine('html', swig.renderFile);
app.use(routes);
app.listen(3000, function() {
console.log('listening on port 3000');
});
| JavaScript | 0.000001 | @@ -239,24 +239,61 @@
e(routes);%0A%0A
+var PORT = process.env.PORT %7C%7C 3000;%0A
app.listen(3
@@ -291,20 +291,20 @@
.listen(
-3000
+PORT
, functi
@@ -347,13 +347,16 @@
ort
-3000'
+' + PORT
);%0A%7D
|
6996a084c1b59923597760d9951b60d26faf79a7 | correct date for christmas theme | src/public/style/theme.js | src/public/style/theme.js | import DefaultColor from './themes/default/color'
import ChristmasColor from './themes/christmas/color'
const currentDate = new Date()
const year = currentDate.getFullYear()
const christmasDates = {
begin: new Date(`12/15/${year}`),
end: new Date(`01/15/${year + 1}`)
}
let Color
if (currentDate > christmasDates.begin && currentDate < christmasDates.end) {
require('./themes/christmas/color.css')
require('./themes/christmas/style.css')
Color = ChristmasColor
} else {
require('./themes/default/color.css')
require('./themes/default/style.css')
Color = DefaultColor
}
export default Color | JavaScript | 0.005502 | @@ -263,12 +263,8 @@
year
- + 1
%7D%60)%0A
|
6f828873a2cf1c1f3f40da8e2e67aecd7eb72f3e | add materialie import to app level | sample/src/main.js | sample/src/main.js | export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-materialize-bridge', plugin => {
plugin.useClickCounter()
.useBadge()
.useBreadcrumbs()
.useBox()
.useButton()
.useCard()
.useCarousel()
.useCharacterCounter()
.useCheckbox()
.useChip()
.useCollapsible()
.useCollection()
.useColors()
.useDatePicker()
.useDropdown()
.useFab()
.useFile()
.useFooter()
.useInput()
.useModal()
.useNavbar()
.usePagination()
.useParallax()
.useProgress()
.usePushpin()
.useRadio()
.useRange()
.useScrollfire()
.useScrollSpy()
.useSelect()
.useSidenav()
.useSlider()
.useSwitch()
.useTabs()
.useTooltip()
.useTransitions()
.useWaves()
.useWell();
});
aurelia.use.globalResources('shared/collapse-panel');
aurelia.use.globalResources('shared/markdown');
aurelia.use.globalResources('shared/logger');
aurelia.use.globalResources('shared/au-code');
aurelia.use.globalResources('shared/sampleValueConverters');
aurelia.start()
.then(au => au.setRoot('app'));
}
| JavaScript | 0 | @@ -1,8 +1,31 @@
+import 'materialize';%0A%0A
export f
|
183e485c430745068b96910660d64e8cf9e13cdf | use render App instead of ...App | src/app.js | src/app.js | import 'styles/bootstrap'
import 'styles/app'
import Vue from 'vue'
import {createRouter} from 'router'
import {createStore} from 'store'
import 'plugins'
import App from 'views/App'
export const createApp = ssrContext => {
const store = createStore()
const router = createRouter(store)
const app = new Vue({
...App,
router,
store,
ssrContext
})
return {app, router, store}
}
| JavaScript | 0 | @@ -318,20 +318,8 @@
e(%7B%0A
- ...App,%0A
@@ -351,16 +351,41 @@
rContext
+,%0A render: h =%3E h(App)
%0A %7D)%0A%0A
|
3d4df753fdbac1efed02e6190dd2f9a61ea50bf6 | remove logging of the NODE_ENV | src/app.js | src/app.js | import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import { applyMiddleware, compose, createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute } from 'react-router'
import createHistory from 'history/lib/createHashHistory'
import { syncHistory, routeReducer } from 'react-router-redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
/*
reducers
*/
import * as reducers from './reducers'
/*
containers
*/
import App from "./containers/App";
import Home from "./containers/Home";
import Foo from "./components/Foo";
import Bar from "./components/Bar";
/*
history/logging
*/
const history = createHistory()
const routerMiddleware = syncHistory(history)
const loggerMiddleware = createLogger()
/*
reducer
*/
const reducer = combineReducers({
...reducers,
routing: routeReducer
})
var middlewareArray = [
thunkMiddleware,
routerMiddleware
]
if(process.env.NODE_ENV==='development'){
middlewareArray.push(loggerMiddleware)
}
/*
store
*/
const finalCreateStore = compose(
applyMiddleware.apply(null, middlewareArray)
)(createStore)
const store = finalCreateStore(reducer)
console.log('-------------------------------------------');
console.dir(process.env.NODE_ENV)
/*
routes
*/
ReactDOM.render(
<Provider store={store}>
<div>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="foo" component={Foo}/>
<Route path="bar" component={Bar}/>
</Route>
</Router>
</div>
</Provider>,
document.getElementById('mount')
)
| JavaScript | 0 | @@ -1241,102 +1241,8 @@
r)%0A%0A
-console.log('-------------------------------------------');%0Aconsole.dir(process.env.NODE_ENV)%0A
/*%0A%0A
|
e5a131eaefe2512abca26a89182732f1bff7fc9e | Remove comment. | src/app.js | src/app.js | var SVG_NS = "http://www.w3.org/2000/svg"
export default function (app) {
var view = app.view || function () {
return ""
}
var model
var actions = {}
var subscriptions = []
var hooks = {
onError: [],
onAction: [],
onUpdate: [],
onRender: []
}
var node
var root
var batch = []
var plugins = app.plugins || []
for (var i = -1; i < plugins.length; i++) {
var plugin = i < 0 ? app : plugins[i](app)
if (plugin.model != null) {
model = merge(model, plugin.model)
}
if (plugin.actions) {
init(actions, plugin.actions)
}
if (plugin.subscriptions) {
subscriptions = subscriptions.concat(plugin.subscriptions)
}
var _hooks = plugin.hooks
if (_hooks) {
Object.keys(_hooks).forEach(function (key) {
hooks[key].push(_hooks[key])
})
}
}
load(function () {
root = app.root || document.body.appendChild(document.createElement("div"))
render(model, view)
for (var i = 0; i < subscriptions.length; i++) {
subscriptions[i](model, actions, onError)
}
})
function onError(error) {
for (var i = 0; i < hooks.onError.length; i++) {
hooks.onError[i](error)
}
if (i <= 0) {
throw error
}
}
function init(container, group, lastName) {
Object.keys(group).forEach(function (key) {
if (!container[key]) {
container[key] = {}
}
var name = lastName ? lastName + "." + key : key
var action = group[key]
var i
if (typeof action === "function") {
container[key] = function (data) {
for (i = 0; i < hooks.onAction.length; i++) {
hooks.onAction[i](name, data)
}
var result = action(model, data, actions, onError)
if (result == null || typeof result.then === "function") {
return result
} else {
for (i = 0; i < hooks.onUpdate.length; i++) {
hooks.onUpdate[i](model, result, data)
}
model = merge(model, result)
render(model, view)
}
}
} else {
init(container[key], action, name)
}
})
}
function load(fn) {
if (document.readyState[0] !== "l") {
fn()
} else {
document.addEventListener("DOMContentLoaded", fn)
}
}
function render(model, view) {
for (i = 0; i < hooks.onRender.length; i++) {
view = hooks.onRender[i](model, view)
}
patch(root, node, node = view(model, actions), 0)
for (var i = 0; i < batch.length; i++) {
batch[i]()
}
batch = []
}
function merge(a, b) {
var obj = {}
var key
if (isPrimitive(b) || Array.isArray(b)) {
return b
}
for (key in a) {
obj[key] = a[key]
}
for (key in b) {
obj[key] = b[key]
}
return obj
}
function isPrimitive(type) {
type = typeof type
return type === "string" || type === "number" || type === "boolean"
}
function defer(fn, data) {
setTimeout(function () {
fn(data)
}, 0)
}
function shouldUpdate(a, b) {
return a.tag !== b.tag || typeof a !== typeof b || isPrimitive(a) && a !== b
}
function createElementFrom(node, isSVG) {
var element
if (typeof node === "string") {
element = document.createTextNode(node)
} else {
element = (isSVG = isSVG || node.tag === "svg")
? document.createElementNS(SVG_NS, node.tag)
: document.createElement(node.tag)
for (var name in node.data) {
if (name === "onCreate") {
defer(node.data[name], element)
} else {
setElementData(element, name, node.data[name])
}
}
for (var i = 0; i < node.children.length; i++) {
element.appendChild(createElementFrom(node.children[i], isSVG))
}
}
return element
}
function removeElementData(element, name, value) {
element[name] = value
element.removeAttribute(name)
}
function setElementData(element, name, value, oldValue) {
name = name.toLowerCase()
if (!value) {
removeElementData(element, name, value, oldValue)
} else if (name === "style") {
for (var i in oldValue) {
if (!(i in value)) {
element.style[i] = ""
}
}
for (var i in value) {
element.style[i] = value[i]
}
} else {
element.setAttribute(name, value)
if (element.namespaceURI !== SVG_NS) {
if (element.type === "text") {
var oldSelStart = element.selectionStart
var oldSelEnd = element.selectionEnd
}
element[name] = value
if (oldSelStart >= 0) {
element.setSelectionRange(oldSelStart, oldSelEnd)
}
}
}
}
function updateElementData(element, data, oldData) {
for (var name in merge(oldData, data)) {
var value = data[name]
var oldValue = oldData[name]
var realValue = element[name]
if (name === "onUpdate") {
defer(value, element)
} else if (
value !== oldValue || typeof realValue === "boolean" && realValue !== value
) {
setElementData(element, name, value, oldValue)
}
}
}
function patch(parent, oldNode, node, index) {
var element = parent.childNodes[index]
if (oldNode === undefined) {
parent.appendChild(createElementFrom(node))
} else if (node === undefined) {
// Removing a child one at a time updates the DOM, so we end up
// with an index out of date that needs to be adjusted. Instead,
// collect all the elements and delete them in a batch.
batch.push(parent.removeChild.bind(parent, element))
if (oldNode && oldNode.data && oldNode.data.onRemove) {
defer(oldNode.data.onRemove, element)
}
} else if (shouldUpdate(node, oldNode)) {
if (typeof node === "string") {
element.textContent = node
} else {
parent.replaceChild(createElementFrom(node), element)
}
} else if (node.tag) {
updateElementData(element, node.data, oldNode.data)
var len = node.children.length, oldLen = oldNode.children.length
for (var i = 0; i < len || i < oldLen; i++) {
patch(element, oldNode.children[i], node.children[i], i)
}
}
}
}
| JavaScript | 0 | @@ -1089,18 +1089,16 @@
%7D%0A %7D)%0A
-
%0A funct
@@ -5453,212 +5453,8 @@
) %7B%0A
- // Removing a child one at a time updates the DOM, so we end up%0A // with an index out of date that needs to be adjusted. Instead,%0A // collect all the elements and delete them in a batch.%0A%0A
|
cbf2e93bd65a9296c9f35e114bea7e43ec8a1163 | Save position on resize without move | src/app.js | src/app.js | /**
* @file This is the central application logic and window management src file.
* This is the central render process main window JS, and has access to
* the DOM and all node abilities.
**/
"use strict";
// Libraries ==============================================---------------------
// Must use require syntax for including these libs because of node duality.
window.$ = window.jQuery = require('jquery');
window._ = require('underscore');
// Main Process ===========================================---------------------
// Include global main process connector objects for the renderer (this window).
var remote = require('remote');
var mainWindow = remote.getCurrentWindow();
$.i18n = window.i18n = remote.require('i18next');
var app = remote.require('app');
var scale = {};
// Page loaded
$(function(){
// After page load, wait for the griddle image to finish before initializing.
$('#griddle').load(initEditor);
});
function initEditor() {
var $griddle = $('#editor-wrapper img');
var $editor = $('#editor');
$griddle.aspect = 0.5390;
$editor.aspect = 0.4717;
$editor.pos = {
left: 27,
top: 24,
right: 48,
bottom: 52
};
var margin = [160, 100];
// Set maximum work area render size
$(window).on('resize', function(e){
var win = [$(window).width(), $(window).height()];
// Assume size to width
$griddle.width(win[0] - margin[0]);
$griddle.height((win[0] - margin[0]) * $griddle.aspect);
// If too large, size to height
if ($griddle.height() > win[1] - margin[1]) {
$griddle.width((win[1] - margin[1]) / $griddle.aspect);
$griddle.height((win[1] - margin[1]));
}
scale = {};
scale.x = ($griddle.width()) / $griddle[0].naturalWidth;
scale.y = ($griddle.height()) / $griddle[0].naturalHeight;
scale = (scale.x < scale.y ? scale.x : scale.y);
var off = $griddle.offset();
$editor.css({
top: off.top + (scale * $editor.pos.top),
left: off.left + (scale * $editor.pos.left),
width: $griddle.width() - ($editor.pos.right * scale),
height: $griddle.height() - ($editor.pos.bottom * scale)
});
editorLoad(); // Load the editor (if it hasn't already been loaded)
// This must happen after the very first resize, otherwise the canvas doesn't
// have the correct dimensions for Paper to size to.
}).resize();
}
// Load the actual editor PaperScript (only when the canvas is ready).
var editorLoaded = false;
function editorLoad() {
if (!editorLoaded) {
editorLoaded = true;
paper.PaperScript.load($('<script>').attr({
type:"text/paperscript",
src: "editor.ps.js",
canvas: "editor"
})[0]);
}
}
// Trigger load init resize only after editor has called this function.
function editorLoadedInit() {
$(window).resize();
buildToolbar();
}
function buildToolbar() {
var $t = $('<ul>').appendTo('#tools');
_.each(paper.tools, function(tool, index){
$t.append($('<li>').append(
$('<img>').attr({
src: 'images/icon-' + tool.key + '.png',
title: i18n.t(tool.name)
})
).click(function(){
$('#tools li.active').removeClass('active');
$(this).addClass('active');
tool.activate();
$('#editor').css('cursor', 'url("images/cursor-' + tool.key + '.png"), move');
}));
});
// Activate the first (default) tool.
$t.find('li:first').click();
}
| JavaScript | 0.000001 | @@ -2344,16 +2344,51 @@
ize to.%0A
+ $(mainWindow).trigger('move');%0A
%7D).res
|
9331944802d63a21f532f29f0815a3fc38b8b451 | use for..of instead of map (because of async) | src/app.js | src/app.js | 'use strict'
const {
CDP_USER,
CDP_SESSION_COOKIE,
PEN_ID,
NODE_ENV,
PORT = 3000
} = process.env
if (!CDP_USER || !CDP_SESSION_COOKIE || !PEN_ID) {
throw Error('CDP_USER, CDP_SESSION_COOKIE and PEN_ID required!')
}
const socketio = require('socket.io')
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const { uniqBy } = require('lodash')
const initBot = require('./lib/bot')
//------------------------------------------
// Logging
//------------------------------------------
const { createLogger, format, transports } = require('winston')
const { combine, timestamp, label, printf } = format
const loggerFormat = printf(info => {
return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`
})
const logger = createLogger({
level: 'info',
format: combine(
label({ label: 'cdp-bot' }),
timestamp(),
loggerFormat
),
transports: [
new transports.File({ filename: 'logs/error.log', level: 'error' }),
new transports.File({ filename: 'logs/all.log' })
]
})
if (NODE_ENV !== 'production') {
logger.add(new transports.Console({
format: format.simple()
}))
}
//------------------------------------------
// Database
//------------------------------------------
const knex = require('knex')({
client: 'sqlite3',
connection: {
filename: 'data/db.sqlite'
}
})
knex.schema
.createTableIfNotExists('apps', table => {
table.increments('id').primary()
table.string('apiKey').index().unique()
table.string('apiSecret').index().unique()
table.string('ip').index()
table.timestamp('created_at').defaultTo(knex.fn.now())
})
.catch(e => logger.error(e.message))
//------------------------------------------
// Init Server
//------------------------------------------
const app = express()
const server = http.Server(app)
const io = socketio(server)
const ns = io.of('/auth')
// CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
res.header('Access-Control-Allow-Credentials', 'true')
next()
})
// JSON and URL-encoded support
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// Start server
server.listen(PORT, () => {
logger.info('Bot started!')
logger.info(`Listening on port ${PORT}`)
})
const state = {
lastRequest: null,
hasNextReq: false
}
;(async () => {
const bot = initBot(CDP_SESSION_COOKIE, CDP_USER, PEN_ID)
await bot.updateToken()
setInterval(async () => {
const now = Date.now()
const diff = now - state.lastRequest
if (state.hasNextReq && diff > 2000) {
logger.info(`Auth request detected!`)
state.lastRequest && logger.info(`Time since last request: ${diff}ms`)
state.hasNextReq = false
state.lastRequest = Date.now()
const comments = await bot.getAllComments()
logger.info(`Parsed comments: ${JSON.stringify(comments, null, 2)}`)
/**
* token Array<Promise>
*/
const tokens = comments.map(async comment => {
const { username, userId, name, text } = comment
const [ socketID, apiKey ] = text.split(':')
bot.deleteComment(comment.id)
.then(removed => {
logger.info(`Comment removed: ${comment.id}, ${username}, ${text}`)
})
.catch(e => {
logger.error(`Error when removing comment: ${comment.id}`)
})
if (!socketID || !apiKey) {
logger.error(`Wrong comment format: ${comment.text}`)
return
}
const result = await knex
.select('apiSecret')
.from('apps')
.where('apiKey', '=', apiKey)
.first()
if (!result) {
logger.error(`Couldn't find apiKey ${apiKey}`)
return
}
if (result && result.apiSecret.length !== 64) {
logger.error(`Wrong apiSecret length: ${apiSecret.length}`)
return
}
const token = jwt.sign(
{ username, userId, name },
result.apiSecret,
{ expiresIn: 60 * 5 }
)
return {
token,
to: socketID,
userId,
username,
name
}
})
// Send the tokens only to the first comment with
// the same session id
uniqBy(tokens, 'to')
.filter(t => t)
.forEach(async tokenPromise => {
const token = await tokenPromise
ns.to(`/auth#${token.to}`).emit('authenticated', token)
})
}
}, 1000)
ns.on('connection', client => {
logger.info(`Client connected: ${client.id}`)
client.on('notify', async () => {
logger.info(`Notified by: ${client.id}`)
state.hasNextReq = true
})
})
// REST endpoints
app.get('/', (req, res) => {
res.json({
success: true,
name: 'CodePen Auth',
description: 'Allow CodePen users to authenticate with your app.'
})
})
app.post('/verify', (req, res, next) => {
const { token, apiSecret } = req.body
if (!token || !apiSecret) {
res.status(400).json({
error: `'token' and 'apiSecret' parameters required!`
})
return
}
try {
const validToken = jwt.verify(token, apiSecret)
logger.log('debug', `TOKEN_VALID ${validToken.username}`);
res.json({ valid: true, data: validToken })
} catch (e) {
logger.log('debug', `TOKEN_ERROR ${e}`);
res.json({ valid: false, error: e.message })
}
})
const randomHex = (len = 32) => new Promise((resolve, reject) => {
crypto.randomBytes(len, async (err, buffer) => {
if (err) {
reject(err)
return
}
resolve(buffer.toString('hex'))
})
})
app.get('/createApp', async (req, res, next) => {
try {
const apiKey = await randomHex(16)
const apiSecret = await randomHex()
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
const result = await knex('apps').insert({ apiKey, apiSecret, ip })
if (result.length && result[0]) {
res.json({ apiKey, apiSecret })
}
} catch (e) {
res.status(500).json({ error: true })
}
})
// renew tokens and cookies each 10 minutes
setInterval(async () => {
logger.info(`Updating token...`)
await bot.updateToken()
}, 600000)
})()
| JavaScript | 0 | @@ -3173,113 +3173,66 @@
-/**%0A * token Array%3CPromise%3E%0A
+let tokens = %5B%5D%0A
-*/
%0A
-const tokens = comments.map(async comment =%3E %7B%0A
+for (let comment of comments) %7B
%0A
@@ -3993,32 +3993,33 @@
eturn%0A %7D%0A
+%0A
if (resu
@@ -4305,23 +4305,28 @@
-return
+tokens.push(
%7B%0A
@@ -4422,24 +4422,25 @@
%7D
+)
%0A %7D
)%0A%0A
@@ -4423,33 +4423,32 @@
%7D)%0A %7D
-)
%0A%0A // Send
|
218c5632c8925769b8c04a9be1c4030c898f518f | use some instead of forEach | src/app.js | src/app.js | import $ from 'jquery'
import * as lib from './mylib'
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (var key in changes) {
var storageChange = changes[key];
console.log(`Storage key "${key}" in namespace "${namespace}" changed. Old value was "${storageChange.oldValue}", new value is "${storageChange.newValue}".`);
reduceAttention();
}
});
function reduceAttention() {
chrome.storage.local.get('excluding', (ret)=> {
const exc = ret.excluding;
let set = new Set(exc);
$("div.property_unit").each((index, elem)=> {
let unit = $(elem);
const title = unit.find("div.property_unit-header h2 a").html();
set.forEach((val)=> {
if (title.indexOf(val) != -1) {
unit.addClass("shrkw-hide");
} else {
unit.removeClass("shrkw-hide");
}
});
});
});
}
function insertButtons() {
let clearButton = $('div#js-pageTop').append("<button class='shrkw-clear'>Clear</button>");
clearButton.on("click", ()=> {chrome.storage.local.clear(()=> {console.log('cleared');})})
$("input.js-clipkey").after("<button class='shrkw-excluding'>Exc</button>");
$("button.shrkw-excluding").on("click", (e)=> {
e.preventDefault();
var title_a = $(e.target).closest("div.property_unit").find("div.property_unit-header h2 a");
lib.addExcludingWord(title_a.html());
});
}
insertButtons();
reduceAttention();
| JavaScript | 0.000003 | @@ -492,37 +492,8 @@
ng;%0A
- let set = new Set(exc);%0A%0A
@@ -645,19 +645,30 @@
-set.forEach
+const found = exc.some
((va
@@ -765,19 +765,63 @@
-%7D else %7B%0A
+ return true;%0A %7D%0A %7D);%0A if (!found) %7B%0A
@@ -858,37 +858,25 @@
de%22);%0A
- %7D%0A %7D);
+%7D
%0A %7D);%0A %7D
|
f459ffcfaae25dd4d2946f6fc2af7ec1bb08246d | Fix unhandled exception | src/queryMatchBrackets.js | src/queryMatchBrackets.js | (function() {
var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
(document.documentMode == null || document.documentMode < 8);
var Pos = CodeMirror.Pos;
function findMatchingBracket(cm, where, strict) {
var cur = cm.getCursor(), state = cm.getStateAfter();
if (state.matches.length > cur.line) {
var matches = state.matches[cur.line], i = matches.length;
while (i--) {
var pos = matches[i];
if (pos[0] === cur.ch || pos[0] === cur.ch - 1 || pos[1] === cur.ch || pos[1] === cur.ch - 1)
return {from: Pos(cur.line, pos[0]), to: Pos(cur.line, pos[1]),
match: true};
}
}
if (state.noMatches.length > cur.line) {
var noMatches = state.noMatches[cur.line], i;
if (noMatches) {
i = noMatches.length;
while (i--) {
var pos = noMatches[i];
if (pos === cur.ch || pos === cur.ch - 1)
return {from: Pos(cur.line, pos), to: false,
match: false};
}
}
}
return null;
}
function matchBrackets(cm, autoclear) {
var found = findMatchingBracket(cm);
if (!found)
return;
var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style});
var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style});
// Kludge to work around the IE bug from issue #1193, where text
// input stops going to the textare whever this fires.
if (ie_lt8 && cm.state.focused) cm.display.input.focus();
var clear = function() {
cm.operation(function() { one.clear(); two && two.clear(); });
};
if (autoclear) setTimeout(clear, 800);
else return clear;
}
var currentlyHighlighted = null;
function doMatchBrackets(cm) {
cm.operation(function() {
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false);
});
}
CodeMirror.defineOption("queryMatchBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init)
cm.off("cursorActivity", doMatchBrackets);
if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {};
cm.on("cursorActivity", doMatchBrackets);
}
});
CodeMirror.defineExtension("queryMatchBrackets", function() {matchBrackets(this, true);});
})();
| JavaScript | 0.000431 | @@ -347,16 +347,39 @@
.line%5D,
+i;%0A%09%09if (matches) %7B%0A%09%09%09
i = matc
@@ -392,16 +392,17 @@
ngth;%0A%09%09
+%09
while (i
@@ -407,16 +407,17 @@
(i--) %7B%0A
+%09
%09%09%09var p
@@ -436,16 +436,17 @@
%5Bi%5D;%0A%09%09%09
+%09
if (pos%5B
@@ -531,24 +531,25 @@
ch - 1)%0A%09%09%09%09
+%09
return %7Bfrom
@@ -601,24 +601,25 @@
s%5B1%5D),%0A%09%09%09%09%09
+%09
match: true%7D
@@ -620,16 +620,21 @@
true%7D;%0A
+%09%09%09%7D%0A
%09%09%7D%0A%09%7D%0A%09
|
81bfc55dcca1b8e8093ddb5bb28b4d4a6bd80110 | add method for scaling container | src/app.js | src/app.js | var Video = require('./video');
var Assets = require('./assets');
var Debugger = require('potion-debugger');
var PotionAudio = require('potion-audio');
var App = function(container) {
this.container = container;
container.style.position = 'relative';
var canvas = document.createElement('canvas');
canvas.style.display = 'block';
container.appendChild(canvas);
this.canvas = canvas;
this.width = 300;
this.height = 300;
this.audio = new PotionAudio();
this.assets = new Assets(this);
this.states = null;
this.input = null;
this.config = {
allowHiDPI: true,
getCanvasContext: true,
addInputEvents: true,
showPreloader: true,
fixedStep: false,
stepTime: 1/60,
maxStepTime: 1/60
};
this.video = new Video(this, canvas, this.config);
this.video._isRoot = true;
this.debug = new Debugger(this);
};
App.prototype.resize = function(width, height) {
this.width = width;
this.height = height;
this.container.style.width = this.width + 'px';
this.container.style.height = this.height + 'px';
if (this.video) {
this.video._resize(width, height);
}
if (this.states) {
this.states.resize();
}
};
module.exports = App;
| JavaScript | 0.000001 | @@ -971,101 +971,28 @@
his.
-container.style.
+scale(
width
- = this.width + 'px';%0A this.container.style.height = this.height + 'px'
+, height)
;%0A%0A
@@ -1105,16 +1105,16 @@
();%0A
-
%7D%0A%7D;%0A%0A
modu
@@ -1109,16 +1109,160 @@
%7D%0A%7D;%0A%0A
+App.prototype.scale = function(width, height) %7B%0A this.container.style.width = width + 'px';%0A this.container.style.height = height + 'px';%0A%7D;%0A%0A
module.e
|
eeb6bb4917bc2668769dd6d547209366b36464c4 | Fix indentation for select, plural, selectordinal | src/quill.intl-toolbar.js | src/quill.intl-toolbar.js | export default function(doc) {
const typeMap = {
number: '{foo, number}',
date: '{foo, date, medium}',
time: '{foo, time, medium}',
select: `
{foo, select,
foo {Foo}
bar {Bar}
other {Baz}
}`.trim(),
plural: `
{foo, plural,
=0 {no foos}
one {# foo}
other {# foos}
}`.trim(),
selectordinal: `
{foo, selectordinal,
one {#st}
two {#nd}
few {#rd}
other {#th}
}`.trim()
};
const addButton = (container, type) => {
const button = doc.createElement('button');
button.setAttribute('type', 'button');
button.setAttribute('data-type', type);
button.innerHTML = type;
button.classList.add(`ql-${type}`);
button.value = type;
container.appendChild(button);
};
const addControls = (container) => {
[
'number',
'date',
'time',
'select',
'plural',
'selectordinal'
].forEach(type => {
addButton(container, type);
});
};
const bindEvents = (container, quill) => {
const buttons = Array.from(container.querySelectorAll('button'));
buttons.forEach(button => {
const
type = button.getAttribute('data-type'),
text = typeMap[type];
button.addEventListener('click', () => {
quill.focus();
const range = quill.getSelection();
quill.updateContents({
ops: [
{ retain: range.start },
{ delete: range.end - range.start },
{ insert: text }
]
});
});
});
};
return function(quill, options) {
const container = typeof options.container === 'string'
? document.querySelector(options.container)
: options.container;
addControls(container);
bindEvents(container, quill);
};
}
| JavaScript | 0.000268 | @@ -1,194 +1,21 @@
-export default function(doc) %7B%0A const typeMap = %7B%0A number: '%7Bfoo, number%7D',%0A date: '%7Bfoo, date, medium%7D',%0A time: '%7Bfoo, time, medium%7D',%0A select: %60%0A
+const SELECT = %60%0A
%7Bfoo
@@ -24,28 +24,16 @@
select,%0A
-
foo
@@ -34,36 +34,24 @@
foo %7BFoo%7D%0A
-
bar %7BBar
@@ -60,85 +60,49 @@
- other %7BBaz%7D%0A %7D%60.trim(),%0A plural: %60%0A
+other %7BBaz%7D%0A%7D%60.trim();%0A%0Aconst PLURAL = %60%0A
%7Bfoo
@@ -107,36 +107,24 @@
oo, plural,%0A
-
=0 %7Bno f
@@ -128,28 +128,16 @@
o foos%7D%0A
-
one
@@ -144,28 +144,16 @@
%7B# foo%7D%0A
-
othe
@@ -167,216 +167,380 @@
os%7D%0A
- %7D%60.trim(),%0A selectordinal: %60%0A %7Bfoo, selectordinal,%0A one %7B#st%7D%0A two %7B#nd%7D%0A few %7B#rd%7D%0A other %7B#th%7D%0A %7D%60.trim()
+%7D%60.trim();%0A%0Aconst SELECTORDINAL = %60%0A%7Bfoo, selectordinal,%0A one %7B#st%7D%0A two %7B#nd%7D%0A few %7B#rd%7D%0A other %7B#th%7D%0A%7D%60.trim();%0A%0A%0Aexport default function(doc) %7B%0A const typeMap = %7B%0A number: '%7Bfoo, number%7D',%0A date: '%7Bfoo, date, medium%7D',%0A time: '%7Bfoo, time, medium%7D',%0A select: SELECT,%0A plural: PLURAL,%0A selectordinal: SELECTORDINAL
%0A
|
2a0e686d64228750794b8796cd6298c94704134f | Refactor scr.state.js to use a sorter from scr.processor.js in renderer | src/renderer/scr.state.js | src/renderer/scr.state.js | var STATE = (function(){
var ROOT = {};
// ---------------
// State variables
// ---------------
var FILE;
var MSGS;
var selectedChannel;
var currentPage;
var messagesPerPage;
// -----------------
// Utility functions
// -----------------
var messageKeySorter = (key1, key2) => {
if (key1.length === key2.length){
return key1 > key2 ? 1 : key1 < key2 ? -1 : 0;
}
else{
return key1.length > key2.length ? 1 : -1;
}
};
// ----------------------------------
// Channel and message refresh events
// ----------------------------------
var eventOnChannelsRefreshed;
var eventOnMessagesRefreshed;
var triggerChannelsRefreshed = function(){
eventOnChannelsRefreshed && eventOnChannelsRefreshed(ROOT.getChannelList());
};
var triggerMessagesRefreshed = function(){
eventOnMessagesRefreshed && eventOnMessagesRefreshed(ROOT.getMessageList());
};
ROOT.onChannelsRefreshed = function(callback){
eventOnChannelsRefreshed = callback;
};
ROOT.onMessagesRefreshed = function(callback){
eventOnMessagesRefreshed = callback;
};
// ------------------------------------
// File upload and basic data retrieval
// ------------------------------------
ROOT.uploadFile = function(file){
FILE = file;
MSGS = null;
currentPage = 1;
triggerChannelsRefreshed();
triggerMessagesRefreshed();
};
ROOT.getChannelName = function(channel){
return FILE.getChannelById(channel).name;
};
ROOT.getUserName = function(user){
return FILE.getUserById(user).name;
};
ROOT.getRawMessages = function(channel){
return channel ? FILE.getMessages(channel) : FILE.getAllMessages();
};
// --------------------------
// Channel list and selection
// --------------------------
ROOT.getChannelList = function(){
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({ // reserve.txt
id: key,
name: channels[key].name,
server: FILE.getServer(channels[key].server),
msgcount: FILE.getMessageCount(key)
}));
};
ROOT.selectChannel = function(channel){
currentPage = 1;
selectedChannel = channel;
MSGS = Object.keys(FILE.getMessages(channel)).sort(messageKeySorter);
triggerMessagesRefreshed();
};
ROOT.getSelectedChannel = function(){
return selectedChannel;
};
// ------------
// Message list
// ------------
ROOT.getMessageList = function(){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
var startIndex = messagesPerPage*(ROOT.getCurrentPage()-1);
return MSGS.slice(startIndex, !messagesPerPage ? undefined : startIndex+messagesPerPage).map(key => {
var message = messages[key];
return { // reserve.txt
user: FILE.getUser(message.u),
timestamp: message.t,
contents: message.m,
embeds: message.e,
attachments: message.a,
edited: (message.f&1) === 1
};
});
};
// ----------
// Pagination
// ----------
ROOT.setMessagesPerPage = function(amount){
messagesPerPage = amount;
triggerMessagesRefreshed();
};
ROOT.updateCurrentPage = function(action){
switch(action){
case "first": currentPage = 1; break;
case "prev": currentPage = Math.max(1, currentPage-1); break;
case "next": currentPage = Math.min(ROOT.getPageCount(), currentPage+1); break;
case "last": currentPage = ROOT.getPageCount(); break;
}
triggerMessagesRefreshed();
};
ROOT.getCurrentPage = function(){
var total = ROOT.getPageCount();
if (currentPage > total && total > 0){
currentPage = total;
}
return currentPage;
};
ROOT.getPageCount = function(){
return !MSGS ? 0 : (!messagesPerPage ? 1 : Math.ceil(MSGS.length/messagesPerPage));
};
// End
return ROOT;
})();
| JavaScript | 0 | @@ -203,293 +203,8 @@
%0A %0A
- // -----------------%0A // Utility functions%0A // -----------------%0A %0A var messageKeySorter = (key1, key2) =%3E %7B%0A if (key1.length === key2.length)%7B%0A return key1 %3E key2 ? 1 : key1 %3C key2 ? -1 : 0;%0A %7D%0A else%7B%0A return key1.length %3E key2.length ? 1 : -1;%0A %7D%0A %7D;%0A %0A
//
@@ -1989,24 +1989,39 @@
ort(
-messageKeySorter
+PROCESSOR.SORTER.oldestToNewest
);%0A%0A
|
dd7d737c31ed713f84d5257f1e1ccd0ef599fa67 | Modify info log | src/bot.js | src/bot.js | /**
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {Adapter, User, TextMessage} = require.main.require('hubot');
const PubSub = require(`@google-cloud/pubsub`);
const {google} = require('googleapis');
const {auth} = require('google-auth-library');
const HangoutsChatTextMessage = require('./message')
const express = require('express');
const bodyparser = require('body-parser');
const app = express()
.use(bodyparser.urlencoded({extended: false}))
.use(bodyparser.json());
class HangoutsChatBot extends Adapter {
constructor(robot, options) {
super(robot);
this.subscriptionName = `projects/${options.projectId}/subscriptions/${options.subscriptionId}`;
this.isPubSub = options.isPubSub;
this.port = options.port;
if (this.isPubSub) {
// Establish OAuth with Hangouts Chat
let authClientPromise = auth.getClient({
scopes: ['https://www.googleapis.com/auth/chat.bot']
});
this.chatPromise = authClientPromise.then((credentials) =>
google.chat({
version: 'v1',
auth: credentials
}));
}
}
/*
* Helper method which takes care of constructing the response url
* and sending the message to Hangouts Chat.
*/
sendMessage(envelope, ...strings) {
let data = {
text: strings[0] || '',
thread: envelope.message.thread
};
if (this.isPubSub) {
this.chatPromise.then((chat) =>
chat.spaces.messages.create({
parent: envelope.message.space.name,
requestBody: data
}));
} else {
// Post message as HTTP response
envelope.message.httpRes.json(data);
}
}
/*
* Hubot is sending a message to Hangouts Chat.
*/
send (envelope, ...strings) {
this.sendMessage(envelope, ...strings);
}
/*
* Hubot is sending a reply to Hangouts Chat.
*/
reply (envelope, ...strings) {
this.sendMessage(envelope, ...strings);
}
/*
* Activates HTTP listener and sets
* up handler to handle events.
*/
startHttpServer() {
// Create an event handler to handle messages.
app.post('/', (req, res) => {
this.onEventReceived(req.body, res);
});
// Listen for new messages.
app.listen(this.port, () => {
this.robot.logger.info(`Server is running in port - ${this.port}`);
});
}
/*
* Initializes the Cloud Pub/Sub Subscriber,
* establishes connection to the Subscription
* and sets up handler to handle events.
*/
startPubSubClient() {
const pubsub = PubSub();
this.robot.logger.info(`Connecting to Pub/Sub subscription - ${this.subscriptionName}`);
const subscription = pubsub.subscription(this.subscriptionName);
// Create an event handler to handle messages.
const messageHandler = (pubsubMessage) => {
this.robot.logger.debug(`Received message ${pubsubMessage.id}:`);
this.robot.logger.debug(`\tData: ${pubsubMessage.data}`);
const dataUtf8encoded = Buffer.from(pubsubMessage.data, 'base64').toString('utf8');
let event;
try {
event = JSON.parse(dataUtf8encoded);
} catch (ex) {
logging.warn('Bad request');
pubsubMessage.ack();
return;
}
this.onEventReceived(event, null);
// "Ack" (acknowledge receipt of) the message.
pubsubMessage.ack();
};
// Listen for new messages until timeout is hit.
subscription.on(`message`, messageHandler);
}
/*
* Invoked when Event is received from Hangouts Chat.
*/
onEventReceived(event, res) {
// TODO(kavimehta): Create and allow for additional message types
if (event.type != 'MESSAGE') {
this.robot.logger.info('Only MESSAGE event supported now !');
return;
}
let message = event.message;
let sender = message.sender;
// Construct TextMessage and User objects in the Hubot world
let userId = sender.name;
let userOptions = sender;
let user = new User(userId, userOptions);
let hangoutsChatTextMessage = new HangoutsChatTextMessage(
user,
message.argumentText,
message.name,
message.space,
message.thread,
message.createTime,
res);
// Pass the message to the Hubot bot
this.robot.receive(hangoutsChatTextMessage);
}
/*
* This is like the main method.
* Hubot invokes this method, when we use this adapter, to setup
* the bridge between Hubot and Hangouts Chat
*/
run() {
this.robot.logger.info('Running');
if (this.isPubSub) {
// Connect to PubSub subscription
this.startPubSubClient();
} else {
// Begin listening at HTTP endpoint
this.startHttpServer();
}
// To make Hubot load scripts
this.emit('connected')
}
}
module.exports = HangoutsChatBot
| JavaScript | 0.000001 | @@ -4996,48 +4996,8 @@
) %7B%0A
- this.robot.logger.info('Running');%0A%0A
@@ -5177,24 +5177,102 @@
r();%0A %7D%0A%0A
+ this.robot.logger.info('Hangouts Chat adapter initialized successfully');%0A
// To ma
|
bf75faaa9d13c3926f82f1cb8fbaf7bd46a910dc | Fix prefix trimming logic & move prefix to class var | src/bot.js | src/bot.js | const Discord = require('discord.js');
const glob = require('glob');
const path = require('path');
class Bot {
constructor() {
this.client = new Discord.Client();
this.token = 'MzAzMzI4NjQzNTUwMDE5NTg2.C9Wgwg.2SjC-LzYWuLNGPdhG0F0axdAqtM';
this.commands = {};
this.cmdCount = 0;
this.loadCommands();
this.client.on('ready', () => {
console.log('Thonking.');
});
}
thonk() {
this.client.login(this.token);
this.client.on('message', message => {
this.runCommand(message)
})
}
loadCommands() {
console.log('Loading commands...');
glob.sync(path.join(__dirname, 'commands/*.js')).forEach( file => {
this.addCommand(require(path.resolve(file)));
this.cmdCount++
});
console.log(this.commands);
console.log(`Finished loading ${this.cmdCount} commands.`)
}
addCommand(command) {
this.commands[command.command] = {
description: command.description,
execute: command.execute
}
}
runCommand(message) {
const prefix = '!';
const content = message.content;
if(content.startsWith(prefix)) {
const formattedContent = content.slice(prefix.length, content.length);
const commandArray = formattedContent.split(' ');
const command = commandArray[0];
const args = commandArray[1];
if(this.commands.hasOwnProperty(command)) {
const selectedCommand = this.commands[command];
selectedCommand.execute(this, message, args)
} else {
message.channel.sendMessage('Command not recognized. Try !help for a list of available commands.');
}
}
}
//client.on('message', message => {
// message.react(':thonking:291056594601377792')
//});
}
module.exports = Bot; | JavaScript | 0 | @@ -253,16 +253,50 @@
dAqtM';%0A
+ this.commandPrefix = '!';%0A
@@ -1188,35 +1188,50 @@
const prefix =
-'!'
+this.commandPrefix
;%0A const
@@ -1386,36 +1386,34 @@
h);%0A
-cons
+le
t commandArray =
@@ -1486,11 +1486,16 @@
rray
-%5B0%5D
+.shift()
;%0A
@@ -1533,11 +1533,18 @@
rray
-%5B1%5D
+.join(' ')
;%0A%0A
|
9d19e01a1bd307d3a76fa831d835efff78712ab6 | Fix #271 | src/bus.js | src/bus.js | "use strict";
var Bus = {};
/** @constructor */
function BusConnector()
{
this.listeners = {};
this.pair = undefined;
};
/**
* @param {string} name
* @param {function(*=)} fn
* @param {Object} this_value
*/
BusConnector.prototype.register = function(name, fn, this_value)
{
var listeners = this.listeners[name];
if(listeners === undefined)
{
listeners = this.listeners[name] = [];
}
listeners.push({
fn: fn,
this_value: this_value,
});
};
/**
* Unregister one message with the given name and callback
*
* @param {string} name
* @param {function()} fn
*/
BusConnector.prototype.unregister = function(name, fn)
{
var listeners = this.listeners[name];
if(listeners === undefined)
{
return;
}
this.listeners[name] = listeners.filter(function(l)
{
return l.fn !== fn
});
};
/**
* Send ("emit") a message
*
* @param {string} name
* @param {*=} value
* @param {*=} unused_transfer
*/
BusConnector.prototype.send = function(name, value, unused_transfer)
{
if(!this.pair)
{
return;
}
var listeners = this.pair.listeners[name];
if(listeners === undefined)
{
return;
}
for(var i = 0; i < listeners.length; i++)
{
var listener = listeners[i];
listener.fn.call(listener.this_value, value);
}
};
/**
* Send a message, guaranteeing that it is received asynchronously
*
* @param {string} name
* @param {Object=} value
*/
BusConnector.prototype.send_async = function(name, value)
{
dbg_assert(arguments.length === 1 || arguments.length === 2);
setTimeout(this.send.bind(this, name, value), 0);
};
Bus.create = function()
{
var c0 = new BusConnector();
var c1 = new BusConnector();
c0.pair = c1;
c1.pair = c0;
return [c0, c1];
};
| JavaScript | 0 | @@ -122,17 +122,16 @@
fined;%0A%7D
-;
%0A%0A/**%0A *
@@ -172,18 +172,17 @@
unction(
-*=
+?
)%7D fn%0A *
@@ -865,16 +865,17 @@
n !== fn
+;
%0A %7D);
|
a5c825ed645a785de1ea5246151bd18e141ace18 | Fix bugs. | src/cfg.js | src/cfg.js | 'use strict';
var logger = require('./log');
var path = require('path');
var chalk = require('chalk');
/**
* Resolve and configuration file path.
*
* @param {string} config
* @return {string}
*/
function resolveConfig(config) {
if (config[0] === '/') {
// Absolute
return config;
}
// Relative
return process.cwd() + '/' + config;
}
/**
* Resolve and require configuration value.
*
* @param {string|object} config
* @return {object}
*/
function requireConfig(config) {
if (typeof config === 'undefined') {
// Default value
config = 'view.json';
}
config = resolveConfig(config);
try {
config = require(config);
} catch (e) {
// Require default config file at SassDoc's level
config = require('../view.json');
}
}
/**
* Resolve and require package value.
*
* @param {string|object} package
* @return {object}
*/
function requirePackage(dir, package) {
if (typeof package === 'undefined') {
logger.log(chalk.yellow('No package information.'));
return;
}
var path = dir + '/' + package;
try {
return require(path);
} catch (e) {
var message = 'Can\'t find a package file at `' + path + '`.';
logger.log(chalk.yellow(message));
}
}
/**
* Resolve and require theme value.
*
* @param {string} theme
* @return {function}
*/
function requireTheme(theme) {
if (typeof theme === 'undefined') {
theme = 'default';
}
return require('sassdoc-theme-' + theme;
}
/**
* Parse configuration.
*
* @param {string|object} config
* @return {object}
*/
module.exports = function (config) {
// Relative directory for `package` file
var dir;
if (typeof config !== 'object') {
dir = path.dirname(config);
config = requireConfig(config);
} else {
// `package` is relative to CWD
dir = process.cwd();
}
// Resolve package
if (typeof config.package !== 'object') {
config.package = requirePackage(dir, config.package);
}
// Resolve theme
if (typeof config.theme !== 'function') {
config.theme = requireTheme(config.theme);
}
return config;
};
| JavaScript | 0 | @@ -502,37 +502,15 @@
if (
-typeof config === 'undefined'
+!config
) %7B%0A
@@ -604,32 +604,30 @@
try %7B%0A
-config =
+return
require(con
@@ -702,32 +702,30 @@
s level%0A
-config =
+return
require('..
@@ -878,22 +878,18 @@
e(dir, p
-ackage
+kg
) %7B%0A if
@@ -894,38 +894,12 @@
if (
-typeof package === 'undefined'
+!pkg
) %7B%0A
@@ -998,22 +998,18 @@
'/' + p
-ackage
+kg
;%0A%0A try
@@ -1301,36 +1301,14 @@
if (
-typeof theme === 'undefined'
+!theme
) %7B%0A
@@ -1376,16 +1376,17 @@
+ theme
+)
;%0A%7D%0A%0A/**
|
7e234e49a6a442e40a62b333555fa66a9a431b39 | Remove not checking package.json for changes (multimatch not working with paths) | src/cli.js | src/cli.js | #!/usr/bin/env node
import path from 'path';
import execa from 'execa';
import inquirer from 'inquirer';
import isGitClean from 'is-git-clean';
import meow from 'meow';
import updateNotifier from 'update-notifier';
function checkGitStatus(force) {
let clean = false;
let errorMessage = 'Unable to determine if git directory is clean';
try {
clean = isGitClean.sync(process.cwd(), { files: ['!package.json'] });
errorMessage = 'Git directory is not clean';
} catch (err) {
if (err && err.stderr && err.stderr.indexOf('Not a git repository') >= 0) {
clean = true;
}
}
const ENSURE_BACKUP_MESSAGE = 'Ensure you have a backup of your tests or commit the latest changes before continuing.';
if (!clean) {
if (force) {
console.log(`WARNING: ${errorMessage}. Forcibly continuing.`, ENSURE_BACKUP_MESSAGE);
} else {
console.log(
`ERROR: ${errorMessage}. Refusing to continue.`,
ENSURE_BACKUP_MESSAGE,
'You may use the --force flag to override this safety check.'
);
process.exit(1);
}
}
}
function executeTransformation(files, flags, transformer) {
const transformerPath = path.join(__dirname, 'transformers', `${transformer}.js`);
const args = ['-t', transformerPath].concat(files);
if (flags.dry) {
args.push('--dry');
}
if (['babel', 'babylon', 'flow'].indexOf(flags.parser) >= 0) {
args.push('--parser', flags.parser);
}
console.log(`Executing command: jscodeshift ${args.join(' ')}`);
const result = execa.sync(require.resolve('.bin/jscodeshift'), args, {
stdio: 'inherit',
stripEof: false,
});
if (result.error) {
throw result.error;
}
}
function executeTransformations(files, flags, transformers) {
transformers.forEach(t => {
executeTransformation(files, flags, t);
});
}
const cli = meow(
{
description: 'Codemods for migrating test files to Jest.',
help: `
Usage
$ jest-codemods <path> [options]
path Files or directory to transform. Can be a glob like src/**.test.js
Only files using Tape or AVA will be converted.
Options
--force, -f Bypass Git safety checks and forcibly run codemods
--dry, -d Dry run (no changes are made to files)
--parser The parser to use for parsing your source files (babel | babylon | flow) [babel]
`,
},
{
boolean: ['force', 'dry'],
string: ['_'],
alias: {
f: 'force',
h: 'help',
d: 'dry',
},
}
);
updateNotifier({ pkg: cli.pkg }).notify();
if (cli.input.length) {
// Apply all transformers if input is given using CLI.
if (!cli.flags.dry) {
checkGitStatus(cli.flags.force);
}
executeTransformations(cli.input, cli.flags, ['tape', 'ava']);
} else {
// Else show the fancy inquirer prompt.
inquirer.prompt([{
type: 'list',
name: 'transformer',
message: 'Which test library would you like to migrate from?',
choices: [{
name: 'Tape',
value: 'tape',
}, {
name: 'AVA',
value: 'ava',
}, {
name: 'All of the above!',
value: 'all',
}, {
name: 'Other',
value: 'other',
}],
}, {
type: 'input',
name: 'files',
message: 'On which files or directory should the codemods be applied?',
default: 'test.js test-*.js test/**/*.js **/__tests__/**/*.js **/*.test.js',
filter: files => files.trim().split(/\s+/).filter(v => v),
}]).then(answers => {
const { files, transformer } = answers;
if (transformer === 'other') {
console.log('\nCurrently jest-codemods only have support for AVA and Tape.');
console.log('Feel free to create an issue on https://github.com/skovhus/jest-codemods or help contribute!\n');
return;
}
if (!files.length) {
return;
}
if (!cli.flags.dry) {
checkGitStatus(cli.flags.force);
}
const transformers = transformer === 'all' ? ['tape', 'ava'] : [transformer];
transformers.forEach(t => {
executeTransformation(files, cli.flags, t);
});
});
}
| JavaScript | 0 | @@ -397,38 +397,8 @@
wd()
-, %7B files: %5B'!package.json'%5D %7D
);%0A
|
c6d1ffdb899a729d57c1277099402d44165f86f0 | Normalize arguments for packaged Electron app | src/cnc.js | src/cnc.js | /* eslint max-len: 0 */
/* eslint no-console: 0 */
import path from 'path';
import program from 'commander';
import pkg from './package.json';
// Defaults to 'production'
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const increaseVerbosityLevel = (val, total) => {
return total + 1;
};
const parseMountPoint = (val) => {
val = val || '';
if (val.indexOf(':') >= 0) {
let r = val.match(/(?:([^:]*)(?::(.*)))/);
return {
url: r[1] || '/static',
path: r[2]
};
}
return {
url: '/static',
path: val
};
};
const parseController = (val) => {
val = val ? (val + '').toUpperCase() : '';
if (val === 'GRBL' || val === 'SMOOTHIE' || val === 'TINYG') {
return val;
} else {
return '';
}
};
program
.version(pkg.version)
.usage('[options]')
.option('-p, --port <port>', 'set listen port (default: 8000)', 8000)
.option('-H, --host <host>', 'set listen address or hostname (default: 0.0.0.0)', '0.0.0.0')
.option('-b, --backlog <backlog>', 'set listen backlog (default: 511)', 511)
.option('-c, --config <filename>', 'set config file (default: ~/.cncrc)')
.option('-v, --verbose', 'increase the verbosity level (-v, -vv, -vvv)', increaseVerbosityLevel, 0)
.option('-m, --mount [<url>:]<path>', 'set the mount point for serving static files (default: /static:static)', parseMountPoint, { url: '/static', path: 'static' })
.option('-w, --watch-directory <path>', 'watch a directory for changes')
.option('--access-token-lifetime <lifetime>', 'access token lifetime in seconds or a time span string (default: 30d)')
.option('--allow-remote-access', 'allow remote access to the server (default: false)')
.option('--controller <type>', 'specify CNC controller: Grbl|Smoothie|TinyG (default: \'\')', parseController, '');
program.on('--help', () => {
console.log(' Examples:');
console.log('');
console.log(' $ cnc -vv');
console.log(' $ cnc --mount /pendant:/home/pi/tinyweb');
console.log(' $ cnc --watch-directory /home/pi/watch');
console.log(' $ cnc --access-token-lifetime 60d # e.g. 3600, 30m, 12h, 30d');
console.log(' $ cnc --allow-remote-access');
console.log(' $ cnc --controller Grbl');
console.log('');
});
// https://github.com/tj/commander.js/issues/512
// Commander assumes that process.argv[0] is 'node' and argv[1] is script name
if (process.argv.length > 1) {
program.parse(process.argv);
}
const cnc = (options = {}, callback) => {
// Change working directory to 'app' before require('./app')
process.chdir(path.resolve(__dirname, 'app'));
require('./app').createServer({
port: program.port,
host: program.host,
backlog: program.backlog,
configFile: program.config,
verbosity: program.verbose,
mount: program.mount,
watchDirectory: program.watchDirectory,
accessTokenLifetime: program.accessTokenLifetime,
allowRemoteAccess: !!program.allowRemoteAccess,
controller: program.controller,
...options // Override command-line options if specified
}, callback);
};
export default cnc;
| JavaScript | 0.000015 | @@ -2538,16 +2538,457 @@
gv);%0A%7D%0A%0A
+// Commander assumes that the first two values in argv are 'node' and appname, and then followed by the args.%0A// This is not the case when running from a packaged Electron app. Here you have the first value appname and then args.%0Aconst normalizedArgv = ('' + process.argv%5B0%5D).indexOf(pkg.name) %3E= 0%0A ? %5B'node', pkg.name, ...process.argv.slice(1)%5D%0A : process.argv;%0Aif (normalizedArgv.length %3E 1) %7B%0A program.parse(normalizedArgv);%0A%7D%0A%0A
const cn
|
04739d2530a9ada9f39ca661d01d95a462fbe7b3 | Update dlb.js | src/dlb.js | src/dlb.js | //dont-look-back
//by DOLLOR
~(function(global){
"use strict";
var obj,init;
obj={};
obj.enable=true
init=function(){
//封装改变hash方法
obj.changeHashTo=function(newhash){
newhash="#"+newhash;
if(history && history.pushState){
if(newhash!=="#"){
history.pushState({},document.title,newhash);
}
else{
history.pushState({},document.title,
location.href.split("#")[0]
);
}
}
else{
global.location.hash=newhash
}
};
//加倍改变
obj.changeManyTimes=function(newhash){
obj.changeHashTo(newhash+"#3");
obj.changeHashTo(newhash+"#2");
obj.changeHashTo(newhash+"#1");
obj.changeHashTo(newhash);
};
//保存旧的并设置新的
obj.setHash=function(newhash){
obj.lastHash=newhash;
obj.changeManyTimes(obj.lastHash);
};
obj.getHash=function(){
var hash=global.location.hash;
if(hash[0]==="#"){
hash=hash.slice(1);
}
return hash;
};
//响应并阻止后退
obj.preventBack=function(){
//获取改变后的hash
var newhash = obj.getHash();
//检查hash是否变了
if(obj.enable && newhash!==obj.lastHash){
//检查是后退还是前进
if(newhash===obj.lastHash+"#1"){
setTimeout(function(){
history.go(1);
},50)
}
else{
obj.setHash(newhash);
}
}
};
//当前想保持的hash
obj.lastHash=obj.getHash();
obj.changeManyTimes(obj.lastHash);
obj.preventBack();
if(global.addEventListener){
global.addEventListener("hashchange",function(ev){
obj.preventBack();
});
}
else if(global.attachEvent){
global.attachEvent("onhashchange",function(ev){
obj.preventBack();
});
}
else{
//global.onhashchange=obj.preventBack;
}
};
//output
if(!global.dlb){
init();
global.dlb=global.dlb || obj;
}
})(window);
| JavaScript | 0 | @@ -1640,47 +1640,289 @@
t%0A%09i
-f(!global.dlb)%7B%0A%09%09init();%0A%09%09global.dlb=
+nit();%0A%09// Node.js%0A%09if (typeof module !== 'undefined' && module.exports) %7B%0A%09%09module.exports = obj;%0A%09%7D%0A%09// AMD / RequireJS%0A%09else if (typeof define !== 'undefined' && define.amd) %7B%0A%09%09define(%5B%5D, function () %7B%0A%09%09%09return obj;%0A%09%09%7D);%0A%09%7D%0A%09// included directly via %3Cscript%3E tag%0A%09//else %7B%0A%09%09
glob
@@ -1932,17 +1932,18 @@
dlb
-%7C%7C
+=
obj;%0A%09
+//
%7D%0A%7D)
|
9da922c28d0ab9e01f42148d67bdb11dd9d70cde | remove isType function in component in favor of static types array | src/dom.js | src/dom.js | import { toArray } from './util'
export function $ (selector, el = document) {
return el.querySelector(selector)
}
export function $$ (selector, el = document) {
return toArray(el.querySelectorAll(selector))
}
export function id (name, el = document) {
return el.getElementById(name)
}
export function replace (oldElement, newElement) {
oldElement.parentNode.replaceChild(newElement, oldElement)
return newElement
}
export function index (el) {
let idx = 0
while (el) {
idx++
el = el.previousElementSibling
}
return idx
}
export function remove (el) {
el.parentNode && el.parentNode.removeChild(el)
return el
}
export function rect (el) {
const rect = el.getBoundingClientRect()
return {
top: window.pageYOffset + rect.top,
left: window.pageXOffset + rect.left,
width: rect.width,
height: rect.height
}
}
export function addClass (el, clazz) {
el.classList.add(clazz)
return el
}
export function toggleClass (el, clazz, force = undefined) {
el.classList.toggle(clazz, force)
return el
}
export function removeClass (el, clazz) {
el.classList.remove(clazz)
return el
}
export function getAttr (el, name, defaultValue = undefined) {
return el && el.hasAttribute(name) ? el.getAttribute(name) : defaultValue
}
export function setAttr (el, name, value, append = false) {
const attrValue = append ? getAttr(el, name, '') + ' ' + value : value
el.setAttribute(name, attrValue)
return el
}
export function hasAttr (el, name) {
return el && el.hasAttribute(name)
}
export function insertElement (position, node, newNode) {
switch (position) {
case 'beforebegin':
node.parentNode.insertBefore(newNode, node)
break
case 'afterend':
node.parentNode.insertBefore(newNode, node.nextElementSibling)
break
}
return newNode
}
insertElement.before = (node, newNode) => insertElement('beforebegin', node, newNode)
insertElement.after = (node, newNode) => insertElement('afterend', node, newNode)
export function component (name, init, opts = {}) {
function parseConfig (el) {
const confMatcher = new RegExp(`data-(?:component|${name})-([^-]+)`, 'i')
const defaultConf = {}
toArray(el.attributes).forEach(attr => {
const match = confMatcher.exec(attr.name)
if (confMatcher.test(attr.name)) {
defaultConf[match[1]] = attr.value
}
})
try {
const conf = JSON.parse(el.getAttribute('data-component-conf'))
return Object.assign(defaultConf, conf)
} catch (e) {
return defaultConf
}
}
opts = opts instanceof window.HTMLElement ? { root: opts } : opts
return $$(`[data-component~="${name}"]:not([data-component-ready~="${name}"])`, opts.root || document)
.map((el, index) => {
const def = el.getAttribute('data-component').split(' ')
const conf = Object.assign({}, init.DEFAULTS || {}, opts.conf || {}, parseConfig(el))
const options = {
index,
conf,
isType (type) {
return def.indexOf(`${name}-${type}`) !== -1
}
}
const component = init(el, options)
setAttr(el, 'data-component-ready', name, true)
return component
})
}
export default {
$,
$$,
id,
component,
replace,
index,
remove,
rect,
addClass,
toggleClass,
removeClass,
getAttr,
setAttr,
hasAttr,
insertElement
}
| JavaScript | 0.000012 | @@ -2929,16 +2929,61 @@
fig(el))
+%0A const componentPrefix = %60$%7Bname%7D-%60
%0A%0A
@@ -3057,83 +3057,88 @@
-isType (type) %7B%0A return def.indexOf(%60$%7Bname%7D-$%7Btype%7D%60) !== -1%0A
+types: def%0A .filter(name =%3E name.indexOf(componentPrefix) === 0)%0A
@@ -3141,25 +3141,73 @@
-%7D
+.map(name =%3E name.substr(componentPrefix.length))
%0A %7D
|
f509831272a137b420ea4e74cdd9b072807667e1 | make callback optional | src/hub.js | src/hub.js | 'use strict';
var bcrypt = require('bcrypt-nodejs'),
Server = require('socket.io'),
express = require('express'),
http = require('http'),
path = require('path'),
mongo = require('mongojs');
var util = require('util');
var session = require('./session');
var _ = require('lodash');
var cors = require('cors');
var _validTokens = {};
function throwErr (func) {
return function(err, data) {
if (err) {
throw err;
} else {
func.call(null, data);
}
};
}
function addApiCalls (hub, io, socket) {
function idSearch (id) {
return {_id: mongo.ObjectId(id)};
}
function _findScene (sceneId, cb) {
return hub.db.mediaScenes.findOne(idSearch(sceneId), cb);
}
socket.on('listScenes', function(callback) {
hub.db.mediaScenes.find({'$query': {}, '$orderby': {name: 1}}, {name: 1}, callback);
});
socket.on('saveScene', function(sceneData, callback) {
// convert _id so mongo recognizes it
if (sceneData.hasOwnProperty('_id')) {
sceneData._id = mongo.ObjectId(sceneData._id);
}
hub.db.mediaScenes.save(sceneData, function(err, scene) {
io.to(scene._id.toString()).emit('sceneUpdate', scene);
if (callback) {
callback(err, scene);
}
});
});
socket.on('loadScene', _findScene);
socket.on('deleteScene', function(sceneId, callback) {
hub.db.mediaScenes.remove(idSearch(sceneId), function(err) {
callback(err);
});
});
socket.on('subScene', function(sceneId, callback) {
_findScene(sceneId, function(err, scene) {
socket.join(sceneId);
if (callback) {
callback(err, scene);
}
});
});
socket.on('unsubScene', function(sceneId, callback) {
_findScene(sceneId, function(err, scene) {
socket.leave(sceneId);
if (callback) {
callback(err);
}
});
});
socket.on('sendCommand', function(sceneId, commandName, commandValue) {
io.to(sceneId).emit('command', {name: commandName, value: commandValue});
});
}
var Hub = function(config) {
this.config = config;
this.db = mongo.connect(config.mongo, ['mediaScenes', 'sessions']);
session.setClient(this.db);
};
Hub.prototype.listen = function(callback) {
var self = this,
app = express(),
server = http.Server(app),
io = new Server(server);
this.server = server;
app.use(cors());
// require a valid session token for all api calls
var validateSession = function(req, res, next) {
session.find(req.query.token, function(err, data) {
if (err || ! data) {
res.sendStatus(401);
} else {
next();
}
});
};
// allow cross origin requests
io.set('origins', '*:*');
io.sockets.on('connection', function (socket) {
var disconnectTimer = setTimeout(function() {
socket.disconnect();
}, 10000);
socket.on('auth', function (creds, callback) {
function succeed (record) {
addApiCalls(self, io, socket);
clearTimeout(disconnectTimer);
callback(null, record._id.toString());
}
function fail (msg) {
callback(msg);
socket.disconnect();
}
if (creds.hasOwnProperty('password') && creds.password && creds.password !== '') {
if ( bcrypt.compareSync(creds.password, self.config.secret) ) {
session.create(throwErr(succeed));
} else {
fail('Invalid Password');
}
} else if (creds.hasOwnProperty('token') && creds.token && creds.token !== '') {
session.find(creds.token, function(err, data) {
if (data) {
succeed(data);
} else {
fail('Invalid Token');
}
});
} else {
fail('Password must be provided');
}
});
});
server.listen(self.config.port, callback);
};
Hub.prototype.close = function(cb) {
this.server.close(cb);
};
module.exports = {
createHub: function(mongoUrl) {
return new Hub(mongoUrl);
}
};
| JavaScript | 0 | @@ -1559,38 +1559,88 @@
-callback(err);
+if (callback) %7B%0A callback(err); %0A %7D
%0A %7D);
|
7298b6c297cb61e9f268af7bdca7fa25ef117428 | Fix the date display. | appengine-experimental/src/static/javascript/traffic.js | appengine-experimental/src/static/javascript/traffic.js | var map;
var incident_markers = {};
function initialize() {
var zoom = 6;
if (supports_local_storage() && localStorage['map_zoom']) {
zoom = parseInt(localStorage['map_zoom']);
}
var center = new google.maps.LatLng(37.5, -119.2);
var wantGPScenter = true;
if (supports_local_storage() && localStorage['map_center_lat'] && localStorage['map_center_lng']) {
center = new google.maps.LatLng(localStorage['map_center_lat'], localStorage['map_center_lng']);
wantGPScenter = false;
}
var myOptions = {
zoom: zoom,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListener(map, 'zoom_changed', function() {
// save the zoom level for later use...
if (supports_local_storage()) {
localStorage['map_zoom'] = map.getZoom();
}
});
google.maps.event.addListener(map, 'dragend', function() {
// save the center for later use...
if (supports_local_storage()) {
localStorage['map_center_lat'] = map.getCenter().lat();
localStorage['map_center_lng'] = map.getCenter().lng();
}
});
if (wantGPScenter && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var gps_location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(gps_location);
});
}
update_incidents();
}
function update_incidents () {
jQuery.getJSON("/json", function (data) {
jQuery.each(data, function (i, incident) {
if (incident.geolocation && (incident.Status == "new" || incident.Status == "active")) {
var infowindow = new google.maps.InfoWindow({
content: '<div class="logtype">' + incident.LogType + '</div><div class="location">' + incident.Location + '</div><div class="area">' + incident.Area + '</div><div class="logtime">' + incident.LogTime + '</div>'
});
if (incident_markers[incident.ID]) {
// Marker exists, just update the info window...
google.maps.event.clearInstanceListeners(incident_markers[incident.ID]);
google.maps.event.addListener(incident_markers[incident.ID], 'click', function() {
infowindow.open(map, incident_markers[incident.ID]);
});
// and the icon
incident_markers[incident.ID].setIcon("http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=caution|FF0000");
} else {
var icon_url = (incident.Status == "new") ? "http://chart.apis.google.com/chart?chst=d_map_xpin_icon&chld=pin_star|caution|FF0000|FFFF00" : "http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=caution|FF0000";
var marker = new google.maps.Marker({
position: new google.maps.LatLng(incident.geolocation.lat, incident.geolocation.lon),
map: map,
title: incident.LogType,
icon: icon_url
});
var listener = google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
incident_markers[incident.ID] = marker;
}
} else if (incident.geolocation) {
// old incident
if (incident_markers[incident.ID]) {
incident_markers[incident.ID].setMap();
delete incident_markers[incident.ID];
}
}
});
setTimeout(update_incidents, 60000);
});
}
function clear_incidents() {
for (var x in incident_markers) {
incident_markers[x].setMap();
}
incident_markers = {};
}
function supports_local_storage() {
return ('localStorage' in window) && window['localStorage'] !== null;
}
| JavaScript | 0.000152 | @@ -1626,24 +1626,83 @@
active%22)) %7B%0A
+%09%09%09%09var logtime = new Date(incident.LogTimeEpoch * 1000);%0A%0A
%09%09%09%09var info
@@ -1928,32 +1928,40 @@
me%22%3E' +
-incident.LogTime
+logtime.toLocaleString()
+ '%3C/di
|
ca11e44f1639cc92d5014e5c226d8e259cb53ac6 | make hops-config use hops-root everywhere | packages/config/index.js | packages/config/index.js | 'use strict';
var fs = require('fs');
var path = require('path');
var appRoot = require('app-root-path');
var config = module.exports = {
buildConfig: require.resolve('./configs/build'),
developConfig: require.resolve('./configs/develop'),
renderConfig: require.resolve('./configs/render'),
locations: []
};
if (fs.existsSync(appRoot.resolve('package.json'))) {
Object.assign(config, appRoot.require('package.json').hops);
}
if (fs.existsSync(appRoot.resolve('hops.config.js'))) {
Object.assign(config, appRoot.require('hops.config.js'));
}
['buildConfig', 'developConfig', 'renderConfig'].forEach(function (key) {
if (!path.isAbsolute(config[key])) {
config[key] = appRoot.resolve(config[key]);
}
});
| JavaScript | 0.000001 | @@ -65,19 +65,20 @@
);%0A%0Avar
-app
+hops
Root = r
@@ -89,21 +89,17 @@
re('
-app
+hops
-root
--path
');%0A
@@ -320,35 +320,36 @@
(fs.existsSync(
-app
+hops
Root.resolve('pa
@@ -381,35 +381,36 @@
.assign(config,
-app
+hops
Root.require('pa
@@ -450,19 +450,20 @@
stsSync(
-app
+hops
Root.res
@@ -513,19 +513,20 @@
config,
-app
+hops
Root.req
@@ -688,11 +688,12 @@
%5D =
-app
+hops
Root
|
0d4568176d9d58f95fb585be5726f3859902d14f | Update config for production | config/webpack/server/production.js | config/webpack/server/production.js | const _ = require("lodash");
const webpack = require("webpack");
const BabiliPlugin = require("babili-webpack-plugin");
const defaultConfig = require("./default");
const productionConfig = require("./default");
_.mergeWith(defaultConfig, {
devtool: false
});
productionConfig.plugins.push(
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new BabiliPlugin({}, {
comments: false
}),
new webpack.DefinePlugin({
"process.env.NODE_ENV": "'production'",
"process.env.SERVER_RENDERING": true
})
);
module.exports = productionConfig;
| JavaScript | 0 | @@ -1,33 +1,4 @@
-const _ = require(%22lodash%22);%0A
cons
@@ -94,141 +94,46 @@
nst
-defaultConfig = require(%22./default%22);%0Aconst productionConfig = require(%22./default%22);%0A%0A_.mergeWith(defaultConfig, %7B%0A devtool: false%0A%7D
+productionConfig = require(%22./default%22
);%0A%0A
|
3edd1c55503082132717dcb3d2ab57b5f1e62117 | Add getGridData test to apiSpec. | test/apiSpec.js | test/apiSpec.js | // helper functions defined in helpers.js
var data = generateData(10);
var columns = getColumns(data);
describe("sensei-grid api", function () {
var grid;
var $el = $('<div class="sensei-grid-test">');
// create dom element before each test
beforeEach(function () {
// suppress console.log statements from src files
console.log = function () {};
// create wrapper element
$("body").append($el);
// render grid
grid = $el.grid(data, columns);
grid.render();
});
// remove grid wrapper after each test
afterEach(function () {
$(".sensei-grid-test").remove();
grid = null;
});
describe("getRowDataByIndex", function () {
it("should return data by positive index", function () {
expect(grid.getRowDataByIndex(0)).toEqual(data[0]);
expect(grid.getRowDataByIndex(1)).toEqual(data[1]);
expect(grid.getRowDataByIndex(9)).toEqual(data[9]);
});
it("should return data by negative index", function () {
expect(grid.getRowDataByIndex(-1)).toEqual(data[9]);
});
it("should throw error when row is not found", function () {
expect(function () { grid.getRowDataByIndex(100) }).toThrowError("Row does not exist");
expect(function () { grid.getRowDataByIndex(-100) }).toThrowError("Row does not exist");
expect(function () { grid.getRowDataByIndex("foo") }).toThrowError("Row does not exist");
});
});
describe("getRowData", function () {
it("should return row data", function () {
var $row = $(".sensei-grid-test>table>tbody>tr");
expect(grid.getRowData($row.eq(0))).toEqual(data[0]);
expect(grid.getRowData($row.eq(1))).toEqual(data[1]);
expect(grid.getRowData($row.eq(9))).toEqual(data[9]);
});
});
describe("getRowCells", function () {
it("should return row cells", function () {
var $row = $(".sensei-grid-test>table>tbody>tr:first");
expect(grid.getRowCells($row).length).toEqual(5);
expect(grid.getRowCells($row).get()).toEqual($row.find(">td").get());
});
});
describe("getCellDataByIndex", function () {
it("should return cell data by index", function () {
expect(grid.getCellDataByIndex(0,0)).toEqual(data[0]["id"]);
expect(grid.getCellDataByIndex(5,4)).toEqual(data[5]["count"]);
});
it("should return cell data by negative index", function () {
expect(grid.getCellDataByIndex(-1,0)).toEqual(data[9]["id"]);
expect(grid.getCellDataByIndex(0,-1)).toEqual(data[0]["count"]);
});
});
describe("getCellDataByKey", function () {
it("should return cell data by key", function () {
expect(grid.getCellDataByKey(0, "created_at")).toEqual(data[0]["created_at"]);
expect(grid.getCellDataByKey(1, "title")).toEqual(data[1]["title"]);
expect(grid.getCellDataByKey(9, "id")).toEqual(data[9]["id"]);
});
it("should throw error when cell or row is not found", function () {
expect(function () { grid.getCellDataByKey(0,"key_from_outer_space") }).toThrowError("Cell does not exist");
expect(function () { grid.getCellDataByKey(100,"title") }).toThrowError("Row does not exist");
});
});
}); | JavaScript | 0 | @@ -3433,12 +3433,181 @@
%0A %7D);
+%0A%0A describe(%22getGridData%22, function () %7B%0A it(%22should return grid data%22, function () %7B%0A expect(grid.getGridData()).toEqual(data);%0A %7D);%0A %7D);
%0A%7D);
|
e589d0eaebd2c99a1a3b945d7c2368bb33ec1449 | update aegir | test/browser.js | test/browser.js | /* eslint-env mocha */
'use strict'
const eachSeries = require('async/eachSeries')
const Store = require('idb-pull-blob-store')
const _ = require('lodash')
const IPFSRepo = require('ipfs-repo')
const pull = require('pull-stream')
const repoContext = require.context('buffer!./example-repo', true)
const basePath = 'ipfs' + Math.random()
const idb = window.indexedDB ||
window.mozIndexedDB ||
window.webkitIndexedDB ||
window.msIndexedDB
idb.deleteDatabase(basePath)
idb.deleteDatabase(basePath + '/blocks')
describe('Browser', () => {
before((done) => {
const repoData = []
repoContext.keys().forEach((key) => {
repoData.push({
key: key.replace('./', ''),
value: repoContext(key)
})
})
const mainBlob = new Store(basePath)
const blocksBlob = new Store(basePath + '/blocks')
eachSeries(repoData, (file, cb) => {
if (_.startsWith(file.key, 'datastore/')) {
return cb()
}
const blocks = _.startsWith(file.key, 'blocks/')
const blob = blocks ? blocksBlob : mainBlob
const key = blocks ? file.key.replace(/^blocks\//, '') : file.key
pull(
pull.values([file.value]),
blob.write(key, cb)
)
}, done)
})
const repo = new IPFSRepo(basePath, { stores: Store })
require('./basics')(repo)
require('./ipld-dag-pb')(repo)
require('./ipld-dag-cbor')(repo)
require('./ipld-eth-block')(repo)
require('./ipld-all')
})
| JavaScript | 0.000015 | @@ -16,16 +16,35 @@
ocha */%0A
+/* global self */%0A%0A
'use str
@@ -364,22 +364,20 @@
t idb =
-window
+self
.indexed
@@ -384,22 +384,20 @@
DB %7C%7C%0A
-window
+self
.mozInde
@@ -407,22 +407,20 @@
DB %7C%7C%0A
-window
+self
.webkitI
@@ -437,14 +437,12 @@
%7C%0A
-window
+self
.msI
|
9a6da82179dd789a7dc1d680139e530486cd27c0 | test alternate script eval for async-require | src/main/shadow/build/async-closure-import.js | src/main/shadow/build/async-closure-import.js | var CLOSURE_IMPORT_SCRIPT = (function() {
if (typeof(window.fetch) === 'undefined') {
return undefined;
}
var loadOrder = [];
var loadState = {};
function responseText(response) {
// FIXME: check status
return response.text();
}
function loadPending() {
for (var i = 0, len = loadOrder.length; i < len; i++) {
var uri = loadOrder[i];
var state = loadState[uri];
if (typeof(state) === "string") {
var code = state + "\n//# sourceURL=" + uri + "\n";
eval(code);
loadState[uri] = true;
} else if (state === true) {
continue;
} else {
break;
}
}
}
function evalFetch(uri) {
return function(code) {
loadState[uri] = code;
loadPending();
};
}
return function closure_fetch(uri) {
if (loadState[uri] == undefined) {
loadState[uri] = false;
loadOrder.push(uri);
fetch(uri).then(responseText).then(evalFetch(uri));
}
};
})();
| JavaScript | 0 | @@ -245,24 +245,417 @@
ext();%0A %7D%0A%0A
+ // apparently calling eval causes the code to never be optimized%0A // creating a script node, appending it and removing it seems to%0A // have the same effect without the speed penalty?%0A function scriptEval(code) %7B%0A var node = document.createElement(%22script%22);%0A node.appendChild(document.createTextNode(code));%0A document.body.append(node);%0A document.body.removeChild(node);%0A %7D%0A%0A
function l
@@ -665,24 +665,46 @@
Pending() %7B%0A
+ var loadNow = %22%22;%0A
for (var
@@ -851,24 +851,53 @@
%22string%22) %7B%0A
+ if (state != %22%22) %7B%0A
var
@@ -952,17 +952,25 @@
-e
+ scriptE
val(code
@@ -968,24 +968,34 @@
Eval(code);%0A
+ %7D%0A
load
|
90d00c10b1940cc92e6474d048236b6fb70b7f53 | Make metadata-manager a bit more robust | www/common/metadata-manager.js | www/common/metadata-manager.js | define(['json.sortify'], function (Sortify) {
var UNINIT = 'uninitialized';
var create = function (sframeChan) {
var meta = UNINIT;
var members = [];
var metadataObj = UNINIT;
// This object reflects the metadata which is in the document at this moment.
// Normally when a person leaves the pad, everybody sees them leave and updates
// their metadata, this causes everyone to fight to change the document and
// operational transform doesn't like it. So this is a lazy object which is
// only updated either:
// 1. On changes to the metadata that come in from someone else
// 2. On changes connects, disconnects or changes to your own metadata
var metadataLazyObj = UNINIT;
var priv = {};
var dirty = true;
var changeHandlers = [];
var lazyChangeHandlers = [];
var titleChangeHandlers = [];
var rememberedTitle;
var checkUpdate = function (lazy) {
if (!dirty) { return; }
if (meta === UNINIT) { throw new Error(); }
if (metadataObj === UNINIT) {
metadataObj = {
defaultTitle: meta.doc.defaultTitle,
//title: meta.doc.defaultTitle,
type: meta.doc.type,
users: {}
};
metadataLazyObj = JSON.parse(JSON.stringify(metadataObj));
}
if (!metadataObj.users) { metadataObj.users = {}; }
if (!metadataLazyObj.users) { metadataLazyObj.users = {}; }
var mdo = {};
// We don't want to add our user data to the object multiple times.
//var containsYou = false;
//console.log(metadataObj);
Object.keys(metadataObj.users).forEach(function (x) {
if (members.indexOf(x) === -1) { return; }
mdo[x] = metadataObj.users[x];
/*if (metadataObj.users[x].uid === meta.user.uid) {
//console.log('document already contains you');
containsYou = true;
}*/
});
//if (!containsYou) { mdo[meta.user.netfluxId] = meta.user; }
if (!priv.readOnly) {
mdo[meta.user.netfluxId] = meta.user;
}
metadataObj.users = mdo;
var lazyUserStr = JSON.stringify(metadataLazyObj.users[meta.user.netfluxId]);
dirty = false;
if (lazy || lazyUserStr !== JSON.stringify(meta.user)) {
metadataLazyObj = JSON.parse(JSON.stringify(metadataObj));
lazyChangeHandlers.forEach(function (f) { f(); });
}
if (metadataObj.title !== rememberedTitle) {
console.log("Title update\n" + metadataObj.title + '\n');
rememberedTitle = metadataObj.title;
titleChangeHandlers.forEach(function (f) { f(metadataObj.title); });
}
changeHandlers.forEach(function (f) { f(); });
};
var change = function (lazy) {
dirty = true;
setTimeout(function () {
checkUpdate(lazy);
});
};
console.log('here register');
sframeChan.on('EV_METADATA_UPDATE', function (ev) {
meta = ev;
if (ev.priv) {
priv = ev.priv;
}
change(true);
});
sframeChan.on('EV_RT_CONNECT', function (ev) {
meta.user.netfluxId = ev.myID;
members = ev.members;
change(true);
});
sframeChan.on('EV_RT_JOIN', function (ev) {
members.push(ev);
change(false);
});
sframeChan.on('EV_RT_LEAVE', function (ev) {
var idx = members.indexOf(ev);
if (idx === -1) { console.log('Error: ' + ev + ' not in members'); return; }
members.splice(idx, 1);
change(false);
});
sframeChan.on('EV_RT_DISCONNECT', function () {
members = [];
change(true);
});
return Object.freeze({
updateMetadata: function (m) {
// JSON.parse(JSON.stringify()) reorders the json, so we have to use sortify even
// if it's on our own computer
if (Sortify(metadataLazyObj) === Sortify(m)) { return; }
metadataObj = JSON.parse(JSON.stringify(m));
metadataLazyObj = JSON.parse(JSON.stringify(m));
change(false);
},
updateTitle: function (t) {
metadataObj.title = t;
change(true);
},
getMetadata: function () {
checkUpdate(false);
return Object.freeze(JSON.parse(JSON.stringify(metadataObj)));
},
getMetadataLazy: function () {
return metadataLazyObj;
},
onTitleChange: function (f) { titleChangeHandlers.push(f); },
onChange: function (f) { changeHandlers.push(f); },
onChangeLazy: function (f) { lazyChangeHandlers.push(f); },
isConnected : function () {
return members.indexOf(meta.user.netfluxId) !== -1;
},
getViewers : function () {
checkUpdate(false);
var list = members.slice().filter(function (m) { return m.length === 32; });
return list.length - Object.keys(metadataObj.users).length;
},
getPrivateData : function () {
return priv;
},
getUserData : function () {
return meta.user;
},
getNetfluxId : function () {
return meta.user.netfluxId;
}
});
};
return Object.freeze({ create: create });
});
| JavaScript | 0.000133 | @@ -2398,27 +2398,20 @@
erStr =
-JSON.string
+Sort
ify(meta
@@ -2518,27 +2518,20 @@
Str !==
-JSON.string
+Sort
ify(meta
@@ -4339,16 +4339,52 @@
omputer%0A
+ if (!m) %7B return; %7D%0A
|
6bb748e06be938429a4e7925d0da0f275f37c9fc | Update googleplayservices.js | www/googleplayservices.js | www/googleplayservices.js | var argscheck = require ('cordova/argscheck')
var exec = require ('cordova/exec')
module.exports = function () {
var exports = {}
exports.getPlayerId = function (init) {
var success = (typeof init.success != "undefined") ? init.success : function () {}
var error = (typeof init.error != "undefined") ? init.error : function () {}
cordova.exec (success, error, "GooglePlayServices", "getPlayerId", [])
}
exports.initialize = function (init) {
var success = (typeof init.success != "undefined") ? init.success : function () {}
var error = (typeof init.error != "undefined") ? init.error : function () {}
cordova.exec (success, error, "GooglePlayServices", "doInitialize", [])
}
return exports
} ()
| JavaScript | 0.000001 | @@ -690,20 +690,18 @@
%22, %22
-doInitialize
+tryConnect
%22, %5B
|
f5b77fb23a082842d1fff46c41701a395174eab8 | Use correct current url | endScript.js | endScript.js | function extractPageFeeds() {
var feeds = {};
feeds["site"] = getBaseURL();
feeds["list"] = [];
var headLinks = document.getElementsByTagName("head")[0].getElementsByTagName("link");
for (var i = 0; i < headLinks.length; i++) {
var link = headLinks[i];
if (link.attributes.getNamedItem("rel") !== null && link.attributes.getNamedItem("rel").value == "alternate") {
var type = link.attributes.getNamedItem("type");
if (type !== null) {
var typeValue = type.value;
if (typeValue === "application/rss+xml" || typeValue === "application/atom+xml" || typeValue === "text/xml") {
var href = link.attributes.getNamedItem("href").value;
if (href) {
feeds["list"].push({url: fullURL(href), title: titleFromType(typeValue), type: typeFromString(typeValue)});
}
}
}
}
}
safari.self.tab.dispatchMessage("extractedFeeds", feeds);
}
function protocol(url) {
return url.split(":")[0];
}
function typeFromString(string) {
if (string.indexOf("rss") != -1) {
return "RSS";
} else if (string.indexOf("atom") != -1) {
return "Atom";
} else {
return "Unknown";
}
}
function titleFromType(type) {
if (type.indexOf("rss") != -1) {
return "RSS Feed";
} else if (type.indexOf("atom") != -1) {
return "Atom Feed";
} else {
return "Feed";
}
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
function getBaseURL() {
var head = document.getElementsByTagName("head")[0];
var baseLinks = head.getElementsByTagName("base");
var baseURL;
for (var i=0; i < baseLinks.length; i++) {
var link = baseLinks[i];
if (link.attributes.getNamedItem("href") !== null) {
url = link.attributes.getNamedItem("href").value;
if (url.charAt(url.length - 1) != "/") {
url += "/";
}
baseURL = url;
break;
}
}
if (baseURL === undefined) {
baseURL = protocol(document.URL) + "://" + document.domain + "/"
}
return baseURL;
}
function fullURL(url) {
var trimmedURL = url.trim();
var protocol = trimmedURL.substr(0,4);
if (protocol !== "http" && protocol !== "feed") {
if (trimmedURL[0] == "/") {
trimmedURL = trimmedURL.slice(1);
}
trimmedURL = getBaseURL() + trimmedURL;
}
return trimmedURL;
}
function populatePopover() {
var popover = safari.extension.popovers[0];
popover.width = 300;
popover.height = 100;
}
if (window.top === window) {
if (document.domain !== "undefined") {
extractPageFeeds();
}
}
| JavaScript | 0.000123 | @@ -59,28 +59,36 @@
ite%22%5D =
-getBaseURL()
+window.location.href
;%0A feed
|
6027d67ee66a3daa164111853fe8486f38fe1565 | Fix show/hide slide out menu onresize :tada: | assets/js/main.js | assets/js/main.js | 'use strict';
var navMenu = navMenu || {};
navMenu = function() {
this.init = function() {
$('html').addClass('menu_mobile');
$('.menu-btn').on('click', function() {
$('body').hasClass('menu--active') ? app.hide() : app.show();
});
}
this.hide = function() {
$('nav').velocity({
translateX: '0%'
}, {
duration: 100,
easing: 'spring'
}).velocity({
display: 'block',
duration: 100
}), $('body').removeClass('menu--active');
$("#overlay").velocity({
opacity: 0,
translateX: '0%',
easing: 'spring'
}, 100 );
}
this.show = function() {
$('nav').velocity({
opacity: 1
}, {
display: 'block',
duration: 100
}).velocity({
translateX: '-108%'
}, {
duration: 600,
easing: 'spring'
}), $('body').addClass('menu--active');
$("#overlay").velocity({
opacity: 1,
backgroundColor: '#01AD99',
translateX: '-100%',
easing: 'spring'
}, 100);
}
this.init();
};
var app = new navMenu();
| JavaScript | 0 | @@ -52,24 +52,25 @@
u = function
+
() %7B%0A%0A this
@@ -77,32 +77,33 @@
.init = function
+
() %7B%0A %0A $(
@@ -171,32 +171,33 @@
click', function
+
() %7B%0A $('bo
@@ -253,16 +253,225 @@
show();%0A
+ %7D)%0A %0A $(window).on('resize', function () %7B%0A %0A var win = $(this);%0A %0A if (win.width() %3E= 1024 && $('body').hasClass('menu--active')) %7B%0A %0A app.hide();%0A %0A %7D%0A
%7D);%0A
@@ -488,32 +488,33 @@
.hide = function
+
() %7B%0A %0A $(
@@ -723,33 +723,33 @@
%0A %0A $(
-%22
+'
#overlay
%22).velocity(
@@ -728,33 +728,33 @@
%0A $('#overlay
-%22
+'
).velocity(%7B%0A
@@ -855,16 +855,17 @@
function
+
() %7B%0A
@@ -1111,17 +1111,17 @@
$(
-%22
+'
#overlay
%22).v
@@ -1120,9 +1120,9 @@
rlay
-%22
+'
).ve
|
b9ab427cf1646e88cdc0b69e07a19cfe82addb08 | Improve clearity in answers and questions for metoder | build/metoder.js | build/metoder.js | var data = {
"title": "Metoder",
"questions": [
{
"description": "Datatypen list är ett exempel på inbyggda objekt i Python",
"alternatives": ["Sant", "Falskt"],
"answer": "Sant"
}, {
"description": "Vilket uttryck returnerar heltalet 2?",
"gist_id": "17828f77063ab3946c22",
"alternatives": ["x.count('ä')", "x.find('det där')", "x.strip()"],
"answer": "x.count('ä')"
}, {
"description": "Vilket uttryck returnerar en exakt kopia av x?",
"alternatives": ["x.strip().title()", "x.lstrip().replace('aldrig', 'ofta')", "x.split('!')[0] + '!'"],
"answer": "x.split('!')[0] + '!'"
}, {
"description": "Vilket av följande uttryck returnerar ett värde?",
"gist_id": "90bad65e763b70b7c115",
"alternatives": ["x.remove(5)", "x.pop(5)", "x.append(5)"],
"answer": "x.pop(5)"
}, {
"description": "Vilken av följande uttryck förändrar inte x?",
"alternatives": ["x.reverse()", "x.sort()", "x.pop()"],
"answer": "x.sort()"
}
]
}
| JavaScript | 0.000001 | @@ -264,39 +264,54 @@
ption%22: %22Vilket
-uttryck
+av f%C3%B6ljande alternativ
returnerar helt
@@ -856,28 +856,28 @@
%22: %22
-90bad65e763b70b7c115
+417010f657e678e8a7f0
%22,%0A
@@ -905,17 +905,19 @@
ves%22: %5B%22
-x
+seq
.remove(
@@ -918,25 +918,27 @@
emove(5)%22, %22
-x
+seq
.pop(5)%22, %22x
@@ -936,17 +936,19 @@
p(5)%22, %22
-x
+seq
.append(
@@ -976,17 +976,19 @@
swer%22: %22
-x
+seq
.pop(5)%22
@@ -1071,17 +1071,19 @@
ar inte
-x
+seq
?%22,%0A
@@ -1108,17 +1108,19 @@
ves%22: %5B%22
-x
+seq
.reverse
@@ -1125,17 +1125,19 @@
se()%22, %22
-x
+seq
.sort()%22
@@ -1139,17 +1139,19 @@
rt()%22, %22
-x
+seq
.pop()%22%5D
@@ -1175,17 +1175,19 @@
swer%22: %22
-x
+seq
.sort()%22
|
2b71556bc6b95624f91a883745258b8cd69801a1 | Add GA event when user reaches bottom of page | assets/js/main.js | assets/js/main.js | $(document).ready(function () {
/* Add the current year to the footer */
function getYear() {
var d = new Date();
var n = d.getFullYear();
return n.toString();
}
$('#year').html(getYear());
});
| JavaScript | 0 | @@ -225,12 +225,341 @@
ar());%0A%0A
+ (function()%7B%0A var triggered = false;%0A $(window).scroll(function () %7B%0A if (($(window).scrollTop() %3E= $(document).height() - $(window).height() - 10) && !triggered) %7B%0A triggered = true;%0A ga('send', 'event', 'Page', 'Scroll', 'Bottom');%0A %7D%0A %7D);%0A %7D)()%0A%0A
%7D);%0A
|
660a617ce9f74bd5df1058d9d1608fc48e3f3410 | Update main.js | assets/js/main.js | assets/js/main.js | // To make images retina, add a class "2x" to the img element
// and add a <image-name>@2x.png image. Assumes jquery is loaded.
function isRetina() {
var mediaQuery = "(-webkit-min-device-pixel-ratio: 1.5),\
(min--moz-device-pixel-ratio: 1.5),\
(-o-min-device-pixel-ratio: 3/2),\
(min-resolution: 1.5dppx)";
if (window.devicePixelRatio > 1)
return true;
if (window.matchMedia && window.matchMedia(mediaQuery).matches)
return true;
return false;
};
function retina() {
if (!isRetina())
return;
$("img.2x").map(function(i, image) {
var path = $(image).attr("src");
path = path.replace(".png", "@2x.png");
path = path.replace(".jpg", "@2x.jpg");
$(image).attr("src", path);
});
};
$(document).ready(retina);
$(document).ready(function() {
//为超链接加上target='_blank'属性
$('a[href^="http"]').each(function() {
$(this).attr('target', '_blank');
});
});
| JavaScript | 0.000001 | @@ -840,22 +840,8 @@
$('a
-%5Bhref%5E=%22http%22%5D
').e
|
9042e55fb1676dcd4b8d3b1e6aa3f0565a6a8bf1 | Update tags.js | assets/js/tags.js | assets/js/tags.js | /*标签的js */
/**
* 分类展示
* 点击左侧的标签展示时
* 右侧的相关裂变展开或者收起
* @return {[type]} [description]
*/
function tagDisplay() {
/*only show first tag*/
var $first_tag_posts=$('.post-list-body').find('div:first');
$first_tag_posts.nextAll().hide();
//初始化第一个标签的隐藏文章
$first_tag_posts.find("a.post-list-item").hide();//隐藏文章
$first_tag_posts.find("a.post-list-item").slice(0,2).show();//显示文章
/*show tag when click tag list*/
$('.tag').click(function() {
var cate = $(this).attr('cate'); //get tag's name
var $cur_tag_posts=$(document.getElementsByName(cate)[0]);
$('.post-list-body>div').hide(250);
$cur_tag_posts.show(400);
//隐藏该标签下的部分文章
$cur_tag_posts.find("a.post-list-item").hide();//隐藏文章
$cur_tag_posts.find("a.post-list-item").slice(0,2).show();//显示文章
});
}
/**
*生成分页
*/
function generatePagi() {
$("div.pagination .inline-list li a").on("click",function(){
tag_reset();//复原操作
//给当前a标签添加class为cur_page
$(this).addClass("current-page");
var cur_page=$(this).attr("cur_page");//得到点击的页码
var $cur_tag_posts=$(this).closest("div.pagination");//得到当前的tag
//判断页码-1<=(可选的页数/2)
if(cur_page-1>2){
$cur_tag_posts.find("a.post-list-item").hide();//隐藏文章
alert(cur_page);
$cur_tag_posts.find("a.post-list-item").slice((cur_page-1)*2,cur_page*2).show();//显示文章
//隐藏所有页码
$cur_tag_posts.find("div.pagination").find("li").hide();
//显示五个页码slice(cur_page-2-1,cur_page+2+1)
$cur_tag_posts.find("div.pagination").find("li").slice(cur_page-2-1,cur_page+2).show();
//$cur_tag_posts.find("a[cur_page='"+(cur_page-2)+"']").closest("li").prevAll().hide();//隐藏页码
//$cur_tag_posts.find("a[cur_page='"+(cur_page+2)+"']").closest("li").nextAll().show();//显示页码
}else{//判断页码-总页数>=(可选的页数/2)
$cur_tag_posts.find("a.post-list-item").hide();//隐藏文章
$cur_tag_posts.find("a.post-list-item").slice((cur_page-1)*2,cur_page*2).show();//显示文章
//隐藏所有页码
$cur_tag_posts.find("div.pagination").find("li").hide();
//显示五个页码slice(cur_page-2-1,cur_page+2+1)
$cur_tag_posts.find("div.pagination").find("li").slice(0,cur_page+2).show();
// $cur_tag_posts.find("a[cur_page='"+(cur_page+2)+"']").closest("li").nextAll().hide();//隐藏页码
// $cur_tag_posts.find("a[cur_page='"+(cur_page-2)+"']").closest("li").prevAll().show();//显示页码
}
});
//前一页
$("div.pagination strong.prev").on("click",function(){
var $cur_tag_posts=$(this).closest("div.pagination");//得到当前的tag
var cur_page=$cur_tag_posts.find("a.current-page").attr("cur_page");//获取当前的页码
tag_reset();//复原操作
var prev_page=cur_page-1;//获取前一页的页码
if(prev_page>0){
//给前一个页码添加current-page样式
$cur_tag_posts.find("a[cur_page='"+(prev_page)+"']").attrClass("current-page");
$cur_tag_posts.find("a.post-list-item").hide();//隐藏文章
$cur_tag_posts.find("a.post-list-item").slice((prev_page-1)*2,prev_page*2).show();//显示文章
}
});
//后一页
$("div.pagination strong.next").on("click",function(){
var $cur_tag_posts=$(this).closest("div.pagination");//得到当前的tag
var cur_page=$cur_tag_posts.find("a.current-page").attr("cur_page");//获取当前的页码
tag_reset();//复原操作
var next_page=cur_page+1;//获取下一页
var total_page=$cur_tag_posts.find("a:last").attr("cur_page");//总的页数
if(next_page<=total_page){
$cur_tag_posts.find("a[cur_page='"+(next_page)+"']").attrClass("current-page");//给前一个页码添加current-page样式
$cur_tag_posts.find("a.post-list-item").hide();//隐藏文章
$cur_tag_posts.find("a.post-list-item").slice((next_page+1)*2,next_page*2).show();//显示文章
}
});
}
/**
复原操作,在所有点击操作之前发生一次
*/
function tag_reset(){
//1.清除所有的class为cur_page的a标签
$("div.pagination a").removeClass("current-page");
//2.隐藏所有文章
$("a.post-list-item").hide();
//3.显示所有的页码
$("div.pagination li").show();
}
// FitVids options
$(function() {
tagDisplay();
generatePagi();
});
| JavaScript | 0 | @@ -1140,33 +1140,37 @@
osest(%22div.p
-agination
+ost-list-body
%22);//%E5%BE%97%E5%88%B0%E5%BD%93%E5%89%8D%E7%9A%84ta
@@ -2649,33 +2649,37 @@
osest(%22div.p
-agination
+ost-list-body
%22);//%E5%BE%97%E5%88%B0%E5%BD%93%E5%89%8D%E7%9A%84ta
@@ -3294,25 +3294,29 @@
t(%22div.p
-agination
+ost-list-body
%22);//%E5%BE%97%E5%88%B0%E5%BD%93
|
c7d508c7135e7d7569b0a0c3c69c88051f4334c1 | update blueprint | blueprints/ember-frost-text/index.js | blueprints/ember-frost-text/index.js | module.exports = {
description: '',
normalizeEntityName: function () {},
/**
Installs specified packages at the root level of the application.
Triggered by 'ember install <addon name>'.
@returns {Promise} package names and versions
*/
afterInstall: function () {
return this.addAddonsToProject({
packages: [
{name: 'ember-frost-theme', target: '^1.2.0'}
]
})
}
}
| JavaScript | 0 | @@ -387,9 +387,9 @@
'%5E1.
-2
+3
.0'%7D
|
2b74861c9c19cd12f5a3ae89a96d3753cbb6747d | Remove pending RubyGemsRefresh spec | spec/javascripts/rubygemsRefreshSpec.js | spec/javascripts/rubygemsRefreshSpec.js | describe('RubyGemsRefresh.init', function() {
beforeEach(function() {
var fixtures = [
"<div class='rubygems' style='display: none;'>",
"</div>"
].join("\n");
setFixtures(fixtures);
jasmine.clock().install();
jasmine.Ajax.install();
});
afterEach(function() {
RubyGemsRefresh.cleanupTimeout();
jasmine.clock().uninstall();
jasmine.Ajax.uninstall();
});
describe("when the status is critical", function() {
it("shows the rubygems notification", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
for (var i=0; i < 4; i++) {
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"critical\"}"
});
}
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('bad');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
describe("when the status is major", function() {
it("shows the rubygems notification", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
for (var i=0; i < 4; i++) {
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"major\"}"
});
}
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('bad');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
describe("when the status is minor", function() {
it("shows the rubygems impaired notification", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
for (var i=0; i < 4; i++) {
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"minor\"}"
});
}
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('impaired');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
describe("when the status is none", function() {
it("does not show the rubygems notification", function() {
RubyGemsRefresh.init();
$(".rubygems").show();
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"none\"}"
});
expect($(".rubygems")).toBeHidden();
});
});
describe("when rubygems is unreachable", function() {
it("shows unreachable", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
for (var i=0; i < 4; i++) {
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"unreachable\"}"
});
}
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('unreachable');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
describe("when rubygems is unparsable", function() {
it("shows page broken notification", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
for (var i=0; i < 4; i++) {
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"page broken\"}"
});
}
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('broken');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
// marking this disabled, as we removed this functionality in
// e0d9cdd3720f5f34a292f5ff719483a7a4968bb0
xdescribe("when our app is unreachable", function() {
it("shows unreachable", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 500,
responseText: "{}"
});
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('unreachable');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
describe("when page is broken/raises parsing error", function() {
it("shows page broken error", function() {
spyOn(RubyGemsRefresh, "clearStatuses");
RubyGemsRefresh.init();
expect($(".rubygems")).toBeHidden();
jasmine.clock().tick(30001);
jasmine.Ajax.requests.mostRecent().response({
status: 200,
responseText: "{\"status\": \"page broken\"}"
});
expect($(".rubygems")).toBeVisible();
expect($(".rubygems")).toHaveClass('broken');
expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();
});
});
});
| JavaScript | 0 | @@ -3929,661 +3929,8 @@
);%0A%0A
- // marking this disabled, as we removed this functionality in%0A // e0d9cdd3720f5f34a292f5ff719483a7a4968bb0%0A xdescribe(%22when our app is unreachable%22, function() %7B%0A it(%22shows unreachable%22, function() %7B%0A spyOn(RubyGemsRefresh, %22clearStatuses%22);%0A RubyGemsRefresh.init();%0A expect($(%22.rubygems%22)).toBeHidden();%0A%0A jasmine.clock().tick(30001);%0A jasmine.Ajax.requests.mostRecent().response(%7B%0A status: 500,%0A responseText: %22%7B%7D%22%0A %7D);%0A expect($(%22.rubygems%22)).toBeVisible();%0A expect($(%22.rubygems%22)).toHaveClass('unreachable');%0A expect(RubyGemsRefresh.clearStatuses).toHaveBeenCalled();%0A %7D);%0A %7D);%0A%0A
de
|
91ac5fed5244ec328d1a47e95f244b839f9a74ae | extract logic into separate method | spec/js/test-color-splash-playground.js | spec/js/test-color-splash-playground.js | describe('CSPlayground', function() {
var $playgroundElement;
var playground;
beforeEach(function() {
$playgroundElement = $(document.createElement('table'));
});
describe('.initialize(4)', function() {
// given
var colors = [ 'red', 'blue', 'green' ];
var size = 4;
beforeEach(function() {
playground = new CSPlayground($playgroundElement, colors);
// when
playground.initialize(size);
});
it('should create ' + (size * size) + ' cells', function() {
// then
var expectedCells = (size * size);
var cells = $('td', $playgroundElement);
expect(cells.length).toEqual(expectedCells);
});
it('should add a color to each cell', function() {
// then
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var color = cell.attr('data-color');
expect(color).not.toBe(null);
});
});
it('should add the color of start-cell (0,3) to no other cell', function() {
var startCellColor = null;
var cells = $('td', $playgroundElement);
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == '0' && yIndex == '3') {
startCellColor = cell.attr('data-color');
return false; // break the loop
}
});
expect(startCellColor).not.toBe(null);
// then
$.each(cells, function(index, element) {
var cell = $(element);
var xIndex = cell.attr('data-index-x');
var yIndex = cell.attr('data-index-y');
if (xIndex == '0' && yIndex == '3') {
return true; // continue;
}
var color = cell.attr('data-color');
expect(color).not.toBe(startCellColor);
});
});
it('cells (0,2) and (1,3) should have different color', function() {
fail('not yet implemented');
});
});
}); | JavaScript | 0.999899 | @@ -997,274 +997,63 @@
Cell
-Color = null;%0A%0A%09%09%09var cells = $('td', $playgroundElement);%0A%09%09%09$.each(cells, function(index, element) %7B%0A%09%09%09%09var cell = $(element);%0A%09%09%09%09var xIndex = cell.attr('data-index-x'
+ = getCellByPosition($playgroundElement, 0, 3
);%0A
-%09
%09%09%09var
-yIndex = cell.attr('data-index-y');%0A%0A%09%09%09%09if (xIndex == '0' && yIndex == '3') %7B%0A%09%09%09%09%09
star
@@ -1061,25 +1061,30 @@
CellColor =
-c
+startC
ell.attr('da
@@ -1098,58 +1098,8 @@
r');
-%0A%09%09%09%09%09return false; // break the loop%0A%09%09%09%09%7D%0A%09%09%09%7D);
%0A%0A%09%09
@@ -1150,16 +1150,60 @@
// then%0A
+%09%09%09var cells = $('td', $playgroundElement);%0A
%09%09%09$.eac
@@ -1649,11 +1649,417 @@
;%0A%09%7D);%0A%0A
-
%7D);
+%0A%0Afunction getCellByPosition($playgroundElement, x, y) %7B%0A%09var expectedCell = null;%0A%0A%09var cells = $('td', $playgroundElement);%0A%09$.each(cells, function(index, element) %7B%0A%09%09var cell = $(element);%0A%09%09var xIndex = cell.attr('data-index-x');%0A%09%09var yIndex = cell.attr('data-index-y');%0A%0A%09%09if (xIndex == x && yIndex == y) %7B%0A%09%09%09expectedCell = cell;%0A%09%09%09return false; // break the loop%0A%09%09%7D%0A%09%7D);%0A%0A%09return expectedCell;%0A%7D
|
e15be8c0811a8a80808df6b3a053a748e4ed284b | add desc | Algorithms/JS/linkedList/addTwoNumbers.js | Algorithms/JS/linkedList/addTwoNumbers.js | addTwoNumbers.js
| JavaScript | 0.000001 | @@ -1,17 +1,282 @@
-addTwoNumbers.js
+// You are given two linked lists representing two non-negative numbers.%0A// The digits are stored in reverse order and each of their nodes contain a single digit.%0A// Add the two numbers and return it as a linked list.%0A%0A// Input: (2 -%3E 4 -%3E 3) + (5 -%3E 6 -%3E 4)%0A// Output: 7 -%3E 0 -%3E 8
%0A
|
e7d933646c63735fb7871023c18af3facc8a2ce9 | add desc | Algorithms/JS/strings/longestSubstring.js | Algorithms/JS/strings/longestSubstring.js | longestSubstring.js
| JavaScript | 0.000001 | @@ -1,20 +1,63 @@
+// Given a string, find the length of the
longest
-S
+ s
ubstring
.js%0A
@@ -56,8 +56,328 @@
ring
-.js
+ without repeating characters.%0A%0A// Examples:%0A%0A// Given %22abcabcbb%22, the answer is %22abc%22, which the length is 3.%0A%0A// Given %22bbbbb%22, the answer is %22b%22, with the length of 1.%0A%0A// Given %22pwwkew%22, the answer is %22wke%22, with the length of 3.%0A// Note that the answer must be a substring, %22pwke%22 is a subsequence and not a substring.
%0A
|
55b7cd5be3e7485eb2d01d7b8f7e1cffe8587b42 | Remove dead code | core/actions/slackPreviewRelease.js | core/actions/slackPreviewRelease.js | 'use strict';
const { waterfall, mapSeries } = require('async');
const previewReleaseTemplate = require('./slack-views/slack-preview-release');
module.exports = function createPreviewRelease(getReleasePreview, slack, repos) {
return (cb) => {
const reposBranches = repos.map(repo => ({ repo }));
waterfall([
(next) => getReleasePreview(reposBranches, next),
(reposInfo, next) => notifyPreviewInSlack(reposInfo, next)
], cb);
};
function getPRsFromChangesForEachRepo(repos, cb) {
mapSeries(repos, (repo, nextRepo) => {
pullRequestsFromChanges({ repo }, (err, prIds) => {
if (err) return nextRepo(null, { repo, failReason: err.message });
nextRepo(null, { repo, prIds });
});
}, cb);
}
function getDeployInfoForEachRepo(reposInfo, cb) {
mapSeries(reposInfo, (repoInfo, nextRepo) => {
if (repoInfo.prIds.length === 0) {
return nextRepo(null, Object.assign({ failReason: 'NO_CHANGES' }, repoInfo));
}
deployInfoFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, deployInfo) => {
let failReason;
if (err) {
failReason = err.message;
}
else if (deployInfo.deployNotes) {
failReason = 'DEPLOY_NOTES';
}
else if (deployInfo.services.length === 0) {
failReason = 'NO_SERVICES';
}
nextRepo(null, Object.assign({ failReason, services: deployInfo.services }, repoInfo));
});
}, cb);
}
function getIssuesToReleaseForEachRepo(reposInfo, cb) {
mapSeries(reposInfo, (repoInfo, nextRepo) => {
issuesFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, issues) => {
if (err) return nextRepo(null, Object.assign({ failReason: err.message }, repoInfo));
nextRepo(null, Object.assign({ issues }, repoInfo));
});
}, cb);
}
function notifyPreviewInSlack(reposInfo, cb) {
const msg = previewReleaseTemplate(reposInfo);
slack.send(msg, cb);
}
};
| JavaScript | 0.001497 | @@ -468,1406 +468,8 @@
%7D;%0A%0A
- function getPRsFromChangesForEachRepo(repos, cb) %7B%0A mapSeries(repos, (repo, nextRepo) =%3E %7B%0A pullRequestsFromChanges(%7B repo %7D, (err, prIds) =%3E %7B%0A if (err) return nextRepo(null, %7B repo, failReason: err.message %7D);%0A nextRepo(null, %7B repo, prIds %7D);%0A %7D);%0A %7D, cb);%0A %7D%0A%0A function getDeployInfoForEachRepo(reposInfo, cb) %7B%0A mapSeries(reposInfo, (repoInfo, nextRepo) =%3E %7B%0A if (repoInfo.prIds.length === 0) %7B%0A return nextRepo(null, Object.assign(%7B failReason: 'NO_CHANGES' %7D, repoInfo));%0A %7D%0A deployInfoFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, deployInfo) =%3E %7B%0A let failReason;%0A if (err) %7B%0A failReason = err.message;%0A %7D%0A else if (deployInfo.deployNotes) %7B%0A failReason = 'DEPLOY_NOTES';%0A %7D%0A else if (deployInfo.services.length === 0) %7B%0A failReason = 'NO_SERVICES';%0A %7D%0A nextRepo(null, Object.assign(%7B failReason, services: deployInfo.services %7D, repoInfo));%0A %7D);%0A %7D, cb);%0A %7D%0A%0A function getIssuesToReleaseForEachRepo(reposInfo, cb) %7B%0A mapSeries(reposInfo, (repoInfo, nextRepo) =%3E %7B%0A issuesFromPullRequests(repoInfo.repo, repoInfo.prIds, (err, issues) =%3E %7B%0A if (err) return nextRepo(null, Object.assign(%7B failReason: err.message %7D, repoInfo));%0A nextRepo(null, Object.assign(%7B issues %7D, repoInfo));%0A %7D);%0A %7D, cb);%0A %7D%0A%0A
fu
|
90d1711ca365c040e249c9297ede437492d4495b | fix some supid typos | src/rules/no-unsupported-elements-use-aria.js | src/rules/no-unsupported-elements-use-aria.js | import {
DOM
, aria
} from '../util'
export default [{
msg: 'This element does not support ARIA roles, states and properties.'
, AX: 'AX_ARIA_12'
, test (tagName, props) {
const reserved = DOM[tagName].reserved || false
const hasProp = hasProp(props, Object.keys(aria).concat('role'))
return !reserved || !hasProp
}
}]
export const description = `
Certain reserved DOM elements do not support ARIA roles, states and properties.
This is often because they are not visible, for example \`meta\`, \`html\`, \`script\`,
\`style\`. This rule enforces that these DOM elements do not contain the \`role\` and/or
\`aria-*\` props.
`
const fail = [{
when: 'the element should not be given any ARIA attributes'
, render: React => <meta charset="UTF-8" aria-hidden="false" />
}]
const pass = [{
when: 'the reserver element is not given an illegal prop'
, render: React => <meta charset="UTF-8" />
}, {
when: 'an illegal props is given to a non-reserved elemeent'
, render: React => <div aria-hidden={true} />
}]
| JavaScript | 0.999999 | @@ -15,16 +15,26 @@
%0A, aria%0A
+, hasProp%0A
%7D from '
@@ -243,23 +243,23 @@
const
-hasProp
+prop
= hasP
@@ -329,20 +329,17 @@
ved %7C%7C !
-hasP
+p
rop%0A %7D%0A
@@ -649,16 +649,23 @@
ops.%0A%60%0A%0A
+export
const fa
@@ -802,16 +802,23 @@
/%3E%0A%7D%5D%0A%0A
+export
const pa
|
1b83980e263668f31347d2f658161069bf9989d8 | update function to es6/7 | Challenges/DashInsert.js | Challenges/DashInsert.js | const assert = require('assert');
function DashInsert(str) {
const arr = str.split('');
for (let i = 0; i < str.length - 1; i += 1) {
if (arr[i] % 2 !== 0 && arr[i + 1] % 2 !== 0) {
arr[i] = `${arr[i]}-`;
}
}
// console.log('123');
console.log(str);
return arr.join('');
}
const in1 = '1234567'; // input
const expect1 = '1234567'; // output
const test1 = DashInsert(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log('works');
| JavaScript | 0 | @@ -32,16 +32,13 @@
);%0A%0A
-function
+const
Das
@@ -44,21 +44,25 @@
shInsert
-(str)
+ = str =%3E
%7B%0A con
@@ -295,16 +295,17 @@
n('');%0A%7D
+;
%0A%0Aconst
|
43ca8a0da41bd804329c056d6c5ac7cea931d5e4 | Add TransformExample to UIExplorerList.ios.js | Examples/UIExplorer/UIExplorerList.ios.js | Examples/UIExplorer/UIExplorerList.ios.js | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
Settings,
SnapshotViewIOS,
StyleSheet,
} = React;
import type { NavigationContext } from 'NavigationContext';
var UIExplorerListBase = require('./UIExplorerListBase');
var COMPONENTS = [
require('./ActivityIndicatorIOSExample'),
require('./DatePickerIOSExample'),
require('./ImageExample'),
require('./LayoutEventsExample'),
require('./ListViewExample'),
require('./ListViewGridLayoutExample'),
require('./ListViewPagingExample'),
require('./MapViewExample'),
require('./ModalExample'),
require('./Navigator/NavigatorExample'),
require('./NavigatorIOSColorsExample'),
require('./NavigatorIOSExample'),
require('./PickerIOSExample'),
require('./ProgressViewIOSExample'),
require('./ScrollViewExample'),
require('./SegmentedControlIOSExample'),
require('./SliderIOSExample'),
require('./SwitchIOSExample'),
require('./TabBarIOSExample'),
require('./TextExample.ios'),
require('./TextInputExample.ios'),
require('./TouchableExample'),
require('./TransparentHitTestExample'),
require('./ViewExample'),
require('./WebViewExample'),
];
var APIS = [
require('./AccessibilityIOSExample'),
require('./ActionSheetIOSExample'),
require('./AdSupportIOSExample'),
require('./AlertIOSExample'),
require('./AnimatedExample'),
require('./AnimatedGratuitousApp/AnExApp'),
require('./AppStateIOSExample'),
require('./AsyncStorageExample'),
require('./BorderExample'),
require('./CameraRollExample.ios'),
require('./ClipboardExample'),
require('./GeolocationExample'),
require('./LayoutExample'),
require('./NetInfoExample'),
require('./PanResponderExample'),
require('./PointerEventsExample'),
require('./PushNotificationIOSExample'),
require('./RCTRootViewIOSExample'),
require('./StatusBarIOSExample'),
require('./TimerExample'),
require('./VibrationIOSExample'),
require('./XHRExample.ios'),
require('./ImageEditingExample'),
];
type Props = {
navigator: {
navigationContext: NavigationContext,
push: (route: {title: string, component: ReactClass<any,any,any>}) => void,
},
onExternalExampleRequested: Function,
};
class UIExplorerList extends React.Component {
props: Props;
render() {
return (
<UIExplorerListBase
components={COMPONENTS}
apis={APIS}
searchText={Settings.get('searchText')}
renderAdditionalView={this.renderAdditionalView.bind(this)}
search={this.search.bind(this)}
onPressRow={this.onPressRow.bind(this)}
/>
);
}
renderAdditionalView(renderRow: Function, renderTextInput: Function): React.Component {
return renderTextInput(styles.searchTextInput);
}
search(text: mixed) {
Settings.set({searchText: text});
}
_openExample(example: any) {
if (example.external) {
this.props.onExternalExampleRequested(example);
return;
}
var Component = UIExplorerListBase.makeRenderable(example);
this.props.navigator.push({
title: Component.title,
component: Component,
});
}
onPressRow(example: any) {
this._openExample(example);
}
// Register suitable examples for snapshot tests
static registerComponents() {
COMPONENTS.concat(APIS).forEach((Example) => {
if (Example.displayName) {
var Snapshotter = React.createClass({
render: function() {
var Renderable = UIExplorerListBase.makeRenderable(Example);
return (
<SnapshotViewIOS>
<Renderable />
</SnapshotViewIOS>
);
},
});
AppRegistry.registerComponent(Example.displayName, () => Snapshotter);
}
});
}
}
var styles = StyleSheet.create({
searchTextInput: {
height: 30,
},
});
module.exports = UIExplorerList;
| JavaScript | 0.000006 | @@ -2510,32 +2510,65 @@
TimerExample'),%0A
+ require('./TransformExample'),%0A
require('./Vib
|
80da99bcd53d3f94eca7c5b96a152c8348a76d11 | Set constant height for free-form textbox | src/modules/WriteViewContainer.js | src/modules/WriteViewContainer.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Map } from 'immutable';
import { NavigationActions } from 'react-navigation';
import {
Image,
TextInput,
Alert,
View,
ScrollView,
StyleSheet,
} from 'react-native';
import LoadingSpinner from '../components/LoadingSpinner';
import { addFreeWord } from '../state/UserState';
import { getImage, getSizeByWidth } from '../services/graphics';
import DoneButton from '../components/DoneButton';
import SaveConfirmationWindow from '../components/SaveConfirmationWindow';
const styles = StyleSheet.create({
container: {
flex: 1,
width: null,
height: null,
},
scrollContainer: {},
textBoxContainer: {
paddingVertical: 32,
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
doneButton: {
alignSelf: 'center',
},
});
const mapStateToProps = state => ({
answers: state.getIn(['user', 'currentUser', 'answers']),
freeWordKey: state.getIn(['navigatorState', 'routes', 2, 'key']),
});
const mapDispatchToProps = dispatch => ({
back: key => dispatch(NavigationActions.back({ key })),
pushRoute: key => dispatch(NavigationActions.navigate({ routeName: key })),
popRoute: () => dispatch(NavigationActions.back()),
saveFreeWord: freeWord => dispatch(addFreeWord(freeWord)),
});
@connect(mapStateToProps, mapDispatchToProps)
export default class WriteViewContainer extends Component {
static navigationOptions = {
title: 'Kirjoita',
};
static propTypes = {
back: PropTypes.func.isRequired,
freeWordKey: PropTypes.string,
popRoute: PropTypes.func.isRequired,
pushRoute: PropTypes.func.isRequired,
saveFreeWord: PropTypes.func.isRequired,
answers: PropTypes.instanceOf(Map).isRequired,
};
state = {
text: '',
showSucceedingMessage: false,
showSpinner: false,
};
error = () => {
this.setState({ showSpinner: false });
Alert.alert(
'Ohops!',
'Jokin meni pieleen! Tarkista nettiyhteys tai yritä myöhemmin uudelleen!',
[{ text: 'Ok' }],
);
};
renderTextForm = () =>
<Image
style={{
height: null,
width: getSizeByWidth('textbox', 0.45).width,
flexDirection: 'row',
justifyContent: 'flex-start',
}}
resizeMode="stretch"
source={getImage('textbox').normal}
>
<TextInput
multiline
autoFocus={!this.state.text}
numberOfLines={30}
maxLength={500}
onChangeText={text => this.setState({ text })}
underlineColorAndroid="transparent"
style={{
flex: 1,
textAlignVertical: 'top',
margin: 16,
fontFamily: 'Roboto-Regular',
}}
/>
</Image>;
sendText = async () => {
await this.props.saveFreeWord(Map({ text: this.state.text }));
this.setState({ showSucceedingMessage: true });
};
renderDoneButton = () =>
<DoneButton
onPress={this.sendText.bind(this)}
disabled={this.state.text.length === 0}
/>;
hideSucceedingMessage = () => {
if (this.state.showSucceedingMessage) {
this.setState({ showSucceedingMessage: false });
this.props.back(this.props.freeWordKey);
}
};
renderSaveConfirmationWindow = () =>
<SaveConfirmationWindow
closeWindow={this.hideSucceedingMessage}
visible={this.state.showSucceedingMessage}
/>;
render() {
if (this.state.showSpinner) {
return <LoadingSpinner />;
}
return (
<Image source={getImage('forest').normal} style={styles.container}>
<ScrollView
keyboardShouldPersistTaps={'always'}
overScrollMode={'always'}
contentContainerStyle={styles.scrollContainer}
>
<View style={styles.textBoxContainer}>
{this.renderTextForm()}
</View>
</ScrollView>
<View style={styles.doneButton}>
{this.renderDoneButton()}
</View>
{this.renderSaveConfirmationWindow()}
</Image>
);
}
}
| JavaScript | 0 | @@ -770,29 +770,16 @@
al: 32,%0A
- flex: 1,%0A
flex
@@ -2189,28 +2189,27 @@
height:
-null
+250
,%0A wi
|
9a9957df4ec7a5dca7d2bfa21c9e2013db99d691 | make sure parseError is receiving an Error | src/modules/support/parseError.js | src/modules/support/parseError.js | function parseStack(e) {
var concatStack = e.stack.replace(/\n +/g, '|');
if (e.stack.includes(e.message)) {
return concatStack;
}
return e.message + '|' + concatStack;
}
export default function parseError(e) {
if (e.stack) {return parseStack(e);}
if (e.message) {return e.message;}
return String(e);
}
| JavaScript | 0.000067 | @@ -181,23 +181,8 @@
%0A%7D%0A%0A
-export default
func
@@ -186,21 +186,18 @@
unction
-parse
+is
Error(e)
@@ -293,12 +293,122 @@
tring(e);%0A%7D%0A
+%0Aexport default function parseError(e) %7B%0A if (e instanceof Error) %7Breturn isError(e);%7D%0A return String(e);%0A%7D%0A
|
d28f7b13bdc449a8b2ab39e8aa41a5be0c63a692 | Set currentPath in init lifecycle hook. | addon/components/search-help-modal/component.js | addon/components/search-help-modal/component.js | import Ember from 'ember';
import layout from './template';
/**
* Modal that provides examples and explanation of Lucene Search syntax
*
* ```handlebars
* {{search-help-modal
* isOpen=isOpen
* }}
* ```
* @class search-help-modal
*/
export default Ember.Component.extend({
layout,
isOpen: false,
currentPath: Ember.computed(function() {
return window.location.origin + window.location.pathname;
}),
actions: {
close() {
this.set('isOpen', false);
},
toggleHelpModal() {
this.toggleProperty('isOpen');
},
}
});
| JavaScript | 0 | @@ -319,64 +319,87 @@
-currentPath: Ember.computed(function() %7B%0A return
+init() %7B%0A this._super(...arguments);%0A this.set('currentPath', %60$%7B
wind
@@ -420,11 +420,11 @@
igin
- +
+%7D$%7B
wind
@@ -447,16 +447,18 @@
name
+%7D%60)
;%0A %7D
-)
,%0A
|
dd6e67fa527d013d88d9b8fbc29c7b5d023fae7d | fix done callback invocations | test/helpers.js | test/helpers.js | "use strict";
const expect = require("expect.js");
exports.successResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
expect(res.headers["content-type"]).to.be("text/javascript; charset=utf-8");
expect(res.headers["cache-control"]).to.be("no-cache");
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.not.be.empty();
});
res.on("close", cb);
res.on("end", () => {
if (close) close(cb);
else cb();
});
};
};
exports.failureResponseCallback = function (cb, close) {
return function (res) {
res.setEncoding("utf8");
expect(res.statusCode).to.be(200);
res.on("data", chunk => {
expect(chunk).to.be.a("string");
expect(chunk).to.contain("Cannot require");
});
res.on("close", cb);
res.on("end", () => {
if (close) close(cb);
else cb();
});
};
};
| JavaScript | 0.000003 | @@ -437,39 +437,16 @@
%0A%09%09%7D);%0A%0A
-%09%09res.on(%22close%22, cb);%0A
%09%09res.on
@@ -477,37 +477,30 @@
lose) close(
-cb
);%0A%09%09%09
-else
cb();%0A%09%09%7D);%0A
@@ -776,31 +776,8 @@
);%0A%0A
-%09%09res.on(%22close%22, cb);%0A
%09%09re
@@ -820,21 +820,14 @@
ose(
-cb
);%0A%09%09%09
-else
cb()
|
9c666da48463b6b7745ad8882d85a40921976d7c | fix practice server crash | practiceserver.js | practiceserver.js | var port = 1340;
// Downgrade from root
if (process.getuid() === 0)
require('fs').stat(__filename, function(err, stats) {
if (err)
return console.log(err);
process.setuid(stats.uid);
});
console.log("Started practice server");
var io = require('socket.io').listen(port);
var games = {},
gameBySocketId = {},
gamesPerProcess = 32;
io.sockets.on('connection',function(socket){
socket.on('subscribe',function(type,gameId){
var g = games[gameId];
if(typeof g == 'undefined'){
if(gamesPerProcess > 0){
games[gameId] = new PGame(gameId,socket);
gamesPerProcess--;
}else{
socket.emit('error','No more practice rooms available');
return;
}
}else{
if(type == 'controller'){
if(g.c0 === null){
g.connect(0,socket);
}else if(g.c1 === null){
g.connect(1,socket);
}else{
socket.emit('error','This room already has two controllers');
}
}else{
socket.emit('error','This id is taken');
}
}
});
socket.on('disconnect',function(){
var g = gameBySocketId[socket.id];
if(g.host.id == socket.id){
g.c0.emit('disconnect');
g.c1.emit('disconnect');
delete gameBySocketId[g.c0.id];
delete gameBySocketId[g.c1.id];
delete gameBySocketId[g.host.id];
delete games[g.gid];
}else if(g.c0.id == socket.id){
g.c0 = null;
}else if(g.c1.id == socket.id){
g.c1 = null;
}
});
});
PGame = function(id,host){
this.host = host;
this.gid = id;
this.c0 = null;
this.c1 = null;
gameBySocketId[host.id] = this;
};
PGame.prototype.connect = function(id,socket){
if(id == 0){
this.c0 = socket;
}
if(id == 1){
this.c1 = socket;
}
(function(pgame){
socket.on('paddle',function(point){
pgame.host.emit('paddle',id,point);
});
socket.on('dbl',function(){
pgame.host.emit('dlb',id);
});
})(this);
socket.emit('connected',id);
gameBySocketId[socket.id] = this;
};
| JavaScript | 0 | @@ -1163,43 +1163,25 @@
+if(
g.c0
-.emit('disconnect');%0A%09%09 g.c1
+)%7B%0A%09%09%09g.c0
.emi
@@ -1195,28 +1195,25 @@
onnect');%0A%09%09
-
+%09
delete gameB
@@ -1230,32 +1230,81 @@
g.c0.id%5D;%0A%09%09
+%7D%0A%09%09 if(g.c1)%7B%0A%09%09%09g.c1.emit('disconnect');%0A%09%09%09
delete gameBySoc
@@ -1315,24 +1315,32 @@
d%5Bg.c1.id%5D;%0A
+%09%09 %7D%0A
%09%09 delete
|
5451e403cd6b7cce3351746531fdc945b418ee45 | Update tests! | test/helpers.js | test/helpers.js | var expect = require("expect.js");
var mocha = require("mocha");
var assets = require("..");
describe("helper functions", function () {
it("do not pollute global scope if helperContext is passed", function () {
var ctx = {};
var instance = assets({ helperContext: ctx });
expect(ctx.css).to.be.a("function");
expect(ctx.js).to.be.a("function");
expect(ctx.assetPath).to.be.a("function");
expect(global.css).to.equal(undefined);
expect(global.js).to.equal(undefined);
expect(global.assetPath).to.equal(undefined);
});
it("throw an Error if asset is not found", function () {
var ctx = {};
var instance = assets({ helperContext: ctx });
expect(function () {
ctx.assetPath("non-existant-asset.js");
}).to.throwError(/'non-existant-asset.js' not found/i);
});
it("returns many paths if options.build is false", function () {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/css", build: false });
var files = ctx.assetPath("depends-on-blank.css");
expect(files).to.equal(
'/assets/blank-20069ab163c070349198aa05124dcaa8.css\n' +
'/assets/depends-on-blank-976b290d2657588f29e6f3c5a26611ee.css'
);
});
it("returns a single path if options.build is true", function () {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/css", build: true });
var files = ctx.assetPath("depends-on-blank.css");
expect(files).to.equal('/assets/depends-on-blank-9df23d3309e74402b1d69a0a08dcd9ee.css');
});
describe("css", function () {
it("returns a <link> tag for each asset found (separated by \\n)", function () {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/css" });
var link = ctx.css("depends-on-blank.css");
expect(link).to.equal(
'<link rel="stylesheet" href="/assets/blank-20069ab163c070349198aa05124dcaa8.css" />\n' +
'<link rel="stylesheet" href="/assets/depends-on-blank-976b290d2657588f29e6f3c5a26611ee.css" />'
);
});
it("should serve correct asset even if extention is not supplied", function() {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/css" });
var link = ctx.css("asset");
expect(link).to.equal(
'<link rel="stylesheet" href="/assets/asset-20069ab163c070349198aa05124dcaa8.css" />'
);
});
it("should have additional attributes in result tag", function() {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/css" });
var link = ctx.css("asset", { data: { 'turbolinks-track': true } });
expect(link).to.equal(
'<link rel="stylesheet" href="/assets/asset-20069ab163c070349198aa05124dcaa8.css" data-turbolinks-track />'
);
});
});
describe("js", function () {
it("returns a <script> tag for each asset found (separated by \\n)", function () {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/js" });
var script = ctx.js("depends-on-blank.js");
expect(script).to.equal(
'<script src="/assets/blank-3d2afa4aef421f17310e48c12eb39145.js"></script>\n' +
'<script src="/assets/depends-on-blank-3d2afa4aef421f17310e48c12eb39145.js"></script>'
);
});
it("should serve correct asset even if extention is not supplied", function() {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/js" });
var script = ctx.js("asset.js");
expect(script).to.equal(
'<script src="/assets/asset-3d2afa4aef421f17310e48c12eb39145.js"></script>'
);
});
it("should have additional attributes in result tag", function() {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/js" });
var script = ctx.js("asset.js", { async: true });
expect(script).to.equal(
'<script src="/assets/asset-3d2afa4aef421f17310e48c12eb39145.js" async></script>'
);
});
});
describe("assetPath", function () {
it("returns a file path for each asset found (separated by \\n)", function () {
var ctx = {};
var instance = assets({ helperContext: ctx, paths: "test/assets/js" });
var path = ctx.assetPath("depends-on-blank.js");
expect(path).to.equal(
'/assets/blank-3d2afa4aef421f17310e48c12eb39145.js\n' +
'/assets/depends-on-blank-3d2afa4aef421f17310e48c12eb39145.js'
);
});
it("is accessible from javascript assets");
it("is accessible from coffeescript assets");
it("is accessible from stylus assets");
it("is accessible from less assets");
it("is accessible from sass assets");
it("is accessible from haml coffeescript assets");
it("is accessible from ejs assets");
});
describe("asset", function () {
it("returns the contents of the asset");
it("is accessible from javascript assets");
it("is accessible from coffeescript assets");
it("is accessible from stylus assets");
it("is accessible from less assets");
it("is accessible from sass assets");
it("is accessible from haml coffeescript assets");
it("is accessible from ejs assets");
});
});
| JavaScript | 0 | @@ -2643,17 +2643,14 @@
, %7B
+'
data
-: %7B '
+-
turb
@@ -2668,18 +2668,16 @@
k': true
- %7D
%7D);%0A
|
0909ff1f46f7020731bc87167e289676be065d66 | Make print links open in new windows | app/assets/javascripts/core.js | app/assets/javascripts/core.js | //Reusable functions
var Alphagov = {
daysInMsec: function(d) {
return d * 24 * 60 * 60 * 1000;
},
cookie_domain: function() {
var host_parts = document.location.host.split(':')[0].split('.').slice(-3);
return '.' + host_parts.join('.');
},
read_cookie: function(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
delete_cookie: function(name) {
if (document.cookie && document.cookie !== '') {
var date = new Date();
date.setTime(date.getTime() - Alphagov.daysInMsec(1)); // 1 day ago
document.cookie = name + "=; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
},
write_cookie: function(name, value) {
var date = new Date();
date.setTime(date.getTime() + Alphagov.daysInMsec(4 * 30)); // 4 nominal 30-day months in the future
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + date.toGMTString() + "; domain=" + Alphagov.cookie_domain() + "; path=/";
}
};
function recordOutboundLink(e) {
_gat._getTrackerByName()._trackEvent(this.href, 'Outbound Links');
setTimeout('document.location = "' + this.href + '"', 100);
return false;
}
$(document).ready(function() {
$("body").addClass("js-enabled");
if(window.location.hash) {
contentNudge(window.location.hash);
}
$("nav").delegate('a', 'click', function(){
var hash;
var href = $(this).attr('href');
if(href.charAt(0) === '#'){
hash = href;
}
else if(href.indexOf("#") > 0){
hash = "#" + href.split("#")[1];
}
if($(hash).length == 1){
$("html, body").animate({scrollTop: $(hash).offset().top - $("#global-header").height()},10);
}
});
function contentNudge(hash){
if($(hash).length == 1){
if($(hash).css("top") == "auto" || "0"){
$(window).scrollTop( $(hash).offset().top - $("#global-header").height() );
}
}
}
// related box fixer
if($(".related-positioning").length !== 0){
$(".related-positioning").css("position", "absolute");
var viewPort = $(window).height();
var relatedBox = $(".related").height();
var boxOffset = $(".related-positioning").position();
var topBoxOffset = boxOffset.top;
if(relatedBox > (viewPort - topBoxOffset)){
$(".related-positioning").css("position", "absolute");
}
else{
$(".related-positioning").css("position", "fixed");
}
}
/*var relatedBoxTop = $(".related-positioning").css("top");
$(window).bind("scroll", function(){
if(isScrolledIntoView($(".beta-notice"))){
var docHeight = $(document).height();
var portHeight = $(window).height();
var distanceDownPage = $(window).scrollTop();
var footerHeight = $("footer").height();
var relatedHeight = $(".related").height();
var relatedBottomStopper = footerHeight + relatedHeight;
console.log("distance down page: "+distanceDownPage)
console.log("relatedBottomStopper: "+relatedBottomStopper)
if ( distanceDownPage <= (relatedBottomStopper + footerHeight) ){
$(".related-positioning").css("top", "auto");
$(".related-positioning").css("bottom", relatedBottomStopper);
}
}
else{
$(".related-positioning").css("top", relatedBoxTop);
$(".related-positioning").css("bottom", "auto");
}
})
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
*/
});
| JavaScript | 0 | @@ -1631,16 +1631,63 @@
bled%22);%0A
+ $('.print-link a').attr('target', '_blank');%0A
%0A if(
|
9780236c224dea63d8dc90bd9b34666e10f63d52 | fix assets precompile problem | app/assets/javascripts/grid.js | app/assets/javascripts/grid.js | var jobsworth = jobsworth || {}
jobsworth.Grid = (function($){
var columns = [
{id: 'read', name: "<span class='unread_icon'/>", field: 'read', resizable: false, sortable: true, formatter: UnreadMarkFormatter, width:16},
{id: 'id', name: 'id', field: 'id', sortable: true},
{id: 'summary', name: 'summary', field: 'summary'},
{id: 'client', name: 'client', field: 'client', sortable: true},
{id: 'milestone', name: 'milestone', field: 'milestone', sortable: true},
{id: 'due', name: 'target date', field: 'due', sortable: true, formatter: HtmlFormatter},
{id: 'time', name: 'time', field: 'time', sortable: true, formatter: DurationFormatter},
{id: 'assigned', name: 'assigned', field: 'assigned', sortable: true},
{id: 'resolution', name: 'resolution', field: 'resolution', sortable: true},
{id: 'updated_at', name: 'last comment date', field: 'updated_at', sortable: true, formatter: TimeFormatter},
];
function Grid(options) {
this.options = options;
this.init();
}
/* formatters for SlickGrid */
function UnreadMarkFormatter(row, cell, value, columnDef, dataContext) {
return value == "f" ? "<span class='unread_icon'/>" : "";
}
// fix slickgrid displaying html in cell
function HtmlFormatter(row, cell, value, columnDef, dataContext) {
return value;
}
function DurationFormatter(row, cell, value, columnDef, dataContext) {
if (value == 0) {
return "";
} else {
return Math.round(value/6)/10 + "hr";
}
}
function HtmlFormatter(row, cell, value, columnDef, dataContext) {
return value;
}
function TimeFormatter(row, cell, value, columnDef, dataContext) {
return $.timeago(value);
}
/* end of formatters */
Grid.prototype.init = function() {
var self = this;
$.getJSON("/companies/properties", function(data) {
for(var index in data) {
var property = data[index]["property"]
columns.push({
id: property.name.toLowerCase(),
name: property.name.toLowerCase(),
field: property.name.toLowerCase(),
sortable: true,
formatter: HtmlFormatter
});
}
$.getJSON("/tasks?format=json", function(rows) {
self.createGrid(rows);
})
})
}
Grid.prototype.reload = function() {
var self = this;
showProgress();
$.getJSON("/tasks?format=json", function(rows) {
self.dataView.setItems(rows);
self.grid.invalidate();
self.grid.render();
hideProgress();
})
}
Grid.prototype.bind = function() {
var self = this;
$("#groupBy").insertBefore(".slick-pager-settings");
$("#groupBy select").change(function() {
var value = $(this).val();
store.set("grid.groupBy", value)
for(var index in columns) {
if(columns[index].id == value) {
self.groupBy(columns[index]);
return;
}
}
self.groupBy(null);
})
this.grid.onClick.subscribe(function (e) {
var cell = self.grid.getCellFromEvent(e);
var task = self.grid.getDataItem(cell.row);
// mark task as read
if (task.read == "f") {
task.read = "t";
self.dataView.updateItem(task.id, task);
}
new jobsworth.Task(task.id);
});
this.grid.onSort.subscribe(function(e, args) {
self.onSort(e, args);
});
this.dataView.onRowCountChanged.subscribe(function (e, args) {
self.grid.updateRowCount();
self.grid.render();
});
this.dataView.onRowsChanged.subscribe(function (e, args) {
self.grid.invalidateRows(args.rows);
self.grid.render();
});
this.grid.onColumnsReordered.subscribe(function (e, args) {
store.set('grid.Columns', self.grid.getColumns());
});
this.grid.onColumnsResized.subscribe(function (e, args) {
store.set('grid.Columns', self.grid.getColumns());
});
$(window).resize(function () {
self.grid.resizeCanvas();
});
}
Grid.prototype.createGrid = function(rows) {
var self = this;
var options = {
enableCellNavigation: true,
enableColumnReorder: true,
multiColumnSort: true,
forceFitColumns:true
};
var groupItemMetadataProvider = new Slick.Data.GroupItemMetadataProvider();
this.dataView = new Slick.Data.DataView({
groupItemMetadataProvider: groupItemMetadataProvider,
inlineFilters: true
});
// highlight unread line
this.dataView.getItemMetadata = (function(original_provider){
return function(row) {
var item = this.getItem(row),
ret = original_provider(row);
if (item){
ret = ret || {}
if (item.read == "f") {
ret.cssClasses = (ret.cssClasses || '') + ' unread';
} else {
ret.cssClasses = (ret.cssClasses || '') + ' read';
}
}
return ret;
}
})(this.dataView.getItemMetadata)
this.grid = new Slick.Grid(this.options.el, this.dataView, columns, options);
this.grid.setSelectionModel(new Slick.RowSelectionModel());
this.grid.registerPlugin(groupItemMetadataProvider);
var pager = new Slick.Controls.Pager(this.dataView, this.grid, $("#pager"));
var columnpicker = new Slick.Controls.ColumnPicker(columns, this.grid, options);
// this line must be called before the lines below
this.bind();
this.dataView.beginUpdate();
this.dataView.setItems(rows);
this.dataView.endUpdate();
this.grid.autosizeColumns();
$(this.options.el).resizable({handles: 's'});
// group rows
if (store.get('grid.groupBy')) {
$("#groupBy select").val(store.get('grid.groupBy'));
}
$("#groupBy select").trigger("change");
// select columns
if (store.get('grid.Columns')) {
var visibleColumns = [];
var cols = store.get('grid.Columns');
for(var i in cols) {
for(var j in columns) {
if (cols[i].name == columns[j].name) {
columns[j].width = cols[i].width;
visibleColumns.push(columns[j]);
}
}
}
this.grid.setColumns(visibleColumns);
}
}
Grid.prototype.groupBy = function(column) {
if (!column) {
this.dataView.groupBy(null);
return;
}
this.dataView.groupBy(
column.field,
function (g) {
return column.name + ": " + g.value + " <span style='color:green'>(" + g.count + " items)</span>";
},
function (a, b) {
return a.value - b.value;
}
);
}
Grid.prototype.onSort = function (e, args) {
var cols = args.sortCols;
this.grid.getData().sort(function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
});
this.grid.invalidate();
this.grid.render();
};
return Grid;
})(jQuery);
| JavaScript | 0.000001 | @@ -937,17 +937,16 @@
rmatter%7D
-,
%0A %5D;%0A%0A
|
1ef8cac00a044ead6075ff3c7d271a881ee0b092 | Add js | app/assets/javascripts/trip.js | app/assets/javascripts/trip.js | $(document).ready(function(){
$('#expense_form').hide();
$('#trip_form').on('click', 'input[type=submit]', function(event){
$('#trip_form').hide();
$('#expense_form').show();
});
$('input#expense_location_id').geocomplete();
$('form').on('click','.add_fields', function(event){
event.preventDefault();
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
});
// $('#add-location').click(function(e){
// e.preventDefault();
// addLegForm();
// })
$('body').on('click','.location',function(e){
$(this).geocomplete();
});
$('#expenses_grid').on('click','#add-expense',function(e){
console.log("clicked");
$('#new_expense').show();
$('#add-expense').hide();
});
$('#expenses_grid').on('submit','#new_expense',function(e){
e.preventDefault();
$.ajax ({
url: $(e.target).attr('action'),
type: 'POST',
data: $(e.target).serialize()
}).done(function(data){
$('#expenses_grid').append(data);
clearInputs();
});
});
});
clearInputs = function(){
$("input[name='expense[usd_cost]'").val("");
$("input[name='expense[location_id]'").val("");
$("input[name='expense[cost]'").val("");
$("input[name='expense[category_id]'").val("");
};
| JavaScript | 0.000022 | @@ -184,24 +184,27 @@
w();%0A %7D);%0A
+ //
$('input#ex
@@ -624,16 +624,19 @@
on(e)%7B%0A
+ //
$(this)
@@ -694,32 +694,33 @@
,'#add-expense',
+
function(e)%7B%0A c
@@ -716,16 +716,38 @@
ion(e)%7B%0A
+ e.preventDefault();%0A
consol
|
c537305921b6c17e71a236243d0f703d6cd9f4da | Fix typo | test/library.js | test/library.js |
var expect = require('expect.js')
, ffi = require('../')
, Library = ffi.Library
describe('Library', function () {
afterEach(gc)
it('should be a function', function () {
expect(Library).to.be.a('function')
})
it('should work with the `new` operator', function () {
var l = new Library()
expect(l).to.be.an('object')
})
it('should accept `null` as a first argument', function () {
var thisFuncs = new Library(null, {
'printf': [ 'void', [ 'string' ] ]
})
var test = thisFuncs.printf instanceof Function
expect(test).to.be(true)
})
it('should accept a lib name as a first argument', function () {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ] ]
})
var test = libm.ceil instanceof Function
expect(test).to.be(true)
expect(libm.ceil(1.1)).to.equal(2)
})
it('should throw when an invalid function name is used', function () {
expect(function () {
new Library(null, {
'doesnotexist__': [ 'void', [] ]
})
}).to.throwException()
})
it('should work with "strcpy" and a 128 length string', function () {
var ZEROS_128 = Array(128 + 1).join('0')
var buf = new ffi.Pointer(256)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_128)
expect(buf.getCString()).to.equal(ZEROS_128)
})
it('should work with "strcpy" and a 2k length string', function () {
var ZEROS_2K = Array(2e3 + 1).join('0')
var buf = new ffi.Pointer(4096)
var strcpy = new Library(null, {
'strcpy': [ 'pointer', [ 'pointer', 'string' ] ]
}).strcpy
strcpy(buf, ZEROS_2K)
expect(buf.getCString()).to.equal(ZEROS_2K)
})
if (process.plaform == 'win32') {
// TODO: Add GetTimeOfDay() with FILETIME struct test
} else {
it('should work with "gettimeofday" and a "timeval" Struct pointer', function () {
var timeval = new ffi.Struct([
['long','tv_sec']
, ['long','tv_usec']
])
var l = new Library(null, {
'gettimeofday': ['int', ['pointer', 'pointer']]
})
var tv = new timeval()
l.gettimeofday(tv.ref(), null)
expect(tv.tv_sec == Math.floor(Date.now() / 1000)).to.be(true)
})
}
describe('async', function () {
it('should call a function asynchronously', function (done) {
var lib = process.platform == 'win32' ? 'msvcrt' : 'libm'
var libm = new Library(lib, {
'ceil': [ 'double', [ 'double' ], { async: true } ]
})
libm.ceil(1.1).on('success', function (res) {
expect(res).to.equal(2)
done()
})
})
})
})
| JavaScript | 0.999999 | @@ -1821,16 +1821,17 @@
cess.pla
+t
form ==
|
bd80c06be4ead6d9185acebe778c24a9fa695f26 | remove commented code | app/components/Editor/state.js | app/components/Editor/state.js | import uniqueId from 'lodash/uniqueId'
import is from 'utils/is'
import assignProps from 'utils/assignProps'
import { observable, computed, action, autorun, extendObservable } from 'mobx'
import CodeMirror from 'codemirror'
import FileStore from 'commons/File/store'
import TabStore from 'components/Tab/store'
import overrideDefaultOptions from './codemirrorDefaultOptions'
import { loadMode } from './components/CodeEditor/addons/mode'
import { findModeByFile, findModeByMIME, findModeByName } from './components/CodeEditor/addons/mode/findMode'
const defaultOptions = { ...CodeMirror.defaults, ...overrideDefaultOptions }
const state = observable({
entities: observable.map({}),
options: observable.shallow(defaultOptions),
})
state.entities.observe((change) => {
if (change.type === 'delete') {
const editor = change.oldValue
if (editor.dispose) editor.dispose()
}
})
class Editor {
constructor (props = {}) {
this.id = props.id || uniqueId('editor_')
state.entities.set(this.id, this)
this.update(props)
this.createCodeMirrorInstance()
}
createCodeMirrorInstance () {
this.cmDOM = document.createElement('div')
Object.assign(this.cmDOM.style, { width: '100%', height: '100%' })
const cm = CodeMirror(this.cmDOM, this.options)
this.cm = cm
cm._editor = this
const setOption = this.cm.setOption.bind(this.cm)
this.cm.setOption = this.setOption = (option, value) => {
this._options.set(option, value)
}
this.dispose = autorun(() => {
const options = Object.entries(this.options)
options.forEach(([option, value]) => {
if (this.cm.options[option] === value) return
setOption(option, value)
})
})
// 1. set value
cm.setValue(this.content)
if (!this.file) {
cm.setCursor(cm.posFromIndex(this.content.length))
}
// 2. set mode
const modeInfo = findModeByFile(this.file)
if (modeInfo) {
loadMode(modeInfo.mode).then(() => this.options.mode = modeInfo.mime)
}
// 3. sync cursor state to corresponding editor properties
cm.on('cursorActivity', () => {
this.selections = cm.getSelections()
const { line, ch } = cm.getCursor()
this.cursorPosition = {
ln: line + 1,
col: ch + 1,
}
})
}
@observable selections = []
@observable cursorPosition = { ln: 1, col: 1 }
setCursor (...args) {
if (!args[0]) return
const lineColExp = args[0]
// if (is.string(lineColExp) && lineColExp.startsWith(':')) {
// const [line = 0, ch = 0] = lineColExp.slice(1).split(':')
// args = [line - 1, ch - 1]
// }
if (is.string(lineColExp)) {
const [line = 0, ch = 0] = lineColExp.split(':')
args = [line - 1, ch - 1]
}
this.cm.setCursor(...args)
setTimeout(() => this.cm.focus())
}
@computed get mode () {
if (!this.options.mode) return ''
const modeInfo = findModeByMIME(this.options.mode)
return modeInfo.name
}
setMode (mode) {
const modeInfo = is.string(mode) ? findModeByName(mode) : mode
this.options.mode = modeInfo.mime
}
@action update (props = {}) {
// simple assignments
extendObservable(this, props)
assignProps(this, props, {
tabId: String,
filePath: String,
gitBlame: Object,
})
if (props.revision) this.revision = props.revision
// file
if (!this.file && props.content) {
this._content = props.content
}
if (props.cm instanceof CodeMirror) this.cm = props.cm
}
@observable _options = observable.map({})
@computed get options () {
const options = { ...state.options, ...this._options.toJS() }
const self = this
const descriptors = Object.entries(options).reduce((acc, [key, value]) => {
acc[key] = {
enumerable: true,
get () { return value },
set (v) { self._options.set(key, v) },
}
return acc
}, {})
return Object.defineProperties({}, descriptors)
}
set options (value) {
this._options = observable.map(value)
}
@observable tabId = ''
@computed get tab () { return TabStore.getTab(this.tabId) }
@observable filePath = undefined
@computed get file () { return FileStore.get(this.filePath) }
@observable _content = ''
@computed get content () {
return this.file ? this.file.content : this._content
}
set content (v) { return this._content = v }
@observable gitBlame = {
show: false,
data: observable.ref([]),
}
destroy () {
this.dispose && this.dispose()
state.entities.delete(this.id)
}
}
export default state
export { state, Editor }
| JavaScript | 0 | @@ -2459,185 +2459,8 @@
%5B0%5D%0A
- // if (is.string(lineColExp) && lineColExp.startsWith(':')) %7B%0A // const %5Bline = 0, ch = 0%5D = lineColExp.slice(1).split(':')%0A // args = %5Bline - 1, ch - 1%5D%0A // %7D%0A
|
2a7c652fa82909616f20ff198458cea7c60f8f45 | split ascending/descending copy tests | test/methods.js | test/methods.js | var B = require('../').Buffer
var test = require('tape')
if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false
test('buffer.toJSON', function (t) {
var data = [1, 2, 3, 4]
t.deepEqual(
new B(data).toJSON(),
{ type: 'Buffer', data: [ 1, 2, 3, 4 ] }
)
t.end()
})
test('buffer.copy', function (t) {
// copied from nodejs.org example
var buf1 = new B(26)
var buf2 = new B(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
buf2[i] = 33 // ASCII !
}
buf1.copy(buf2, 8, 16, 20)
t.equal(
buf2.toString('ascii', 0, 25),
'!!!!!!!!qrst!!!!!!!!!!!!!'
)
t.end()
})
test('test offset returns are correct', function (t) {
var b = new B(16)
t.equal(4, b.writeUInt32LE(0, 0))
t.equal(6, b.writeUInt16LE(0, 4))
t.equal(7, b.writeUInt8(0, 6))
t.equal(8, b.writeInt8(0, 7))
t.equal(16, b.writeDoubleLE(0, 8))
t.end()
})
test('concat() a varying number of buffers', function (t) {
var zero = []
var one = [ new B('asdf') ]
var long = []
for (var i = 0; i < 10; i++) {
long.push(new B('asdf'))
}
var flatZero = B.concat(zero)
var flatOne = B.concat(one)
var flatLong = B.concat(long)
var flatLongLen = B.concat(long, 40)
t.equal(flatZero.length, 0)
t.equal(flatOne.toString(), 'asdf')
t.deepEqual(flatOne, one[0])
t.equal(flatLong.toString(), (new Array(10 + 1).join('asdf')))
t.equal(flatLongLen.toString(), (new Array(10 + 1).join('asdf')))
t.end()
})
test('fill', function (t) {
var b = new B(10)
b.fill(2)
t.equal(b.toString('hex'), '02020202020202020202')
t.end()
})
test('fill (string)', function (t) {
var b = new B(10)
b.fill('abc')
t.equal(b.toString(), 'abcabcabca')
b.fill('է')
t.equal(b.toString(), 'էէէէէ')
t.end()
})
test('copy() empty buffer with sourceEnd=0', function (t) {
var source = new B([42])
var destination = new B([43])
source.copy(destination, 0, 0, 0)
t.equal(destination.readUInt8(0), 43)
t.end()
})
test('copy() after slice()', function (t) {
var source = new B(200)
var dest = new B(200)
var expected = new B(200)
for (var i = 0; i < 200; i++) {
source[i] = i
dest[i] = 0
}
source.slice(2).copy(dest)
source.copy(expected, 0, 2)
t.deepEqual(dest, expected)
t.end()
})
test('copy() ascending and descending', function (t) {
var b
b = new B('abcdefghij')
b.copy(b, 0, 3, 10) // ascending copy
t.equal(b.toString(), 'defghijhij')
b = new B('abcdefghij')
b.copy(b, 3, 0, 7) // descending copy
t.equal(b.toString(), 'abcabcdefg')
t.end()
})
test('buffer.slice sets indexes', function (t) {
t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo')
t.end()
})
test('buffer.slice out of range', function (t) {
t.plan(2)
t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo')
t.equal((new B('hallo')).slice(10, 2).toString(), '')
t.end()
})
| JavaScript | 0.000005 | @@ -2327,20 +2327,16 @@
%0A var b
-%0A b
= new B
@@ -2430,16 +2430,75 @@
hij')%0A
+t.end()%0A%7D)%0A%0Atest('copy() descending', function (t) %7B%0A var
b = new
|
6a3bc5559ed2ba290ec34c8c690bf67847836be3 | Add pageCount to instance via usePagination hook | src/hooks/usePagination.js | src/hooks/usePagination.js | import { useMemo, useLayoutEffect } from 'react'
import PropTypes from 'prop-types'
//
import { addActions, actions } from '../actions'
import { defaultState } from './useTableState'
defaultState.pageSize = 10
defaultState.pageIndex = 0
addActions({
pageChange: '__pageChange__',
})
const propTypes = {
// General
manualPagination: PropTypes.bool,
}
export const usePagination = props => {
PropTypes.checkPropTypes(propTypes, props, 'property', 'usePagination')
const {
rows,
manualPagination,
disablePageResetOnDataChange,
debug,
state: [
{
pageSize,
pageIndex,
pageCount: userPageCount,
filters,
groupBy,
sortBy,
},
setState,
],
} = props
const pageOptions = useMemo(
() => [...new Array(userPageCount)].map((d, i) => i),
[userPageCount]
)
const rowDep = disablePageResetOnDataChange ? null : rows
useLayoutEffect(() => {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}, [setState, rowDep, filters, groupBy, sortBy])
const { pages, pageCount } = useMemo(() => {
if (manualPagination) {
return {
pages: [rows],
pageCount: userPageCount,
}
}
if (debug) console.info('getPages')
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
const pageCount = pages.length
return {
pages,
pageCount,
pageOptions,
}
}, [manualPagination, debug, rows, pageOptions, userPageCount, pageSize])
const page = manualPagination ? rows : pages[pageIndex] || []
const canPreviousPage = pageIndex > 0
const canNextPage = pageIndex < pageCount - 1
const gotoPage = pageIndex => {
if (debug) console.info('gotoPage')
return setState(old => {
if (pageIndex < 0 || pageIndex > pageCount - 1) {
return old
}
return {
...old,
pageIndex,
}
}, actions.pageChange)
}
const previousPage = () => {
return gotoPage(pageIndex - 1)
}
const nextPage = () => {
return gotoPage(pageIndex + 1)
}
const setPageSize = pageSize => {
setState(old => {
const topRowIndex = old.pageSize * old.pageIndex
const pageIndex = Math.floor(topRowIndex / pageSize)
return {
...old,
pageIndex,
pageSize,
}
}, actions.setPageSize)
}
return {
...props,
pages,
pageOptions,
page,
canPreviousPage,
canNextPage,
gotoPage,
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
}
| JavaScript | 0 | @@ -2696,24 +2696,39 @@
ageOptions,%0A
+ pageCount,%0A
page,%0A
|
65fc3b2ffc6440db110ed097e827918538a50b61 | debug fetcher | src/node_modules/fetcher/index.js | src/node_modules/fetcher/index.js | var collections = require('collections');
module.exports = function fetcher (route, callback) {
var collection = collections[route.collection];
var Model = collection.Model;
var model = new Model({
'@id': route.id
});
if (callback) {
model.fetch({
success: function (model, response, options) {
return callback(null, model);
},
error: function (model, response, options) {
return callback(response);
},
});
} else {
model.fetch();
}
return model;
}
| JavaScript | 0.000001 | @@ -34,16 +34,69 @@
tions');
+%0Avar debug = require('debug')(%22craftodex:ui:fetcher%22)
%0A%0Amodule
@@ -193,17 +193,16 @@
ction%5D;%0A
-%0A
var Mo
@@ -224,16 +224,34 @@
n.Model;
+%0A %0A debug(Model)
%0A%0A var
|
e6fcab08e699baa8fd2d9480c66e4ea85bd33447 | fix remove of global matchq; | functions/match/match.js | functions/match/match.js | var events = require("events");
var async = require("async");
var _ = require("lodash");
var shlog = require(global.gBaseDir + "/src/shlog.js");
var sh = require(global.gBaseDir + "/src/shutil.js");
var ShGame = require(global.gBaseDir + "/src/shgame.js");
var match = exports;
match.desc = "match players to the desired game and start them in it";
match.functions = {
add: {desc: "add caller to the game matcher", params: {name: {dtype: "string"}}, security: []},
remove: {desc: "remove caller from the game matcher", params: {name: {dtype: "string"}}, security: []},
counts: {desc: "list the match counts for all games", params: {}, security: []},
list: {desc: "list the match players for all games", params: {}, security: []}
};
// SWD: just init a global game queue for now
//if (_.isUndefined(global.matchq)) {
// global.matchq = {};
// global.matchq.tictactoe = {};
//}
var matchq = {};
matchq.tictactoe = {};
var info = {};
info.tictactoe = {minPlayers: 2, maxPlayers: 2};
match.add = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
if (_.isUndefined(global.matchq[name])) {
cb(1, sh.error("bad_game", "unknown game", {name: name}));
}
if (!_.isUndefined(global.matchq[name][uid])) {
cb(1, sh.error("match_added", "player is already being matched", {uid: uid, name: name}));
return;
}
var keys = Object.keys(global.matchq[name]);
if (keys.length + 1 >= info[name].maxPlayers) {
req.params.cmd = "game.create"; // change the command, req.param.name is already set
req.params.players = keys.slice(0, info[name].maxPlayers);
req.params.players.push(uid); // add the current user
sh.call("game.create", req, res, function (error, data) {
if (error) {
cb(error, data);
return;
}
var matchInfo = {};
matchInfo.gameId = data.data.gameId;
_.each(req.params.players, function (playerId) {
delete global.matchq[name][playerId];
matchInfo[playerId] = {};
});
_.each(req.params.players, function (playerId) {
global.socket.notifyUser(playerId, sh.event("event.match.made", matchInfo));
});
cb(0, sh.event("event.match", matchInfo));
return;
});
}
// just add the user
var ts = new Date().getTime();
var playerInfo = {uid: uid, posted: ts};
global.matchq[name][uid] = playerInfo;
cb(0, sh.event("event.match.add", playerInfo));
};
match.remove = function (req, res, cb) {
var uid = req.session.uid;
var name = req.params.name;
delete global.matchq[name][uid];
cb(0, sh.event("event.match.remove"));
};
match.counts = function (req, res, cb) {
var counts = {};
_.forOwn(global.matchq, function (gameq, idx) {
counts[idx] = Object.keys(gameq).length;
});
cb(0, sh.event("event.match.counts", counts));
};
match.list = function (req, res, cb) {
cb(0, sh.event("event.match.list", global.matchq));
}; | JavaScript | 0 | @@ -884,25 +884,26 @@
%7D;%0A//%7D%0A%0Avar
-m
+gM
atchq = %7B%7D;%0A
@@ -902,17 +902,18 @@
q = %7B%7D;%0A
-m
+gM
atchq.ti
@@ -930,17 +930,18 @@
%7B%7D;%0Avar
-i
+gI
nfo = %7B%7D
@@ -942,17 +942,18 @@
o = %7B%7D;%0A
-i
+gI
nfo.tict
@@ -1104,39 +1104,33 @@
(_.isUndefined(g
-lobal.m
+M
atchq%5Bname%5D)) %7B%0A
@@ -1215,31 +1215,25 @@
sUndefined(g
-lobal.m
+M
atchq%5Bname%5D%5B
@@ -1379,23 +1379,17 @@
t.keys(g
-lobal.m
+M
atchq%5Bna
@@ -1419,17 +1419,18 @@
+ 1 %3E=
-i
+gI
nfo%5Bname
@@ -1577,17 +1577,18 @@
lice(0,
-i
+gI
nfo%5Bname
@@ -1924,39 +1924,33 @@
delete g
-lobal.m
+M
atchq%5Bname%5D%5Bplay
@@ -2329,23 +2329,17 @@
ts%7D;%0A g
-lobal.m
+M
atchq%5Bna
@@ -2526,23 +2526,17 @@
delete g
-lobal.m
+M
atchq%5Bna
@@ -2662,23 +2662,17 @@
forOwn(g
-lobal.m
+M
atchq, f
@@ -2875,23 +2875,17 @@
list%22, g
-lobal.m
+M
atchq));
|
adb336ce92bed67f1aae6047974fb1632bdb11c0 | Display notifications when creating a new database | app/modules/databases/views.js | app/modules/databases/views.js | define([
"app",
"api"
],
function(app, FauxtonAPI) {
var Views = {};
Views.Item = FauxtonAPI.View.extend({
template: "templates/databases/item",
tagName: "tr",
serialize: function() {
return {
database: this.model
};
}
});
Views.List = FauxtonAPI.View.extend({
dbLimit: 10,
template: "templates/databases/list",
events: {
"click button.all": "selectAll",
"submit form.database-search": "switchDatabase"
},
initialize: function(options) {
this.collection.on("add", this.render, this);
},
serialize: function() {
return {
databases: this.collection
};
},
switchDatabase: function(event) {
event.preventDefault();
var dbname = this.$el.find("input.search-query").val();
if (dbname) {
// TODO: switch to using a model, or Databases.databaseUrl()
// Neither of which are in scope right now
// var db = new Database.Model({id: dbname});
var url = ["/database/", dbname, "/_all_docs?limit=10"].join('');
FauxtonAPI.navigate(url);
}
},
beforeRender: function() {
this.collection.each(function(database) {
this.insertView("table.databases tbody", new Views.Item({
model: database
}));
}, this);
},
afterRender: function() {
var dbLimit = this.dbLimit;
var ajaxReq;
this.$el.find("input.search-query").typeahead({
source: function(query, process) {
var url = [
app.host,
"/_all_dbs?startkey=%22",
query,
"%22&endkey=%22",
query,
"\u9999%22&limit=",
dbLimit
].join('');
if (ajaxReq) ajaxReq.abort();
ajaxReq = $.ajax({
url: url,
dataType: 'json',
success: function(data) {
process(data);
}
});
}
});
},
selectAll: function(evt){
$("input:checkbox").attr('checked', !$(evt.target).hasClass('active'));
}
});
Views.Sidebar = FauxtonAPI.View.extend({
template: "templates/databases/sidebar",
events: {
"click a#new": "newDatabase",
"click a#owned": "showMine",
"click a#shared": "showShared"
},
newDatabase: function() {
// TODO: use a modal here instead of the prompt
var name = prompt('Name of database', 'newdatabase');
var db = new this.collection.model({
id: encodeURIComponent(name),
name: name
});
db.save().done(function() {
var route = "#/database/" + name + "/_all_docs?limit=100";
app.router.navigate(route, { trigger: true });
}
);
},
showMine: function(){
console.log('will show users databases and hide shared');
},
showShared: function(){
console.log('will show shared databases and hide the users');
alert('Support for shared databases coming soon');
}
});
return Views;
});
| JavaScript | 0.996626 | @@ -2581,154 +2581,668 @@
-db.save().done(function() %7B%0A var route = %22#/database/%22 + name + %22/_all_docs?limit=100%22;%0A app.router.navigate(route, %7B trigger: true
+var notification = FauxtonAPI.addNotification(%7Bmsg: %22Creating database.%22%7D);%0A db.save().done(function() %7B%0A notification = FauxtonAPI.addNotification(%7B%0A msg: %22Database created successfully%22,%0A type: %22success%22,%0A clear: true%0A %7D);%0A var route = %22#/database/%22 + name + %22/_all_docs?limit=100%22;%0A app.router.navigate(route, %7B trigger: true %7D);%0A %7D%0A ).error(function(xhr) %7B%0A var responseText = JSON.parse(xhr.responseText).reason;%0A notification = FauxtonAPI.addNotification(%7B%0A msg: %22Create database failed: %22 + responseText,%0A type: %22error%22,%0A clear: true%0A
%7D);
|
17ed9829d5042340f67eeca7b8231a08fa35f941 | Modify reducer for function purity | app/reducers/editEventModal.js | app/reducers/editEventModal.js | 'use strict';
import { TOGGLE_EVENT_MODAL } from '../actions/index';
export default function eventEditingModal(state = false, action) {
switch (action.type) {
case TOGGLE_EVENT_MODAL:
console.log(`Action ${action.type} executed with empty payload!`);
state = !state;
default:
return state;
}
};
| JavaScript | 0.000014 | @@ -105,16 +105,21 @@
ingModal
+State
(state =
|
552857d00f5101824709575a812b159b0798eb60 | remove left over code | phobos/source/package.js | phobos/source/package.js | enyo.depends(
"Phobos.js",
"AutoComplete.js",
"FindPopup.js",
"ProjectCtrl.js",
"EditorSettings.js",
"AceScroller.js",
"AceWrapper.js"
);
| JavaScript | 0.000001 | @@ -86,31 +86,8 @@
%22,%0D%0A
-%09%22EditorSettings.js%22,%0D%0A
%09%22Ac
|
34dc80d91cdc2c996654aaf721a56d40d5e6422d | Add logging | app/serviceworkers/sw-cache.js | app/serviceworkers/sw-cache.js | var CURRENT_VERSION = 'v2';
var CACHE_URLS = {
'https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects': 1,
'https://api.cosmicjs.com/v1/blog-cb/objects?bustcache=true': 2
};
function cacheOpen (event, response) {
return function (cache) {
cache
.put(event.request, response.clone())
.then(function () {
console.info('successfully cached');
})
.catch(function (err) {
console.error('cache error', err);
});
return response;
}
}
function fetchSuccess (event) {
return function (response) {
console.info('fetch success');
return caches
.open(CURRENT_VERSION)
.then(cacheOpen(event, response));
}
}
function noCache (event) {
return function () {
console.info('no cache', event.request.url);
return fetch(event.request)
.then(fetchSuccess(event));
}
}
function checkCacheResponse (response) {
if (!response) {
console.info('no cache response');
throw new Error();
}
// console.info('cache response', response);
return response;
}
this.addEventListener('fetch', function (event) {
var cacheType = CACHE_URLS[event.request.url];
if (!cacheType) return;
// console.info('fetch', event.request.url);
if (cacheType === 1) {
event.respondWith(
caches
.match(event.request)
.then(checkCacheResponse)
.catch(noCache(event))
.catch(function noCacheFail () {
console.error('no cache fail');
})
);
} else {
var bustRequest = new Request('https://api.cosmicjs.com/v1/blog-cb/objects');
fetch(bustRequest).then(fetchSuccess({
request: bustRequest
}));
}
});
this.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CURRENT_VERSION) {
return caches.delete(key);
}
}));
})
);
});
| JavaScript | 0.000002 | @@ -417,16 +417,45 @@
cached'
+, event.request.url, response
);%0A
@@ -664,16 +664,35 @@
success'
+, event.request.url
);%0A r
|
16330940dfeec1a4a8c0d82f1a5b5f32d26dfd30 | fix indentation | preview/source/Preview.js | preview/source/Preview.js | enyo.kind(
{
name: "PreviewDevicePicker",
kind: "onyx.Picker",
components: [
{content: "default", value: { height: 800, width: 600, ppi: 163, dpr: 1 }, active: true},
{content: "iPhone\u2122", value: { height: 480, width: 320, ppi: 163, dpr: 1 }},
{content: "iPhone\u2122 4", value: { height: 960, width: 640, ppi: 326, dpr: 2 }},
{content: "iPhone\u2122 5", value: { height: 1136, width: 640, ppi: 326, dpr: 2 }},
{content: "iPad\u2122 Retina", value: { height: 2048, width: 1536, ppi: 264, dpr: 2 }},
{content: "iPad\u2122 2", value: { height: 1280, width: 800, ppi: 132, dpr: 1 }},
{content: "iPad\u2122 mini", value: { height: 1024, width: 768, ppi: 163, dpr: 1 }}
]
}
);
enyo.kind(
{
name: "Preview",
kind: "FittableColumns",
classes: "enyo-fit enyo-border-box",
style: "margin: 4px; background-color: #DDD",
components: [
{
style: "width: 150px; margin: 4px" ,
components: [
{
kind: 'onyx.Groupbox',
style : "margin-top: 8px",
components: [
{kind: "onyx.GroupboxHeader", content: "Orientation"},
{
kind: "onyx.PickerDecorator",
onSelect: "resize",
style : "padding: 6px",
components:
[
{style: "width: 100%"}, // A content-less PickerButton
{
kind: "onyx.Picker", name: "orientation",
components: [
{content: "portrait", active: true, swap: false},
{content: "landscape", swap: true }
]
}
]
}
]
},
{tag: "br"},
{
kind: 'onyx.Groupbox',
components: [
{kind: "onyx.GroupboxHeader", content: "Device"},
{
kind: "onyx.PickerDecorator",
onSelect: "resize",
style :"padding: 6px",
components:
[
{style: "width: 100%"}, // A content-less PickerButton
{
kind: "PreviewDevicePicker", name: "device"
}
]
}
]
},
{tag: "br"},
{
kind: 'onyx.Groupbox',
components: [
{kind: "onyx.GroupboxHeader", content: "Details"},
{content: "width: 600px", name: "devWidth", style: "padding: 8px"},
{content: "height: 800px", name: "devHeight", style: "padding: 8px"},
{content: "DPR: 1", name: "devDPR", style: "padding: 8px",
attributes: {title: "display pixel ratio"} }
]
},
{tag: "br"},
{
kind: 'onyx.Groupbox',
components: [
{kind: "onyx.GroupboxHeader", content: "Zoom"},
{
// padding required so the gray box is connected to groupbox
style: "padding-top: 4px; padding-bottom: 4px",
components: [
{kind: "onyx.Slider", value: 100, onChange: 'zoom', onChanging: 'zoom' }
]
}
]
},
{tag: "br"},
{
kind: "onyx.Button",
ontap:"reload",
style: "padding: 5px; width: 100%; margin-bottom: 5px",
components: [
{tag: 'img', attributes: { src: "assets/images/preview_reload.png"} }
]
},
{tag: "br"},
{
kind:"onyx.Button",
content: "Detach test",
ontap:"detachIframe",
style: "padding: 5px; width: 100%",
attributes: { title: "detach test device, then right click to enable Ripple emulator"}
}
]
},
{
name: 'scrolledIframe',
fit: true,
kind: "ares.ScrolledIFrame"
}
],
debug: true ,
iframeUrl: null,
dlog: function() {
if (this.debug) {
this.log.apply(this, arguments) ;
}
},
zoom: function(inSender, inEvent) {
this.scale = 0.3 + 0.7 * inSender.getValue() / 100 ;
this.applyScale() ;
},
applyScale: function() {
enyo.dom.transformValue(
this.$.scrolledIframe.$.iframe, "scale", this.scale
) ;
this.resized() ;
},
resize: function() {
var device = this.$.device.selected ;
var orientation = this .$.orientation.selected ;
var dw = device.value.width / device.value.dpr;
var dh = device.value.height / device.value.dpr;
this.dlog("size for device " , device.content , " orientation " , orientation.content ) ;
var swap = orientation.swap ;
var targetW = swap ? dh : dw ;
var targetH = swap ? dw : dh ;
this.$.scrolledIframe.setGeometry( targetW , targetH) ;
this.$.devWidth .setContent("width: " + targetW + 'px') ;
this.$.devHeight.setContent("height: " + targetH + 'px') ;
this.$.devDPR .setContent("DPR: " + device.value.dpr) ;
this.resized() ;
},
getQueryParams: function(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens, re = /[?&]?([^=&]+)=?([^&]*)/g;
while ((tokens = re.exec(qs))) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
},
// retrieve URL from window and setup iframe url
create: function() {
this.inherited(arguments);
var param = this.getQueryParams(window.location.search) ;
this.log("preview url " + param.url) ;
this.iframeUrl = param.url ;
this.$.scrolledIframe.setUrl (param.url) ;
},
reload: function() {
this.$.scrolledIframe.reload();
this.applyScale() ;
},
detachIframe: function() {
window.open(
this.iframeUrl ,
'_blank', // ensure that a new window is created each time preview is tapped
'scrollbars=1,menubar=1',
false
);
window.close();
}
}
);
| JavaScript | 0.000963 | @@ -1615,17 +1615,16 @@
%7B%0A%09%09%09%09%09%09
-
kind: 'o
|
791fbfa58a6f7bf30c4231a0a1a2fc6f5d5d94c9 | remove redundant semicolon in modal.js | src/scripts/modal.js | src/scripts/modal.js | // modal.js
// ==================================================
+function($) {
'use strict'
var Modal = function(element, options) {
this.$element = $(element)
this.$target = $(this.$element.data('target') || this.$element.attr('href'))
this.$doc =$(document.body)
this.options = options
this.$backdrop =
this.isOpen = null
}
Modal.DEFAULTS = {
}
Modal.prototype.toggle = function() {
this.isOpen ? this.close() : this.open()
}
Modal.prototype.open = function() {
var that = this
var e = $.Event('fancy:modal:open')
this.$element.trigger(e)
if(this.isOpen || e.isDefaultPrevented()) return
this.isOpen = true
this.$doc.addClass('modal-open')
this.$target.one('tap', '[data-dismiss="modal"]', $.proxy(this.close, this))
this.backdrop(function() {
var transition = $.support.transition && that.$target.hasClass('fade')
that.$target.show().scrollTop(0)
if(transition) that.$target[0].offsetWith // reflow
that.$target.addClass('in')
var e = $.Event('fancy:modal:opend')
transition ?
that.$target.find('.modal-dialog').one($.support.transition.end, function() {
that.$target.trigger('focus').trigger(e)
}).emulateTransitionEnd(300) : that.$target.trigger('focus').trigger(e)
});
}
Modal.prototype.close = function(e) {
if(e) e.preventDefault()
e = $.Event('fancy:modal:close')
this.$element.trigger(e)
if(!this.isOpen || e.isDefaultPrevented()) return
this.isOpen = false
this.$doc.removeClass('modal-open')
this.$target.removeClass('in')
$.support.transition && this.$target.hasClass('fade') ?
this.$target.one($.support.transition.end, $.proxy(this.hideDialog, this)).emulateTransitionEnd(300) :
this.hideDialog()
}
Modal.prototype.hideDialog = function() {
var that = this
this.$target.hide();
this.backdrop(function() {
that.$element.trigger('fancy:modal:hidden')
});
}
Modal.prototype.backdrop = function(callback) {
var that = this
var animate = this.$target.hasClass('fade') ? 'fade' : ''
if (this.isOpen) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="backdrop ' + animate + '" />')
.appendTo(this.$doc)
this.$target.one('tap', $.proxy(function(e) {
if(e.target !== e.currentTarget) return
this.close.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth; // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isOpen && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$target.hasClass('fade') ?
this.$backdrop
.one($.support.transition.end, callbackRemove)
.emulateTransitionEnd(150) :
callbackRemove()
} else if (callback) {
callback()
}
};
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
};
var old = $.fn.modal
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('fancy.modal')
var options = $.extend({}, $this.data(), typeof option == 'object' && option)
if(!data) $this.data('fancy.modal', (data = new Modal(this, options)))
if(typeof option == 'string') data[option]()
else data.open()
})
}
$.fn.modal = Plugin
$.fn.modal.noConflict = function() {
$.fn.modal = old
return this
}
$(document).on('tap', '[data-toggle="modal"]', function() {
var $this = $(this)
var option = $this.data('fancy.modal') ? 'toggle' : $.extend({}, $this.data())
Plugin.call($this, option)
})
}(window.Zepto)
| JavaScript | 0.999619 | @@ -1352,33 +1352,32 @@
rigger(e)%0A %7D)
-;
%0A %7D%0A%0A Modal.pr
@@ -1956,17 +1956,16 @@
t.hide()
-;
%0A thi
@@ -3025,38 +3025,40 @@
sition && this.$
-target
+backdrop
.hasClass('fade'
|
b5ad9544ae5f5f94e6441793d37e68d64988eb1a | add new task from modal | pinch/static/js/pinch.js | pinch/static/js/pinch.js | // Project specific Javascript goes here.
function setup_highlighting(text_selector, button_selector, field_name, options_callback)
{
var target = $(text_selector)[0];
if (target) {
console.log("Setting up highlighting for " + text_selector);
var editor = CodeMirror.fromTextArea(target, {
lineWrapping: true,
readOnly: true
});
// Make the manipulation occur on the mouseup interaction
var lastSel = undefined;
var dblDebounceFn = function() {
lastSel = editor.doc.listSelections()[0];
};
// var debounceFn = _.debounce(dblDebounceFn, 450);
editor.on('cursorActivity', dblDebounceFn);
var el = editor.getWrapperElement();
$(el).mouseup(function() {
console.log("marking selection", lastSel.head.ch, lastSel.anchor.ch);
var options = options_callback();
var sel = lastSel;
console.log("Recording selection", sel)
if (sel.head.ch > sel.anchor.ch) {
editor.doc.markText(sel.anchor, sel.head, options);
} else {
editor.doc.markText(sel.head, sel.anchor, options);
}
});
var currentSelections = JSON.parse($("#selections").val());
for (var i = 0; i < currentSelections.length; i++)
{
var currentSelection = currentSelections[i];
var options = options_callback();
editor.doc.markText({line: currentSelection.line, ch: currentSelection.statement_start}, {line: currentSelection.line, ch: currentSelection.statement_end}, options)
}
// Delete all struckthrough text
$(button_selector).click( function() {
console.log("hi");
var $stricken = editor.getAllMarks();
console.log($stricken);
var selections = [];
for (var i = 0; i < $stricken.length; i++) {
var textMarker = $stricken[i];
for (var j = 0; j < textMarker.lines.length; j++) {
var line = textMarker.lines[j];
var lineNo = line.lineNo()
for (var k = 0; k < line.markedSpans.length; k++) {
var markedSpan = line.markedSpans[k];
selections.push({ "line": lineNo, "statement_start": markedSpan.from, "statement_end": markedSpan.to });
console.log("Span", markedSpan)
}
}
}
$("#selections").val(JSON.stringify(selections));
});
$("#clear").click( function() {
console.log("Clearing all selections...")
var $stricken = editor.getAllMarks();
for (var i = 0; i < $stricken.length; i++) {
$stricken[i].clear()
}
})
}
}
$(document).ready(function() {
setup_highlighting("#strike_statement", "#minify_next", "redactions", function() {
return {
className: 'strikethrough',
atomic: false
}
});
setup_highlighting("#highlight_statement", "#highlight_next", "workstreams", function() {
return {
className: 'highlight',
atomic: false
}
});
// loop over array and call .remove() on each element
// var $ticket = $('<div class="task-header"><textarea></textarea></div>');
// $button_name.click(function() {
// });
// Add Sticky Note Button
var $new_task = $('<li class="ticket">This is another task</li>');
// Drag and Drop sticky notes
var adjustment
$("ul.drag_list").sortable({
group: '.drag_list',
connectWith: '.drag_list',
pullPlaceholder: false,
// animation on drop
onDrop: function (item, targetContainer, _super) {
var clonedItem = $('<li/>').css({height: 0})
item.before(clonedItem)
clonedItem.animate({'height': item.height()})
item.animate(clonedItem.position(), function () {
clonedItem.detach()
_super(item)
})
},
// set item relative to cursor position
onDragStart: function ($item, container, _super) {
var offset = $item.offset(),
pointer = container.rootGroup.pointer
adjustment = {
left: pointer.left - offset.left,
top: pointer.top - offset.top
}
_super($item, container)
},
onDrag: function ($item, position) {
$item.css({
left: position.left - adjustment.left,
top: position.top - adjustment.top
})
}
});
});
| JavaScript | 0.000029 | @@ -2886,27 +2886,324 @@
on%0A%09
-var $new_task = $('
+// Select the list that follows the button clicked%0A%09var $current_list;%0A%09$(%22.add%22).click(function() %7B%0A%09%09$current_list = $(this).parent().next();%0A%09%7D);%0A%09// Take the text from the input from the modal%0A%09$(%22.save%22).click(function() %7B%0A%09%09var new_task_text = $(%22.modal-body input%22).val(); // %22#myModal%22%0A%09%09var $new_task = $(%22
%3Cli
@@ -3212,46 +3212,132 @@
ass=
-%22
+'
ticket
-%22%3EThis is another task%3C/li%3E');%0A
+'%3E%22 + new_task_text + %22%3C/li%3E%22);%0A%09%09$current_list.append($new_task);%0A%09%09$(%22.modal-body input%22).removeAttr('value');%0A%09%7D);
%0A%0A%09/
|
6414a91b594e04474ad4074425ff1e9a03ad8ddf | add uses in misc | public/js/Data.js | public/js/Data.js |
var data = angular.module('data',[]);
data.factory("HopForm",function() {
return {
query: function() {
return [
{
name:'Pellet',
utilization: 1
},{
name:'Whole Leaf',
utilization: 0.9
},{
name:'Plug',
utilization: 0.92
}];
}
};
});
data.factory("HopUse",function() {
return {
query: function() {
return [
{
name:'Boil',
utilization: 1
},{
name:'First Wort',
utilization: 1.1
},{
name:'Dry Hop',
utilization: 0
},{
name:'Aroma',
utilization: 0.5
},{
name:'Mash',
utilization: 0.2
}
];
}
};
});
data.factory("FermentableUses",function() {
return {
defaultValue: 'Mash',
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].name ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{
name:'Mash',
mash: true
},{
name:'Recirculating',
mash: true
},{
name:'Boil',
mash: false
},{
name:'Fermentation',
mash: false
}
];
}
};
});
data.factory("MiscType",function() {
return {
query: function() {
return ['Fining',
'Water Agent',
'Spice',
'Other',
'Herb',
'Flavor'];
}
};
});
data.factory("MiscUse",function() {
return {
query: function() {
return ['Boil',
'Mash',
'Secondary'];
}
};
});
data.factory('PitchRate', function() {
return {
query: function() {
return [
{value:0.35, name:'MFG Recomendado 0.35 (Ale, levadura fresca)'},
{value:0.5, name:'MFG Recommendado+ 0.5 (Ale, levadura fresca)'},
{value:0.75 , name:'Pro Brewer 0.75 (Ale)'},
{value:1.0, name:'Pro Brewer 1.0 (Ale, Alta densidad)'},
{value:1.25, name:'Pro Brewer 1.25 (Ale, or Alta densidad)'},
{value:1.5, name:'Pro Brewer 1.5 (Lager)'},
{value:1.75, name:'Pro Brewer 1.75 (Lager)'},
{value:2.0, name:'Pro Brewer 2.0 (Lager alta densidad)'}
];
}
};
});
data.factory('State', function() {
return {
valueOf: function(name) {
for ( var i=0; i<this.query().length; i++ ) {
if ( name === this.query()[i].value ) {
return this.query()[i];
}
}
return null;
},
query: function() {
return [
{value:'wish', name:'Deseo'},
{value:'draft', name:'Borrador'},
{value:'ready', name:'Lista'},
{value:'running', name:'En Curso'},
{value:'finished', name:'Finalizada'},
{value:'archived', name:'Archivada'}
];
}
};
});
| JavaScript | 0 | @@ -2264,32 +2264,92 @@
'Mash',%0A
+ 'Licor',%0A 'Primary',%0A
|
27a20e43cd9ce9dc3e32e44535ea79ecea83fde4 | remove validation errors on detached | src/select/select.js | src/select/select.js | import {bindable, customAttribute} from 'aurelia-templating';
import {BindingEngine} from 'aurelia-binding';
import {inject} from 'aurelia-dependency-injection';
import {TaskQueue} from 'aurelia-task-queue';
import {getLogger} from 'aurelia-logging';
import {fireEvent} from '../common/events';
import {getBooleanFromAttributeValue} from '../common/attributes';
import {DOM} from 'aurelia-pal';
@inject(Element, BindingEngine, TaskQueue)
@customAttribute('md-select')
export class MdSelect {
@bindable() disabled = false;
@bindable() enableOptionObserver = false;
@bindable() label = '';
@bindable() showErrortext = true;
_suspendUpdate = false;
subscriptions = [];
input = null;
dropdownMutationObserver = null;
optionsMutationObserver = null;
constructor(element, bindingEngine, taskQueue) {
this.element = element;
this.taskQueue = taskQueue;
this.handleChangeFromViewModel = this.handleChangeFromViewModel.bind(this);
this.handleChangeFromNativeSelect = this.handleChangeFromNativeSelect.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.log = getLogger('md-select');
this.bindingEngine = bindingEngine;
}
attached() {
this.taskQueue.queueTask(() => {
this.createMaterialSelect(false);
let wrapper = $(this.element).parent('.select-wrapper');
if (this.label && !wrapper.siblings("label").length) {
let div = $('<div class="input-field"></div>');
let va = this.element.attributes.getNamedItem('validate');
if (va) {
div.attr(va.name, va.label);
}
wrapper.wrap(div);
$(`<label class="md-select-label">${this.label}</label>`).insertAfter(wrapper);
}
});
this.subscriptions.push(this.bindingEngine.propertyObserver(this.element, 'value').subscribe(this.handleChangeFromViewModel));
$(this.element).on('change', this.handleChangeFromNativeSelect);
}
detached() {
$(this.element).off('change', this.handleChangeFromNativeSelect);
this.observeVisibleDropdownContent(false);
this.observeOptions(false);
this.dropdownMutationObserver = null;
$(this.element).material_select('destroy');
this.subscriptions.forEach(sub => sub.dispose());
}
refresh() {
this.taskQueue.queueTask(() => {
this.createMaterialSelect(true);
});
}
labelChanged(newValue) {
this.updateLabel();
}
updateLabel() {
if (this.label) {
const $label = $(this.element).parent('.select-wrapper').siblings('.md-select-label');
$label.text(this.label);
}
}
disabledChanged(newValue) {
this.toggleControl(newValue);
}
showErrortextChanged() {
this.setErrorTextAttribute();
}
setErrorTextAttribute() {
let input = this.element.parentElement.querySelector('input.select-dropdown');
if (!input) return;
this.log.debug('showErrortextChanged: ' + this.showErrortext);
input.setAttribute('data-show-errortext', getBooleanFromAttributeValue(this.showErrortext));
}
notifyBindingEngine() {
this.log.debug('selectedOptions changed', arguments);
}
handleChangeFromNativeSelect() {
if (!this._suspendUpdate) {
this.log.debug('handleChangeFromNativeSelect', this.element.value, $(this.element).val());
this._suspendUpdate = true;
fireEvent(this.element, 'change');
this._suspendUpdate = false;
}
}
handleChangeFromViewModel(newValue) {
this.log.debug('handleChangeFromViewModel', newValue, $(this.element).val());
if (!this._suspendUpdate) {
this.createMaterialSelect(false);
}
}
toggleControl(disable) {
let $wrapper = $(this.element).parent('.select-wrapper');
if ($wrapper.length > 0) {
if (disable) {
$('.caret', $wrapper).addClass('disabled');
$('input.select-dropdown', $wrapper).attr('disabled', 'disabled');
$wrapper.attr('disabled', 'disabled');
} else {
$('.caret', $wrapper).removeClass('disabled');
$('input.select-dropdown', $wrapper).attr('disabled', null);
$wrapper.attr('disabled', null);
$('.select-dropdown', $wrapper).dropdown({'hover': false, 'closeOnClick': false});
}
}
}
createMaterialSelect(destroy) {
this.observeVisibleDropdownContent(false);
this.observeOptions(false);
if (destroy) {
$(this.element).material_select('destroy');
}
$(this.element).material_select();
this.toggleControl(this.disabled);
this.observeVisibleDropdownContent(true);
this.observeOptions(true);
this.setErrorTextAttribute();
}
observeVisibleDropdownContent(attach) {
if (attach) {
if (!this.dropdownMutationObserver) {
this.dropdownMutationObserver = DOM.createMutationObserver(mutations => {
let isHidden = false;
for (let mutation of mutations) {
if (window.getComputedStyle(mutation.target).getPropertyValue('display') === 'none') {
isHidden = true;
}
}
if (isHidden) {
this.dropdownMutationObserver.takeRecords();
this.handleBlur();
}
});
}
this.dropdownMutationObserver.observe(this.element.parentElement.querySelector('.dropdown-content'), {
attributes: true,
attributeFilter: ['style']
});
} else {
if (this.dropdownMutationObserver) {
this.dropdownMutationObserver.disconnect();
this.dropdownMutationObserver.takeRecords();
}
}
}
observeOptions(attach) {
if (getBooleanFromAttributeValue(this.enableOptionObserver)) {
if (attach) {
if (!this.optionsMutationObserver) {
this.optionsMutationObserver = DOM.createMutationObserver(mutations => {
// this.log.debug('observeOptions', mutations);
this.refresh();
});
}
this.optionsMutationObserver.observe(this.element, {
// childList: true,
characterData: true,
subtree: true
});
} else {
if (this.optionsMutationObserver) {
this.optionsMutationObserver.disconnect();
this.optionsMutationObserver.takeRecords();
}
}
}
}
//
// Firefox sometimes fire blur several times in a row
// observable at http://localhost:3000/#/samples/select/
// when enable 'Disable Functionality', open that list and
// then open 'Basic use' list.
// Chrome - ok
// IE 11 - ok
// Edge ?
//
_taskqueueRunning = false;
handleBlur() {
if (this._taskqueueRunning) return;
this._taskqueueRunning = true;
this.taskQueue.queueTask(() => {
this.log.debug('fire blur event');
fireEvent(this.element, 'blur');
this._taskqueueRunning = false;
});
}
}
| JavaScript | 0 | @@ -2119,16 +2119,88 @@
= null;%0A
+ $(this.element).parent().children(%22.md-input-validation%22).remove();%0A
$(th
|
7b78a9d1173b96bcc0e9bf7acb97ef077509cf2f | Switch from false property to eql for IE 8 & lower | polyfills/Array/prototype/fill/tests.js | polyfills/Array/prototype/fill/tests.js | it('exists', function () {
expect(Array.prototype).to.have.property('fill');
});
it('has correct instance', function () {
expect(Array.prototype.fill).to.be.a(Function);
});
it('has correct name', function () {
function nameOf(fn) {
return Function.prototype.toString.call(fn).match(/function\s*([^\s]*)\(/)[1];
}
expect(nameOf(Array.prototype.fill)).to.be('fill');
});
it('has correct argument length', function () {
expect(Array.prototype.fill.length).to.be(1);
});
it('is not enumerable', function () {
expect(Array.prototype.propertyIsEnumerable('fill')).to.be.false;
});
it('fills whole array when using only one argument', function () {
expect([1, 2, 3].fill(0)).to.eql([0, 0, 0]);
});
it('starts filling from the start index given by second argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 3)).to.eql([1, 2, 3, 0, 0, 0]);
});
it('can use a negative start index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, -2)).to.eql([1, 2, 3, 4, 0, 0]);
});
it('stops filling at the end index given by third argument', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 0, 2)).to.eql([0, 0, 3, 4, 5, 6]);
});
it('can use a negative end index', function () {
expect([1, 2, 3, 4, 5, 6].fill(0, 1, -2)).to.eql([1, 0, 0, 0, 5, 6]);
});
it('does not fill if start index is larger than array', function () {
expect([1, 2, 3].fill(0, 5)).to.eql([1, 2, 3]);
});
it('does fill if start index is not a number', function () {
expect([1, 2, 3].fill(0, NaN)).to.eql([0, 0, 0]);
expect([1, 2, 3].fill(1, '')).to.eql([1, 1, 1]);
expect([1, 2, 3].fill(2, {})).to.eql([2, 2, 2]);
});
it('does not fill if end index is not a number', function () {
expect([1, 2, 3].fill(0, 0, NaN)).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(1, 0, '')).to.eql([1, 2, 3]);
expect([1, 2, 3].fill(2, 0, {})).to.eql([1, 2, 3]);
});
it('works on array-like objects', function () {
expect([].fill.call({ length: 3 }, 4)).to.eql({0: 4, 1: 4, 2: 4, length: 3});
});
| JavaScript | 0 | @@ -572,16 +572,18 @@
.to.
-be.
+eql(
false
+)
;%0A%7D)
|
a9641a03a7c0c11ab48d174ace527aa58a177ed9 | support language tables | scraper.js | scraper.js | var request = require('request'),
cheerio = require('cheerio'),
dateFormat = require('dateformat');
var Menu = {
date: dateFormat(new Date(), 'yyyy-mm-dd, hh:MM:ss TT'),
diningHalls: {
atwater: {
breakfast: null,
lunch: null
},
proctor: {
breakfast: null,
lunch: null,
dinner: null
},
ross: {
breakfast: null,
lunch: null,
dinner: null
}
}
}
function requestMenu(callback) {
var menuURL = 'https://menus.middlebury.edu';
request({
method: 'GET',
url: menuURL
}, callback);
}
function parseMenu(err, res, body) {
if (err || res.statusCode !== 200) throw err;
var $ = cheerio.load(body),
diningNodes = {
atwater: null,
proctor: null,
ross: null
},
parseMeal = function(location, meal, $node) {
var itemsArr = $node.find('.views-field-body').text().trim().split('\n');
Menu.diningHalls[location][meal] = itemsArr;
};
// Separate Atwater, Proctor, Ross
$('div.view-content h3').each(function(i, elem) {
var $this = $(elem);
switch ($this.text()) {
case 'Atwater':
diningNodes.atwater = $this.next();
break;
case 'Proctor':
diningNodes.proctor = $this.next();
break;
case 'Ross':
diningNodes.ross = $this.next();
break;
}
});
// Separate meals
for (var node in diningNodes) {
$(diningNodes[node]).find('td').each(function(i, elem) {
var $this = $(this);
switch ($this.find('span.views-field-field-meal').text().trim()) {
case 'Breakfast':
parseMeal(node, 'breakfast', $this);
break;
case 'Lunch':
parseMeal(node, 'lunch', $this);
break;
case 'Dinner':
parseMeal(node, 'dinner', $this);
break;
}
});
};
// return {
// 'date': date,
// 'atwater': diningHalls.atwater || [noInfoMessage],
// 'proctor': diningHalls.proctor || [noInfoMessage],
// 'ross': diningHalls.ross || [noInfoMessage],
// };
}
function scrapeMenu() {
requestMenu(parseMenu);
return Menu;
}
exports.scrapeMenu = scrapeMenu; | JavaScript | 0 | @@ -182,25 +182,26 @@
,%0A dining
-H
+_h
alls: %7B%0A
@@ -475,32 +475,94 @@
dinner: null%0A
+ %7D,%0A language_tables: %7B%0A lunch: null%0A
%7D%0A %7D%0A
@@ -943,24 +943,58 @@
ross: null%0A
+ language_tables: null%0A
%7D,%0A
@@ -1650,32 +1650,151 @@
break;%0A
+ case 'Language Tables':%0A diningNodes.language_tables = $this.next();%0A break;%0A
%7D%0A %7D)
@@ -2397,24 +2397,24 @@
%7D);%0A
+
%7D;%0A%0A
// r
@@ -2409,240 +2409,8 @@
%7D;%0A%0A
- // return %7B%0A // 'date': date,%0A // 'atwater': diningHalls.atwater %7C%7C %5BnoInfoMessage%5D,%0A // 'proctor': diningHalls.proctor %7C%7C %5BnoInfoMessage%5D,%0A // 'ross': diningHalls.ross %7C%7C %5BnoInfoMessage%5D,%0A // %7D;%0A%0A
%7D%0A%0Af
|
6378f2926622488449c839ce9de38916b4fbfb8d | Add LICENSE in the javascript source | src/pre.js | src/pre.js | (function() {
dig = {};
| JavaScript | 0.000001 | @@ -1,8 +1,1071 @@
+/*%0ACopyright (c) 2012 Chris Pettitt%0A%0APermission is hereby granted, free of charge, to any person obtaining a copy%0Aof this software and associated documentation files (the %22Software%22), to deal%0Ain the Software without restriction, including without limitation the rights%0Ato use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0Acopies of the Software, and to permit persons to whom the Software is%0Afurnished to do so, subject to the following conditions:%0A%0AThe above copyright notice and this permission notice shall be included in%0Aall copies or substantial portions of the Software.%0A%0ATHE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0AIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0AFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0AAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0ALIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0AOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0ATHE SOFTWARE.%0A*/%0A
(functio
|
c9311a54bcb12cc88096681fb5eaff60223c6b22 | Fix incorrect merge introduced in a9fa4fc. (Validations weren't running in Responses#new) | Resources/ui/common/responses/ResponsesNewView.js | Resources/ui/common/responses/ResponsesNewView.js | //All the questoin in a survey
function ResponsesNewView(surveyID) {
var _ = require('lib/underscore')._;
var Question = require('models/question');
var Survey = require('models/survey');
var Response = require('models/response');
var QuestionView = require('ui/common/questions/QuestionView');
var ResponseViewHelper = require('ui/common/responses/ResponseViewHelper');
var responseViewHelper = new ResponseViewHelper;
var self = Ti.UI.createView({
layout : 'vertical'
})
var scrollableView = Ti.UI.createScrollableView({
showPagingControl : true
});
self.add(scrollableView);
var survey = Survey.findOneById(surveyID);
var questions = survey.firstLevelQuestions();
var allQuestionViews = Ti.UI.createView();
var saveButton = Ti.UI.createButton({
title : 'Save',
width : '48%'
});
var completeButton = Ti.UI.createButton({
title : 'Complete',
width : '48%'
});
responseViewHelper.paginate(questions, allQuestionViews, scrollableView, [saveButton, completeButton]);
var getCurrentLocation = function() {
var location = {};
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
Ti.API.info("Error getting location");
return;
}
location.longitude = e.coords.longitude;
location.latitude = e.coords.latitude;
Ti.API.info("longitude = " + e.coords.longitude);
Ti.API.info("latitude = " + e.coords.latitude);
});
return location;
};
var validateAndSaveAnswers = function(e, status) {
var questionViews = responseViewHelper.getQuestionViews(self);
var answersData = _(questionViews).map(function(fields, questionID) {
Ti.API.info("questionid:" + questionID);
Ti.API.info("content:" + fields['valueField'].getValue());
return {
'question_id' : questionID,
'content' : fields.valueField.getValue()
}
});
var responseLocation = getCurrentLocation();
responseErrors = Response.validate(answersData, status);
if (!_.isEmpty(responseErrors)) {
responseViewHelper.displayErrors(responseErrors, questionViews);
alert("There were some errors in the response.");
} else {
Response.createRecord(surveyID, status, answersData);
self.fireEvent('ResponsesNewView:savedResponse');
}
};
completeButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "complete");
});
saveButton.addEventListener('click', function(event) {
validateAndSaveAnswers(event, "incomplete");
});
return self;
}
module.exports = ResponsesNewView;
| JavaScript | 0 | @@ -1527,20 +1527,32 @@
onViews(
-self
+allQuestionViews
);%0A%09%09var
|
0bf9e7a1b9c86fd7b1a9da434cca2e49b93870ed | Fix bug where error message isn't shown for invalid room name | public/js/main.js | public/js/main.js | /* Atlassian M.E.A.T.
* Authors: Adam Ahmed, Martin Jopson, Stephen Russell, Robert Smart
* (c) 2011 Atlassian Pty Ltd.
* Atlassian M.E.A.T. may be freely distributed under the MIT Expat license.
*/
(function() {
var roomName = ParameterParser.parse().room;
function runAtMidnight(func) {
var oneDay = 1000 * 60 * 60 * 24;
var midnight = new Date(new Date().getTime() + oneDay);
midnight.setSeconds(0); midnight.setMinutes(0);midnight.setHours(0);
// paranoia
while (midnight < new Date()) midnight = new Date(midnight.getTime() + oneDay);
setTimeout(func, midnight - new Date());
}
function runEveryNMinutesOnTheMthSecond(n, m, func) {
var firstDelaySec = m - (DebugSettings.now() || new Date()).getSeconds();
if (firstDelaySec <= 0) {
firstDelaySec += 60;
}
setTimeout(function() {
try {
func();
setInterval(function() {
func();
}, 1000 * 60 * n);
} catch (err) {
Logger.log("Error in repeated function.", err);
}
}, firstDelaySec * 1000);
}
function reloadRoom(room, callback) {
room.reload(function() {
GlobalEvents.trigger('roomUpdatedByServer', room);
callback && callback();
});
}
function beginReloadingRooms(thisRoom) {
var currIndex = 0;
function updateARoom() {
var otherRoom = EventManager.rooms[currIndex];
currIndex++;
currIndex %= EventManager.rooms.length;
if (otherRoom == thisRoom) { // skip it, it has its own cycle.
updateARoom();
} else {
reloadRoom(otherRoom);
}
}
runEveryNMinutesOnTheMthSecond(15, 20, updateARoom);
}
EventManager.init(function() {
var thisRoom = roomName ? EventManager.getRoom(roomName) : undefined;
if (roomName && !thisRoom) {
$('#errormsg')
.css('font-size','18px')
.text('You entered an invalid room name. The room could not be found.')
.show();
return;
}
//once all the "other" rooms are loaded, begin REloading them one at a time in a round robin to keep them up-to-date.
var afterAllRoomsLoaded = _.after(EventManager.rooms.length, function() { beginReloadingRooms(thisRoom); }),
loadOtherRooms = function(thisRoom) {
_.each(EventManager.rooms, function(room) {
thisRoom !== room && room.load(function() {
afterAllRoomsLoaded();
GlobalEvents.trigger('roomLoaded', room);
});
});
};
initUi(thisRoom);
if (thisRoom) {
thisRoom.load(function() { // if we have a "this" room, we want to load it first without other loads getting in the way (not sure they actually will...)
GlobalEvents.trigger('roomLoaded', thisRoom);
afterAllRoomsLoaded();
//begin reloading this room at regular intervals
runEveryNMinutesOnTheMthSecond(30, 40, function() { reloadRoom(thisRoom); });
loadOtherRooms(thisRoom);
});
} else {
loadOtherRooms();
}
//update UI when the minute ticks over.
runEveryNMinutesOnTheMthSecond(1, 1, function() {
GlobalEvents.trigger('minuteChanged');
});
});
GlobalEvents.bind('bookingAddedByUser', function(event, booking) {
EventManager.bookRoom(booking.room, booking.title, booking.time, booking.duration,
function success() {
booking.room.reload(function() {
GlobalEvents.trigger('roomUpdatedByServer', booking.room);
});
},
function failure() {
GlobalEvents.trigger('bookingFailure', booking);
}
);
});
// update MEAT from server everyday at midnight. gApps also seems to have some memory leaks. This lets us avoid bad consequences from that...
runAtMidnight(function() { window.location.reload(); });
})(); | JavaScript | 0.000001 | @@ -1934,13 +1934,67 @@
%09%09%09.
-show(
+removeClass('hidden');%0A%09%09%09$('#container').addClass('hidden'
);%0A%09
|
142c7d5144b2ef2fc230ddb9b1d4cae29048d1e5 | output ultrasonic reading to ros | examples/sensor-to-ros/index.js | examples/sensor-to-ros/index.js | const Board = require('firmata');
const Sonar = require('./lib/sonar');
const Motor = require('./lib/motor');
const pwait = require('./lib/util').pwait;
const PIN_SONAR = 8;
const PIN_SERVO = 3;
let STEP = 20;
const MIN = 0, MAX = 180;
let servoPos = MIN;
const sonarBoard = new Board('/dev/ttyACM0', err => {
if (err) {
throw new Error(err);
}
console.log('SONAR READY');
const sonar = new Sonar(sonarBoard, PIN_SONAR);
sonarBoard.servoConfig(PIN_SERVO, 660, 1300);
const servoTo = sonarBoard.servoWrite.bind(sonarBoard, PIN_SERVO);
servoTo(servoPos);
const nextPos = () => {
const tmp = servoPos + STEP;
if (tmp > MAX || tmp < MIN) {
// change servo direction
STEP *= -1;
}
return servoPos += STEP;
};
const scan = () => {
// execute 4 pings
return sonar.multiPing(1)
// select the reading with the smallest distance
.then(arr => arr.reduce((c, p) => p.value < c.value ? p : c, { value: Infinity }))
// add current servo position to the data object
.then(data => Object.assign({angle: servoPos}, data))
// send new data to web server
.then(data => {
console.log(`${data.value}(${data.index}) @ ${data.angle}°`);
})
// move to next position
.then(() => servoTo(nextPos()))
// wait 20ms for servo to move
.then(pwait.bind(null, 80))
// trigger next scan
.then(scan);
}
// start scanning
scan();
})
| JavaScript | 0.999999 | @@ -145,16 +145,105 @@
).pwait;
+%0Aconst rosnodejs = require('rosnodejs');%0A%0Aconst std_msgs = rosnodejs.require('std_msgs');
%0A%0Aconst
@@ -341,16 +341,195 @@
= MIN;%0A%0A
+rosnodejs.initNode('sensor_to_ros', %7Bmessages: %5B'std_msgs/Float32'%5D%7D)%0A.then( (nodeHandle) =%3E %7B%0A distance_publisher = nodeHandle.advertise('/distance', 'std_msgs/Float32');%0A
const so
@@ -574,16 +574,22 @@
rr =%3E %7B%0A
+
if (er
@@ -597,16 +597,20 @@
) %7B%0A
+
+
throw ne
@@ -625,18 +625,30 @@
err);%0A
-%7D%0A
+ %7D%0A
consol
@@ -669,16 +669,22 @@
EADY');%0A
+
const
@@ -725,16 +725,22 @@
SONAR);%0A
+
sonarB
@@ -779,16 +779,22 @@
1300);%0A
+
const
@@ -855,16 +855,22 @@
ERVO);%0A%0A
+
servoT
@@ -883,16 +883,22 @@
oPos);%0A%0A
+
const
@@ -911,24 +911,28 @@
s = () =%3E %7B%0A
+
const tm
@@ -952,16 +952,20 @@
+ STEP;%0A
+
if (
@@ -996,16 +996,18 @@
%7B%0A
+
+
// chang
@@ -1030,16 +1030,18 @@
n%0A
+
STEP *=
@@ -1044,26 +1044,34 @@
*= -1;%0A
+
-%7D%0A
+ %7D%0A
return s
@@ -1093,11 +1093,23 @@
;%0A
-%7D;%0A
+ %7D;%0A
co
@@ -1123,24 +1123,28 @@
n = () =%3E %7B%0A
+
// execu
@@ -1154,16 +1154,22 @@
4 pings%0A
+
retu
@@ -1190,16 +1190,24 @@
Ping(1)%0A
+
// s
@@ -1251,16 +1251,24 @@
istance%0A
+
.the
@@ -1346,16 +1346,24 @@
ity %7D))%0A
+
// a
@@ -1407,16 +1407,24 @@
object%0A
+
.the
@@ -1473,16 +1473,24 @@
data))%0A
+
// s
@@ -1516,16 +1516,24 @@
server%0A
+
.the
@@ -1540,24 +1540,34 @@
n(data =%3E %7B%0A
+
consol
@@ -1626,19 +1626,222 @@
%60);%0A
-%7D)%0A
+ // publish the distance to ros%0A msg = new std_msgs.msg.Float32();%0A msg.data = data.value;%0A distance_publisher.publish(msg);%0A %7D)%0A
// m
@@ -1857,24 +1857,30 @@
xt position%0A
+
.then(()
@@ -1903,16 +1903,24 @@
Pos()))%0A
+
// w
@@ -1946,16 +1946,24 @@
to move%0A
+
.the
@@ -1986,16 +1986,24 @@
l, 80))%0A
+
// t
@@ -2019,16 +2019,24 @@
xt scan%0A
+
.the
@@ -2046,18 +2046,30 @@
can);%0A
-%7D%0A
+ %7D%0A
// sta
@@ -2080,16 +2080,22 @@
canning%0A
+
scan()
@@ -2096,11 +2096,20 @@
scan();%0A
-%7D)
+ %7D)%0A%7D);%0A
%0A
|
87374dd5e6e48b3a4a96bac9e845664ce0c330c7 | Add saga for generating me data | app/containers/App/sagas.js | app/containers/App/sagas.js | import { takeLatest } from 'redux-saga/effects';
import {
ME_FROM_TOKEN,
} from './constants';
function* getMeFromToken() {
}
function* meData() {
yield takeLatest(ME_FROM_TOKEN, getMeFromToken);
}
export default [
meData,
];
| JavaScript | 0.000238 | @@ -1,16 +1,27 @@
import %7B
+ call, put,
takeLat
@@ -107,37 +107,339 @@
';%0A%0A
-function* getMeFromToken() %7B%0A
+import %7B%0A meRequestFailed,%0A meRequestSuccess,%0A%7D from './actions';%0A%0Afunction* getMeFromToken(action) %7B%0A // TODO: placeholder for request%0A const request = %7B%7D;%0A try %7B%0A const me = yield call(request.fetch, action.username);%0A yield put(meRequestSuccess(me));%0A %7D catch (err) %7B%0A yield put(meRequestFailed(err.message));%0A %7D
%0A%7D%0A%0A
|
e1a9435e474981151bf53668835da220d795a9ef | Add a cache layer to avoid hitting the HDD as often | plugins/repcastnas.js | plugins/repcastnas.js | const LifeforcePlugin = require("../utils/LifeforcePlugin.js");
const exampleRepcast = require("../static/example_repcast.json");
const restify = require("restify");
const fs = require("fs");
const querystring = require("querystring");
const mimetype = require("mime-types");
const path = require("path");
let pathfix = "";
let pathprefix = "";
let authkey = null;
class RepCastNAS extends LifeforcePlugin {
constructor(restifyserver, logger, name) {
super(restifyserver, logger, name);
this.apiMap = [
{
path: "/repcast/nas/getfiles/:filepath",
type: "get",
handler: handleRepcastDirGet
},
{
path: "/repcast/nas/getfiles",
type: "get",
handler: handleRepcastDirGet
},
{
path: "/repcast/spaces/getfiles",
type: "get",
handler: handleRepcastDirGet
},
{
path: "/repcast/spaces/getfiles/:filepath",
type: "get",
handler: handleRepcastDirGet
}
];
// Grab some specific values from the config
pathfix = this.config.mediamount;
pathprefix = this.config.mediaprefix;
authkey = this.config.authkey.REPCAST_APP_KEY;
restifyserver.use((req, res, next) => {
if (req.url.indexOf("/repcast/filesrv/") === 0) {
if (req.url.indexOf("auth=" + authkey) !== -1) {
return next();
} else {
this.log.info("Got a request for file without correct auth! How did someone get this path?");
res.send(401);
}
}
return next();
});
restifyserver.get("/repcast/filesrv/*", restify.plugins.serveStaticFiles(this.config.mediamount))
}
}
function handleRepcastDirGet(req, res, next) {
const header = req.headers["repka-repcast-token"];
if (!header) {
this.log.warn("Repcast getfiles request without auth, sending back example file list");
res.send(200, exampleRepcast);
return;
} else {
if (header !== authkey) {
res.send(200, exampleRepcast);
return;
}
}
let getpath = "";
if (req.params.filepath) {
getpath = Buffer.from(req.params.filepath, 'base64').toString();
getpath = getpath.replace(pathfix, "");
}
let filepath = pathfix + getpath;
this.log.info("Requested directory listing for " + filepath);
try {
let result = dirlist(filepath);
res.send(200, { error: false, status: "live", count: result.length, info: result });
} catch (err) {
res.send(500, { error: true, status: "error", count: 0, info: [], details: "Error while getting file list" });
}
return next();
}
const walk = (dir) => {
let results = []
let list = fs.readdirSync(dir)
list.forEach((file) => {
file = dir + '/' + file
let stat = fs.statSync(file)
if (stat && stat.isDirectory()) results = results.concat(walk(file))
else results.push(file)
});
return results
}
function dirlist(filepath) {
// get the list of files in this directory:
let files = fs.readdirSync(filepath);
files.sort(function (a, b) {
return fs.statSync(filepath + b).mtime.getTime() - fs.statSync(filepath + a).mtime.getTime();
});
let filelist = [];
files.forEach((file) => {
let fixpath = filepath.replace(pathfix, "");
let jsonstruct = {
date: "",
name: file,
type: "file"
};
let stats = fs.statSync(filepath + file);
// If something is a directory do some extra operations, and include it
if (stats.isDirectory()) {
jsonstruct.type = "dir";
jsonstruct.key = Buffer.from(fixpath + file + "/").toString('base64');
} else {
let ext = path.extname(fixpath + file).replace(".", "");
let fullpath = pathprefix + querystring.escape(fixpath + file) + "?auth=" + authkey;
jsonstruct.path = fullpath;
jsonstruct.size = stats.size;
jsonstruct.original = file;
jsonstruct.mimetype = mimetype.lookup(ext);
jsonstruct.filetype = ext;
}
filelist.push(jsonstruct);
});
return filelist;
}
module.exports = RepCastNAS; | JavaScript | 0 | @@ -360,16 +360,46 @@
null;%0A%0A
+let ResultCache = new Map();%0A%0A
class Re
@@ -2574,16 +2574,120 @@
tpath;%0A%0A
+ // Check if we have the result of this already in cache...%0A if (ResultCache.has(filepath)) %7B%0A
this
@@ -2745,31 +2745,321 @@
path
+ + %22, getting from cache%22
);%0A
+
-try %7B%0A le
+ let result = ResultCache.get(filepath);%0A res.send(200, %7B error: false, status: %22cache%22, count: result.length, info: result %7D);%0A return next();%0A %7D%0A%0A%0A this.log.info(%22Requested directory listing for %22 + filepath + %22, getting live data%22);%0A try %7B%0A cons
t re
@@ -3173,24 +3173,67 @@
result %7D);%0A
+ ResultCache.set(filepath, result);%0A
%7D catch
|
bd4aa5aab6fc6fee7ea8126ca6c0faa610dceb65 | Remove reference to initialize from comments | src/row.js | src/row.js | /*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT license.
*/
/**
Row is a simple container view that takes a model instance and a list of
column metadata describing how each of the model's attribute is to be
rendered, and apply the appropriate cell to each attribute.
@class Backgrid.Row
@extends Backbone.View
*/
var Row = Backgrid.Row = Backbone.View.extend({
/** @property */
tagName: "tr",
/**
@param {Object} options
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
@param {Backbone.Model} options.model The model instance to render.
@throws {TypeError} If options.columns or options.model is undefined.
*/
constructor: function (options) {
Row.__super__.constructor.apply(this, arguments);
var columns = this.columns = options.columns;
if (!(columns instanceof Backbone.Collection)) {
columns = this.columns = new Columns(columns);
}
var cells = this.cells = [];
for (var i = 0; i < columns.length; i++) {
cells.push(this.makeCell(columns.at(i), options));
}
this.listenTo(columns, "add", function (column, columns) {
var i = columns.indexOf(column);
var cell = this.makeCell(column, options);
cells.splice(i, 0, cell);
var $el = this.$el;
if (i === 0) {
$el.prepend(cell.render().$el);
}
else if (i === columns.length - 1) {
$el.append(cell.render().$el);
}
else {
$el.children().eq(i).before(cell.render().$el);
}
});
this.listenTo(columns, "remove", function (column, columns, opts) {
cells[opts.index].remove();
cells.splice(opts.index, 1);
});
},
/**
Factory method for making a cell. Used by #initialize internally. Override
this to provide an appropriate cell instance for a custom Row subclass.
@protected
@param {Backgrid.Column} column
@param {Object} options The options passed to #initialize.
@return {Backgrid.Cell}
*/
makeCell: function (column) {
return new (column.get("cell"))({
column: column,
model: this.model
});
},
/**
Renders a row of cells for this row's model.
*/
render: function () {
this.$el.empty();
var fragment = document.createDocumentFragment();
for (var i = 0; i < this.cells.length; i++) {
fragment.appendChild(this.cells[i].render().el);
}
this.el.appendChild(fragment);
this.delegateEvents();
return this;
},
/**
Clean up this row and its cells.
@chainable
*/
remove: function () {
for (var i = 0; i < this.cells.length; i++) {
var cell = this.cells[i];
cell.remove.apply(cell, arguments);
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/**
EmptyRow is a simple container view that takes a list of column and render a
row with a single column.
@class Backgrid.EmptyRow
@extends Backbone.View
*/
var EmptyRow = Backgrid.EmptyRow = Backbone.View.extend({
/** @property */
tagName: "tr",
/** @property */
emptyText: null,
/**
@param {Object} options
@param {string} options.emptyText
@param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
*/
constructor: function (options) {
EmptyRow.__super__.constructor.apply(this, arguments);
this.emptyText = options.emptyText;
this.columns = options.columns;
},
/**
Renders an empty row.
*/
render: function () {
this.$el.empty();
var td = document.createElement("td");
td.setAttribute("colspan", this.columns.length);
td.textContent = this.emptyText;
this.el.setAttribute("class", "empty");
this.el.appendChild(td);
return this;
}
});
| JavaScript | 0 | @@ -1869,27 +1869,36 @@
Used by
-#initialize
+the constructor%0A
interna
@@ -1910,21 +1910,16 @@
Override
-%0A
this to
@@ -1961,16 +1961,21 @@
ce for a
+%0A
custom
@@ -2098,19 +2098,23 @@
to
-#initialize
+the constructor
.%0A%0A
|
405b4d741a5b02d8166b6b5af605a59bfcde040a | Add support for workspaceFolder variables (#20) | extension.js | extension.js | const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
const diffMatchPatch = require('diff-match-patch');
class AstyleFormatter {
constructor() {
this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
}
getFilesizeInBytes(filename) {
const stats = fs.statSync(filename)
const fileSizeInBytes = stats.size
return fileSizeInBytes
}
// interface required by vscode.DocumentFormattingEditProvider
provideDocumentFormattingEdits(document, options, token) {
return new Promise((resolve, reject) => {
let astyleBinPath = vscode.workspace.getConfiguration('astyle')['executable'] || 'astyle';
let astyleRcPath = vscode.workspace.getConfiguration('astyle')['astylerc'];
const astyleMaxBufferMultiplier = vscode.workspace.getConfiguration('astyle')['max_buffer_multipler'];
let args = vscode.workspace.getConfiguration('astyle')['cmd_options'] || [];
if (astyleRcPath) {
args.push("--options=" + astyleRcPath);
}
args.forEach((item, index) => {
args[index] = item.replace(/\${workspaceRoot}/g, vscode.workspace.rootPath);
});
astyleBinPath = astyleBinPath.replace(/\${workspaceRoot}/g, vscode.workspace.rootPath);
const defaultMaxBufferSize = 200 * 1024;
const maxBufferMultiplierSize = this.getFilesizeInBytes(document.fileName) * astyleMaxBufferMultiplier;
// Assume that the formatting/expansion of the document could double it's size
// Make sure the minimum size is still the default for execFile::maxBuffer
const maxBufferSize = Math.max(defaultMaxBufferSize, maxBufferMultiplierSize);
let astyle = childProcess.execFile(astyleBinPath, args, {maxBuffer: maxBufferSize}, (err, stdout, stderr) => {
if (err && err.code == 'ENOENT') {
vscode.window.showErrorMessage('Can\'t find astyle. (' + astyleBinPath + ')');
reject(null);
return;
}
if (err) {
vscode.window.showErrorMessage('Failed to launch astyle. (reason: "' + stderr.split(/\r\n|\r|\n/g).join(',') + ' ' + err + '")');
reject(null);
return;
}
let editors = this.generateTextEditors(document, stdout);
this.updateStatusBar(editors);
resolve(editors);
});
if (astyle.pid) {
astyle.stdin.write(document.getText());
astyle.stdin.end();
}
});
}
generateTextEditors(document, formattedText) {
let dmp = new diffMatchPatch.diff_match_patch();
let diffs = dmp.diff_main(document.getText(), formattedText.replace(/\r\n|\r|\n/g, document.eol == 2 ? '\r\n' : '\n'));
let editors = [];
let line = 0, character = 0;
diffs.forEach((diff) => {
let op = diff[0];
let text = diff[1];
let start = new vscode.Position(line, character);
let lines = text.split(/\r\n|\r|\n/g);
line += lines.length - 1;
if (lines.length > 1) {
character = lines[lines.length - 1].length;
} else if (lines.length == 1) {
character += lines[0].length;
}
switch (op) {
case diffMatchPatch.DIFF_INSERT:
editors.push(vscode.TextEdit.insert(start, text));
// this new part should not affect counting of original document
line = start.line;
character = start.character;
break;
case diffMatchPatch.DIFF_DELETE:
let end = new vscode.Position(line, character);
editors.push(vscode.TextEdit.delete(new vscode.Range(start, end)));
break;
case diffMatchPatch.DIFF_EQUAL:
break;
}
});
return editors;
}
updateStatusBar(editors) {
if (editors.length == 0) {
this.statusBar.text = 'No changes';
} else {
this.statusBar.text = '$(pencil) Formatted';
}
this.statusBar.show();
setTimeout(() => {
this.statusBar.hide();
}, 500);
}
dispose() {
this.statusBar.dispose();
}
};
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
let formatter = new AstyleFormatter();
let additionalLanguages = vscode.workspace.getConfiguration('astyle')['additional_languages'] || [];
["c", "cpp", "objective-c", "csharp", "java"].concat(additionalLanguages).forEach(function (language) {
let config = vscode.workspace.getConfiguration('astyle')[language];
if (config && !config.enable) {
return;
}
let disposable = vscode.languages.registerDocumentFormattingEditProvider(language, formatter);
context.subscriptions.push(disposable);
});
context.subscriptions.push(formatter);
}
exports.activate = activate;
| JavaScript | 0.000001 | @@ -1245,32 +1245,33 @@
= item.replace(/
+(
%5C$%7BworkspaceRoot
@@ -1263,32 +1263,55 @@
$%7BworkspaceRoot%7D
+)%7C(%5C$%7BworkspaceFolder%7D)
/g, vscode.works
@@ -1394,16 +1394,17 @@
eplace(/
+(
%5C$%7Bworks
@@ -1412,16 +1412,39 @@
aceRoot%7D
+)%7C(%5C$%7BworkspaceFolder%7D)
/g, vsco
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.