commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
511814ce75f471f5a68350312060f5506b2c3dd0 | src/lib/graphqlErrorHandler.js | src/lib/graphqlErrorHandler.js | import raven from "raven"
import { assign } from "lodash"
const blacklistHttpStatuses = [401, 403, 404]
export const shouldLogError = originalError => {
if (originalError && originalError.statusCode) {
return (
originalError.statusCode < 500 &&
!blacklistHttpStatuses.includes(originalError.statusCode)
)
}
return true
}
export default function graphqlErrorHandler(
req,
{ isProduction, enableSentry }
) {
return error => {
if (enableSentry) {
if (shouldLogError(error.originalError)) {
raven.captureException(
error,
assign(
{},
{
tags: { graphql: "exec_error" },
extra: {
source: error.source && error.source.body,
positions: error.positions,
path: error.path,
},
},
raven.parsers.parseRequest(req)
)
)
}
}
return {
message: error.message,
locations: error.locations,
stack: isProduction ? null : error.stack,
}
}
}
| import raven from "raven"
import { assign } from "lodash"
const blacklistHttpStatuses = [401, 403, 404]
export const shouldLogError = originalError => {
if (originalError && originalError.statusCode) {
return (
originalError.statusCode < 500 &&
!blacklistHttpStatuses.includes(originalError.statusCode)
)
}
return true
}
export default function graphqlErrorHandler(
req,
{ isProduction, enableSentry }
) {
return error => {
if (enableSentry) {
if (shouldLogError(error.originalError)) {
raven.captureException(
error,
assign(
{},
{
tags: { graphql: "exec_error" },
extra: {
source: error.source && error.source.body,
positions: error.positions,
path: error.path,
},
},
raven.parsers.parseRequest(req)
)
)
}
}
return {
message: error.message,
locations: error.locations,
path: isProduction ? null : error.path,
stack: isProduction ? null : error.stack,
}
}
}
| Include resolver path to error report in dev mode. | [error] Include resolver path to error report in dev mode.
| JavaScript | mit | artsy/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics | ---
+++
@@ -40,6 +40,7 @@
return {
message: error.message,
locations: error.locations,
+ path: isProduction ? null : error.path,
stack: isProduction ? null : error.stack,
}
} |
5884798a3f122edf001a271a13d8b3ec62aa61d2 | src/server/api/posts.js | src/server/api/posts.js | import koaRouter from 'koa-router';
import fs from 'fs';
import path from 'path'
import readline from 'readline';
const router = koaRouter();
function lineReaderThunk(lineReader) {
return function(done) {
lineReader.on('line', function (line) {
done(null, line);
});
}
}
router.get('/posts', function*(next) {
const postsBaseDir = path.resolve(__dirname, '../../../posts');
const posts = fs.readdirSync(postsBaseDir);
var postData = {};
for (let i = 0, len = posts.length; i < len; i++) {
let postFilename = posts[i];
const postFilePath = path.resolve(postsBaseDir, postFilename);
var lineReader = readline.createInterface({
input: fs.createReadStream(postFilePath)
});
postData[postFilename] = [];
var line = yield lineReaderThunk(lineReader);
postData[postFilename].push(line);
}
this.body = postData;
});
export default router.middleware(); | import koaRouter from 'koa-router';
import fs from 'fs';
import path from 'path'
import readline from 'readline';
const router = koaRouter();
function readPostFile(postFilePath) {
return function(done) {
var lines = [];
var lineReader = readline.createInterface({
input: fs.createReadStream(postFilePath)
});
lineReader.on('line', function(line){
lines.push(line);
});
lineReader.on('close', function(){
done(null, lines);
});
}
}
router.get('/posts', function*(next) {
const postsBaseDir = path.resolve(__dirname, '../../../posts');
const posts = fs.readdirSync(postsBaseDir);
var postData = {};
for (let i = 0, len = posts.length; i < len; i++) {
let postFilename = posts[i];
const postFilePath = path.resolve(postsBaseDir, postFilename);
postData[postFilename] = yield readPostFile(postFilePath);
}
this.body = postData;
});
export default router.middleware(); | Read all the lines of the md files and return them in the response | Read all the lines of the md files and return them in the response
| JavaScript | mit | alexchiri/minimalistic-blog,alexchiri/minimalistic-blog,alexchiri/minimalistic-blog | ---
+++
@@ -5,10 +5,20 @@
const router = koaRouter();
-function lineReaderThunk(lineReader) {
+function readPostFile(postFilePath) {
return function(done) {
- lineReader.on('line', function (line) {
- done(null, line);
+ var lines = [];
+
+ var lineReader = readline.createInterface({
+ input: fs.createReadStream(postFilePath)
+ });
+
+ lineReader.on('line', function(line){
+ lines.push(line);
+ });
+
+ lineReader.on('close', function(){
+ done(null, lines);
});
}
}
@@ -16,20 +26,13 @@
router.get('/posts', function*(next) {
const postsBaseDir = path.resolve(__dirname, '../../../posts');
const posts = fs.readdirSync(postsBaseDir);
+ var postData = {};
- var postData = {};
for (let i = 0, len = posts.length; i < len; i++) {
let postFilename = posts[i];
const postFilePath = path.resolve(postsBaseDir, postFilename);
- var lineReader = readline.createInterface({
- input: fs.createReadStream(postFilePath)
- });
-
- postData[postFilename] = [];
-
- var line = yield lineReaderThunk(lineReader);
- postData[postFilename].push(line);
+ postData[postFilename] = yield readPostFile(postFilePath);
}
this.body = postData; |
6e9572f9dc1ffc5820d3db766a7e54bb8172f72e | index.js | index.js | const ZoomdataSDK = require('zoomdata-client/distribute/sdk/zoomdata-client.node');
async function run() {
const application = {
secure: true,
host: 'developer.zoomdata.com',
port: 443,
path: '/zoomdata-2.6'
};
const credentials = {
key: 'KVKWiD8kUl'
};
const client = await ZoomdataSDK.createClient({ application, credentials });
console.log('Client ready');
const queryConfig = {
filters: [],
groups: [{
name: 'position',
limit: 10,
sort: { dir: 'asc', name: 'position' }
}],
metrics: [
{ name: 'satisfaction', func: 'sum' }
]
};
try {
const data = await fetchData(client, 'Impala', queryConfig);
console.log('Received data:', data);
} finally {
client.close();
}
}
async function fetchData(client, name, queryConfig) {
const query = await client.createQuery({ name }, queryConfig);
console.log('Query created');
return new Promise((resolve, reject) => {
console.log('Running query...');
client.runQuery(query, resolve, reject);
});
}
run().catch(console.error);
| const ZoomdataSDK = require('zoomdata-client/distribute/sdk/zoomdata-client.node');
async function run() {
const application = {
secure: true,
host: 'developer.zoomdata.com',
port: 443,
path: '/zoomdata-2.6'
};
const credentials = {
key: 'KVKWiD8kUl'
};
const client = await ZoomdataSDK.createClient({ application, credentials });
console.log('Client ready');
const queryConfig = {
filters: [],
groups: [{
name: 'gender',
limit: 10,
sort: { dir: 'asc', name: 'gender' }
}],
metrics: [
{ name: 'satisfaction', func: 'sum' }
]
};
try {
const data = await fetchData(client, 'My IMPALA Source', queryConfig);
console.log('Received data:', data);
} finally {
client.close();
}
}
async function fetchData(client, name, queryConfig) {
const query = await client.createQuery({ name }, queryConfig);
console.log('Query created');
return new Promise((resolve, reject) => {
console.log('Running query...');
client.runQuery(query, resolve, reject);
});
}
run().catch(console.error);
| Update query configuration and source name | Update query configuration and source name
| JavaScript | mit | artembykov/zoomdata-sdk-node | ---
+++
@@ -7,7 +7,7 @@
port: 443,
path: '/zoomdata-2.6'
};
-
+
const credentials = {
key: 'KVKWiD8kUl'
};
@@ -15,13 +15,13 @@
const client = await ZoomdataSDK.createClient({ application, credentials });
console.log('Client ready');
-
+
const queryConfig = {
filters: [],
groups: [{
- name: 'position',
+ name: 'gender',
limit: 10,
- sort: { dir: 'asc', name: 'position' }
+ sort: { dir: 'asc', name: 'gender' }
}],
metrics: [
{ name: 'satisfaction', func: 'sum' }
@@ -29,7 +29,7 @@
};
try {
- const data = await fetchData(client, 'Impala', queryConfig);
+ const data = await fetchData(client, 'My IMPALA Source', queryConfig);
console.log('Received data:', data);
} finally {
client.close(); |
a6f5ee1610f0c4a83d6ef3ddea3bf7896c52412f | index.js | index.js | const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('./build'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, './build', 'index.html'));
});
app.get('/infrastucture', function(req, res) {
res.send(200, {
regions : [
{ name : "east-1",
environments : [
{
status : 'green',
instanceCount : 12,
trafficWeight: 0.3
}
]
}
]
})
});
app.get('/load', function(req, res) {
res.send(200, {
regions : [
{ name : "east-1",
environments : [
{
errRate : 0.1,
replicationLag : 0.7
}
]
}
]
})
});
app.listen(9000); | const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('./build'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, './build', 'index.html'));
});
app.get('/infrastructure', function(req, res) {
res.status(200).send({
regions : [
{ name : "east-1",
environments : [
{
status : 'green',
instanceCount : 12,
trafficWeight: 0.3
}
]
}
]
})
});
app.get('/load', function(req, res) {
res.status(200).send({
regions : [
{ name : "east-1",
environments : [
{
errRate : 0.1,
replicationLag : 0.7
}
]
}
]
})
});
app.listen(9000); | Fix infrastructure spelling and clean up deprecated code | Fix infrastructure spelling and clean up deprecated code
| JavaScript | mit | bombbomb/Hydra,bombbomb/Hydra | ---
+++
@@ -8,8 +8,8 @@
res.sendFile(path.join(__dirname, './build', 'index.html'));
});
-app.get('/infrastucture', function(req, res) {
- res.send(200, {
+app.get('/infrastructure', function(req, res) {
+ res.status(200).send({
regions : [
{ name : "east-1",
environments : [
@@ -25,7 +25,7 @@
});
app.get('/load', function(req, res) {
- res.send(200, {
+ res.status(200).send({
regions : [
{ name : "east-1",
environments : [ |
991a35065ce79541b4ee311f9d7b5cfd40f031c5 | index.js | index.js | module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:ava/recommended',
],
plugins: [
'import',
'ava',
],
rules: {
indent: ['error', 4, {
SwitchCase: 1,
MemberExpression: 1,
VariableDeclarator: 1,
outerIIFEBody: 1,
FunctionDeclaration: {
parameters: 1,
body: 1,
},
FunctionExpression: {
parameters: 1,
body: 1,
},
}],
'valid-jsdoc': 'error',
strict: 'error',
'no-sync': 'error',
'no-inline-comments': 'error',
'no-use-before-define': ['error', 'nofunc'],
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'max-len': ['error', 150, 4, {
ignoreUrls: true,
ignoreComments: false,
ignoreRegExpLiterals: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
}],
},
};
| module.exports = {
parser: 'babel-eslint',
extends: [
'airbnb',
'plugin:ava/recommended',
],
plugins: [
'import',
'ava',
],
rules: {
indent: ['error', 4, {
SwitchCase: 1,
MemberExpression: 1,
VariableDeclarator: 1,
outerIIFEBody: 1,
FunctionDeclaration: {
parameters: 1,
body: 1,
},
FunctionExpression: {
parameters: 1,
body: 1,
},
}],
'valid-jsdoc': 'error',
strict: 'error',
'no-sync': 'error',
'no-inline-comments': 'error',
'no-use-before-define': ['error', 'nofunc'],
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'max-len': ['error', 150, 4, {
ignoreUrls: true,
ignoreComments: false,
ignoreRegExpLiterals: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
}],
'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }],
},
};
| Allow .js extension for JSX files | Allow .js extension for JSX files
| JavaScript | mit | brummelte/eslint-config | ---
+++
@@ -36,5 +36,6 @@
ignoreStrings: true,
ignoreTemplateLiterals: true,
}],
+ 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }],
},
}; |
5c54eabf0fe90b35f60adaf9a661ce85616e56e6 | index.js | index.js | var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir/ingredients/commands/Notification');
elixir.extend('react', function (src, options) {
var config = this;
options = _.extend({
debug: ! config.production,
srcDir: config.assetsDir + 'js',
output: config.jsOutput
}, options);
src = "./" + utilities.buildGulpSrc(src, options.srcDir);
gulp.task('react', function () {
var onError = function(e) {
new notification().error(e, 'React Compilation Failed!');
this.emit('end');
};
return gulp.src(src)
.pipe(react(options)).on('error', onError)
.pipe(gulpIf(! options.debug, uglify()))
.pipe(gulp.dest(options.output))
.pipe(new notification().message('React Compiled!'));
});
this.registerWatcher('react', options.srcDir + '/**/*.+(js|jsx)');
return this.queueTask('react');
});
| var gulp = require('gulp'),
react = require('gulp-react'),
gulpIf = require('gulp-if'),
uglify = require('gulp-uglify'),
_ = require('underscore'),
elixir = require('laravel-elixir'),
utilities = require('laravel-elixir/ingredients/commands/Utilities'),
notification = require('laravel-elixir/ingredients/commands/Notification');
elixir.extend('react', function (src, options) {
var config = this;
options = _.extend({
debug: ! config.production,
srcDir: config.assetsDir + 'js',
output: config.jsOutput
}, options);
src = "./" + utilities.buildGulpSrc(src, options.srcDir, "");
gulp.task('react', function () {
var onError = function(e) {
new notification().error(e, 'React Compilation Failed!');
this.emit('end');
};
return gulp.src(src)
.pipe(react(options)).on('error', onError)
.pipe(gulpIf(! options.debug, uglify()))
.pipe(gulp.dest(options.output))
.pipe(new notification().message('React Compiled!'));
});
this.registerWatcher('react', options.srcDir + '/**/*.+(js|jsx)');
return this.queueTask('react');
});
| Fix filepath to source directory when srcDir is specified and the first argument is blank | Fix filepath to source directory when srcDir is specified and the first argument is blank
| JavaScript | mit | joecohens/laravel-elixir-react | ---
+++
@@ -16,7 +16,7 @@
output: config.jsOutput
}, options);
- src = "./" + utilities.buildGulpSrc(src, options.srcDir);
+ src = "./" + utilities.buildGulpSrc(src, options.srcDir, "");
gulp.task('react', function () {
var onError = function(e) { |
26d6b0e3da91d1d77a6b085adfd71bc93fb45c75 | index.js | index.js | var nunjucks = require("nunjucks");
module.exports = function(env, callback) {
var NunjucksTemplate = function(template) {
this.template = template;
};
NunjucksTemplate.prototype.render = function render(locals, callback) {
try {
callback(null, new Buffer(this.template.render(locals)));
} catch (error) {
callback(error);
}
};
NunjucksTemplate.fromFile = function fromFile(filepath, callback) {
var nenv = new nunjucks.Environment(new nunjucks.FileSystemLoader(env.templatesPath));
callback(null, new NunjucksTemplate(nenv.getTemplate(filepath.relative)));
};
env.registerTemplatePlugin("**/*.*(html)", NunjucksTemplate);
callback();
};
| var nunjucks = require("nunjucks");
module.exports = function(env, callback) {
var NunjucksTemplate = function(template) {
this.template = template;
};
NunjucksTemplate.prototype.render = function render(locals, callback) {
try {
callback(null, new Buffer(this.template.render(locals)));
} catch (error) {
callback(error);
}
};
NunjucksTemplate.fromFile = function fromFile(filepath, callback) {
var nenv = new nunjucks.Environment(new nunjucks.FileSystemLoader(env.templatesPath));
callback(null, new NunjucksTemplate(nenv.getTemplate(filepath.relative)));
};
env.registerTemplatePlugin("**/*.*(html|nunjucks)", NunjucksTemplate);
callback();
};
| Add support for templates named *.nunjucks | Add support for templates named *.nunjucks
Fixes #8.
| JavaScript | bsd-2-clause | devoptix/wintersmith-nunjucka,jnordberg/wintersmith-nunjucks,jbuck/wintersmith-nunjucks | ---
+++
@@ -18,7 +18,7 @@
callback(null, new NunjucksTemplate(nenv.getTemplate(filepath.relative)));
};
- env.registerTemplatePlugin("**/*.*(html)", NunjucksTemplate);
+ env.registerTemplatePlugin("**/*.*(html|nunjucks)", NunjucksTemplate);
callback();
}; |
1f8d043822583710de9fae9d655a56f36c66dec3 | index.js | index.js | /* globals module */
'use strict'
module.exports = {
name: 'ember-frost-bunsen',
included: function (app) {
this._super.included(app)
app.import('bower_components/z-schema/dist/ZSchema-browser.js')
},
init: function (app) {
this.options = this.options || {}
this.options.babel = this.options.babel || {}
this.options.babel.optional = this.options.babel.optional || []
if (this.options.babel.optional.indexOf('es7.decorators') === -1) {
this.options.babel.optional.push('es7.decorators')
}
this._super.init && this._super.init.apply(this, arguments)
}
}
| /* globals module */
'use strict'
module.exports = {
name: 'ember-frost-bunsen',
included: function (app) {
this._super.included(app)
this.app.import('bower_components/z-schema/dist/ZSchema-browser.js')
},
init: function (app) {
this.options = this.options || {}
this.options.babel = this.options.babel || {}
this.options.babel.optional = this.options.babel.optional || []
if (this.options.babel.optional.indexOf('es7.decorators') === -1) {
this.options.babel.optional.push('es7.decorators')
}
this._super.init && this._super.init.apply(this, arguments)
}
}
| Revert "incorrect call to this.app.import(). causing issues in consuming app" | Revert "incorrect call to this.app.import(). causing issues in consuming app"
This reverts commit d41144c032dd2bebe05435251b583ed2631da025.
| JavaScript | mit | sophypal/ember-frost-bunsen,sandersky/ember-frost-bunsen,sophypal/ember-frost-bunsen,sandersky/ember-frost-bunsen,ciena-frost/ember-frost-bunsen,ciena-frost/ember-frost-bunsen,sandersky/ember-frost-bunsen,ciena-frost/ember-frost-bunsen,sophypal/ember-frost-bunsen | ---
+++
@@ -7,7 +7,7 @@
included: function (app) {
this._super.included(app)
- app.import('bower_components/z-schema/dist/ZSchema-browser.js')
+ this.app.import('bower_components/z-schema/dist/ZSchema-browser.js')
},
init: function (app) { |
c2148930b2a73d74754917485f0e0318117f3019 | index.js | index.js | #!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var colors = require('colors');
var shell = require('./lib/shell');
var subtree = require('./lib/subtree');
var cwd = process.cwd();
var gitroot = path.join(cwd, ".git")
try {
fs.readdirSync(gitroot);
} catch (error) {
console.error('Run this script from the root of the repository.'.red);
process.exit(1);
}
subtree.run(process.argv.slice(2), function(err, result) {
if (err) {
console.error(('ERROR: ' + err).red);
process.exit(1);
}
});
| #!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var colors = require('colors');
var shell = require('./lib/shell');
var subtree = require('./lib/subtree');
var args = process.argv.slice(2);
if (args.length > 0) {
// Check if it's project root
try {
var gitroot = path.join(process.cwd(), ".git")
fs.readdirSync(gitroot);
} catch (error) {
console.error('Run this script from the root of the repository.'.red);
process.exit(1);
}
// Check if config file exists
try {
var subtrees = path.join(process.cwd(), "subtrees.json")
fs.readFileSync(subtrees);
} catch (error) {
console.error('Missing subtrees.json configuration file'.red);
process.exit(1);
}
subtree.run(args, function(err, result) {
if (err) {
console.error(('ERROR: ' + err).red);
process.exit(1);
}
});
} else {
console.log('usage: git-subtree <command>\n');
console.log('Commands:');
console.log('init\tInitialize project subtrees');
console.log('add\tCreate remote, fetch and add subtree folder');
console.log('pull\tPull changes from subtree');
console.log('push\tPush changes to subtree');
console.log('commit\tCommit subtree folder changes');
}
| Print help if no args, and add check for subtrees.json file presence. | Print help if no args, and add check for subtrees.json file presence.
| JavaScript | mit | plitex/git-subtree | ---
+++
@@ -6,19 +6,40 @@
var shell = require('./lib/shell');
var subtree = require('./lib/subtree');
-var cwd = process.cwd();
-var gitroot = path.join(cwd, ".git")
+var args = process.argv.slice(2);
-try {
- fs.readdirSync(gitroot);
-} catch (error) {
- console.error('Run this script from the root of the repository.'.red);
- process.exit(1);
-}
+if (args.length > 0) {
-subtree.run(process.argv.slice(2), function(err, result) {
- if (err) {
- console.error(('ERROR: ' + err).red);
+ // Check if it's project root
+ try {
+ var gitroot = path.join(process.cwd(), ".git")
+ fs.readdirSync(gitroot);
+ } catch (error) {
+ console.error('Run this script from the root of the repository.'.red);
process.exit(1);
}
-});
+
+ // Check if config file exists
+ try {
+ var subtrees = path.join(process.cwd(), "subtrees.json")
+ fs.readFileSync(subtrees);
+ } catch (error) {
+ console.error('Missing subtrees.json configuration file'.red);
+ process.exit(1);
+ }
+
+ subtree.run(args, function(err, result) {
+ if (err) {
+ console.error(('ERROR: ' + err).red);
+ process.exit(1);
+ }
+ });
+} else {
+ console.log('usage: git-subtree <command>\n');
+ console.log('Commands:');
+ console.log('init\tInitialize project subtrees');
+ console.log('add\tCreate remote, fetch and add subtree folder');
+ console.log('pull\tPull changes from subtree');
+ console.log('push\tPush changes to subtree');
+ console.log('commit\tCommit subtree folder changes');
+} |
8af039a94e7dc2fe5c8689f2ee14891a8e922f97 | karma.conf.js | karma.conf.js | 'use strict';
module.exports = function(config) {
config.set({
autoWatch: true,
browsers: [
'PhantomJS'
],
colors: true,
coverageReporter: {
dir: 'coverage',
instrumenterOptions: {
istanbul: {
noCompact: true
}
},
reporters: [{
type: 'html',
subdir: 'report-html'
}, {
type: 'lcov',
subdir: 'report-lcov'
}, {
type: 'cobertura',
subdir: '.',
file: 'cobertura.txt'
}, {
type: 'lcovonly',
subdir: '.',
file: 'report-lcovonly.txt'
}, {
type: 'teamcity',
subdir: '.',
file: 'teamcity.txt'
}, {
type: 'text',
subdir: '.',
file: 'text.txt'
}, {
type: 'text-summary',
subdir: '.',
file: 'text-summary.txt'
}]
},
files: [
'dist/jasmine-matchers.js',
'dist/jasmine-matchers.spec.js'
],
frameworks: [
'jasmine'
],
preprocessors: {
'**/dist/*.js': [
'coverage'
]
},
reporters: [
'nested',
'coverage'
],
thresholdReporter: {
statements: 95,
branches: 95,
functions: 95,
lines: 95
}
});
};
| 'use strict';
module.exports = function(config) {
config.set({
autoWatch: true,
browsers: [
'PhantomJS'
],
colors: true,
coverageReporter: {
dir: 'coverage',
instrumenterOptions: {
istanbul: {
noCompact: true
}
},
reporters: [{
type: 'html',
subdir: 'report-html'
}, {
type: 'lcov',
subdir: 'report-lcov'
}, {
type: 'cobertura',
subdir: '.',
file: 'cobertura.txt'
}, {
type: 'lcovonly',
subdir: '.',
file: 'report-lcovonly.txt'
}, {
type: 'teamcity',
subdir: '.',
file: 'teamcity.txt'
}, {
type: 'text',
subdir: '.',
file: 'text.txt'
}, {
type: 'text-summary',
subdir: '.',
file: 'text-summary.txt'
}]
},
files: [
'dist/jasmine-matchers.js',
'dist/jasmine-matchers.spec.js'
],
frameworks: [
'jasmine'
],
preprocessors: {
'**/dist/jasmine-matchers.js': [
'coverage'
]
},
reporters: [
'nested',
'coverage'
],
thresholdReporter: {
statements: 95,
branches: 95,
functions: 95,
lines: 95
}
});
};
| Exclude spec from coverage reporting. | Exclude spec from coverage reporting.
| JavaScript | mit | JamieMason/Jasmine-Matchers,JamieMason/Jasmine-Matchers | ---
+++
@@ -58,7 +58,7 @@
],
preprocessors: {
- '**/dist/*.js': [
+ '**/dist/jasmine-matchers.js': [
'coverage'
]
}, |
0582f24801837916e3cb2c674cf3704487929272 | index.js | index.js | 'use strict';
var execFile = require('child_process').execFile;
var toDecimal = require('to-decimal');
module.exports = function (cb) {
if (process.platform !== 'win32') {
throw new TypeError('Only Windows systems are supported');
}
var cmd = 'WMIC';
var args = ['Path', 'Win32_Battery', 'Get', 'EstimatedChargeRemaining'];
execFile(cmd, args, function (err, stdout) {
if (err) {
cb(err);
return;
}
if (!stdout) {
cb(new Error('No battery could be found'));
}
cb(null, toDecimal(parseFloat(stdout.trim().split('\n')[1])));
});
};
| 'use strict';
var execFile = require('child_process').execFile;
var toDecimal = require('to-decimal');
module.exports = function (cb) {
if (process.platform !== 'win32') {
throw new TypeError('Only Windows systems are supported');
}
var cmd = 'WMIC';
var args = ['Path', 'Win32_Battery', 'Get', 'EstimatedChargeRemaining'];
execFile(cmd, args, function (err, stdout) {
if (err) {
cb(err);
return;
}
if (!stdout) {
cb(new Error('No battery could be found'));
}
stdout = parseFloat(stdout.trim().split('\n')[1]);
cb(null, toDecimal(stdout > 1 ? 1 : stdout));
});
};
| Set to `1` if higher | Set to `1` if higher
| JavaScript | mit | kevva/win-battery-level | ---
+++
@@ -20,6 +20,7 @@
cb(new Error('No battery could be found'));
}
- cb(null, toDecimal(parseFloat(stdout.trim().split('\n')[1])));
+ stdout = parseFloat(stdout.trim().split('\n')[1]);
+ cb(null, toDecimal(stdout > 1 ? 1 : stdout));
});
}; |
a4f675a9fd5a7da1d79a0bdc1d974789d965ff24 | index.js | index.js | // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recusrive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| // Requires
var Q = require('q');
var _ = require('underscore');
var qClass = require('qpatch').qClass;
// Etcd client
var Etcd = qClass(require('node-etcd'), ['watcher']);
// Since etcd create the dir keys automatically
// transform the tree of keys
// to contain only a flat array of leaves
function cleanDump(obj) {
// Is a leaf
if(!_.has(obj, 'kvs')) {
// We don't want the modifiedIndex attr in our dumps/restores
return _.pick(obj, 'key', 'value');
}
return _.flatten(_.map(obj.kvs, cleanDump));
}
function Dumper(etcd) {
// ETCD client
this.store = new Etcd();
_.bindAll(this);
}
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
recursive: true
})
.then(cleanDump);
};
// Restore a list of keys
Dumper.prototype.restore = function(entries) {
var self = this;
return Q.all(_.map(entries, function(entry) {
return this.store.set(entry.key, entry.value);
}));
};
// Restore the database from input data
function createDumper() {
return new Dumper();
}
// Exports
module.exports = createDumper;
| Fix silly typo "recusrive" => "recursive" | Fix silly typo "recusrive" => "recursive"
| JavaScript | apache-2.0 | AaronO/etcd-dump | ---
+++
@@ -31,7 +31,7 @@
// Get a JS object of the DB
Dumper.prototype.dump = function() {
return this.store.get('', {
- recusrive: true
+ recursive: true
})
.then(cleanDump);
}; |
df4e0ae386c67dc9635ecb64e8cc6b10fe53e8ec | index.js | index.js | module.exports = require("./moment-timezone");
module.exports.tz.add(require('./data/packed/latest.json'));
| var moment = module.exports = require("./moment-timezone");
moment.tz.load(require('./data/packed/latest.json'));
| Use `moment.tz.load` instead of `moment.tz.add` to import initial data in Node. | Use `moment.tz.load` instead of `moment.tz.add` to import initial data in Node.
#94
| JavaScript | mit | blixt/moment-timezone,moment/moment-timezone,samjoch/moment-timezone,kidaa/moment-timezone,lookfirst/moment-timezone,HubSpot/moment-timezone,eddywashere/moment-timezone,andrewchae/moment-timezone,mj1856/moment-timezone,orocrm/moment-timezone,mkhuramj/moment-timezone,6ft-invsbl-rbbt/moment-timezone,rollbar/moment-timezone,bcbroussard/moment-timezone,timrwood/moment-timezone,dieface/moment-timezone,moment/moment-timezone,almamedia/moment-timezone,d0rc/moment-timezone | ---
+++
@@ -1,2 +1,2 @@
-module.exports = require("./moment-timezone");
-module.exports.tz.add(require('./data/packed/latest.json'));
+var moment = module.exports = require("./moment-timezone");
+moment.tz.load(require('./data/packed/latest.json')); |
c7d0a3cb82beb53df3231e32ae8ac84f804082d2 | index.js | index.js | var pegjs = require('pegjs');
var loaderUtils = require('loader-utils');
module.exports = function(source) {
this.cacheable && this.cacheable();
var query = loaderUtils.parseQuery(this.query);
var pegOptions = { output: 'source' };
var parser = 'module.exports = ' + pegjs.buildParser(source, pegOptions) + ';';
this.callback(null, parser, null);
};
| var pegjs = require('pegjs');
var loaderUtils = require('loader-utils');
module.exports = function(source) {
this.cacheable && this.cacheable();
var query = loaderUtils.parseQuery(this.query);
var cacheParserResults = !!query.cache;
// Description of PEG.js options: https://github.com/pegjs/pegjs#javascript-api
var pegOptions = { output: 'source', cache: cacheParserResults };
return 'module.exports = ' + pegjs.buildParser(source, pegOptions) + ';';
};
| Add option to build parser with enabled cache | Add option to build parser with enabled cache
Usage: `require('pegjs?cache!parser.pegjs')` | JavaScript | mit | eploko/pegjs-loader | ---
+++
@@ -4,7 +4,8 @@
module.exports = function(source) {
this.cacheable && this.cacheable();
var query = loaderUtils.parseQuery(this.query);
- var pegOptions = { output: 'source' };
- var parser = 'module.exports = ' + pegjs.buildParser(source, pegOptions) + ';';
- this.callback(null, parser, null);
+ var cacheParserResults = !!query.cache;
+ // Description of PEG.js options: https://github.com/pegjs/pegjs#javascript-api
+ var pegOptions = { output: 'source', cache: cacheParserResults };
+ return 'module.exports = ' + pegjs.buildParser(source, pegOptions) + ';';
}; |
3372bfedefcc5c057fbdc5ed43457493e1aee71a | index.js | index.js | 'use strict';
var util = require('util');
var wrapi = require('wrapi');
var endpoints = require('./api/slack.json');
function slackWrapi(token) {
var opts = {
qs: {
token: token
},
headers: {
'User-Agent': 'slack-wrapi'
}
};
slackWrapi.super_.call(this,
'https://slack.com/api/',
endpoints,
opts);
};
util.inherits(slackWrapi, wrapi);
module.exports = slackWrapi;
| 'use strict';
var util = require('util');
var wrapi = require('wrapi');
var endpoints = require('./api/slack.json');
function slackWrapi(token) {
var opts = {
headers: {
'User-Agent': 'slack-wrapi',
'Authorization': 'Bearer ' + token,
}
};
slackWrapi.super_.call(this,
'https://slack.com/api/',
endpoints,
opts);
};
util.inherits(slackWrapi, wrapi);
module.exports = slackWrapi;
| Add authorization header to api calls | Add authorization header to api calls
| JavaScript | mit | wrapi/slack | ---
+++
@@ -8,11 +8,9 @@
function slackWrapi(token) {
var opts = {
- qs: {
- token: token
- },
headers: {
- 'User-Agent': 'slack-wrapi'
+ 'User-Agent': 'slack-wrapi',
+ 'Authorization': 'Bearer ' + token,
}
};
|
90732897e7b64a65de03a28860ef2db1e3820d6b | index.js | index.js | import React from 'react';
import { requireNativeComponent } from 'react-native';
import PropTypes from 'prop-types';
const RNPdfScanner = requireNativeComponent('RNPdfScanner', PdfScanner);
class PdfScanner extends React.Component {
sendOnPictureTakenEvent(event) {
return this.props.onPictureTaken(event.nativeEvent);
}
render() {
return (
<RNPdfScanner
{...this.props}
onPictureTaken={this.sendOnPictureTakenEvent.bind(this)}
/>
);
}
}
PdfScanner.propTypes = {
onPictureTaken: PropTypes.func,
overlayColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
enableTorch: PropTypes.bool,
saturation: PropTypes.number,
brightness: PropTypes.number,
contrast: PropTypes.number,
};
export default PdfScanner;
| import React from 'react';
import { requireNativeComponent } from 'react-native';
import PropTypes from 'prop-types';
const RNPdfScanner = requireNativeComponent('RNPdfScanner', PdfScanner);
class PdfScanner extends React.Component {
sendOnPictureTakenEvent(event) {
return this.props.onPictureTaken(event.nativeEvent);
}
render() {
return (
<RNPdfScanner
{...this.props}
onPictureTaken={this.sendOnPictureTakenEvent.bind(this)}
brightness={this.props.brightness||0}
saturation={this.props.saturation||1}
contrast={this.props.contrast||1}
/>;
);
}
}
PdfScanner.propTypes = {
onPictureTaken: PropTypes.func,
overlayColor: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
enableTorch: PropTypes.bool,
saturation: PropTypes.number,
brightness: PropTypes.number,
contrast: PropTypes.number,
};
export default PdfScanner;
| Add default saturation, brightness, contrast value | Add default saturation, brightness, contrast value
| JavaScript | mit | Michaelvilleneuve/react-native-document-scanner,Michaelvilleneuve/react-native-document-scanner,Michaelvilleneuve/react-native-document-scanner,Michaelvilleneuve/react-native-document-scanner | ---
+++
@@ -13,7 +13,10 @@
<RNPdfScanner
{...this.props}
onPictureTaken={this.sendOnPictureTakenEvent.bind(this)}
- />
+ brightness={this.props.brightness||0}
+ saturation={this.props.saturation||1}
+ contrast={this.props.contrast||1}
+ />;
);
}
} |
6211a95f0d9326b16895706bf9e322839a2eff35 | index.js | index.js | #!/usr/bin/env node
const fs = require( 'fs' );
const path = require( 'path' );
const readline = require( 'readline' );
const eol = require( 'os' ).EOL;
const moment = require( 'moment' );
const now = moment();
if ( process.argv.length !== 3 ) printUsageAndExit();
const FILENAME = `${process.argv[2]}.txt`;
const FILEPATH = path.resolve( process.cwd(), './', FILENAME );
const timestamp = function() {
return moment().format( 'hh:mm:ss A' );
}
const rli = readline.createInterface({
input: process.stdin,
output: fs.createWriteStream( FILEPATH, { flags: 'a' } )
});
rli.on( 'line', function ( line ) {
rli.output.write( timestamp() + ' > ' + String( line ) + eol );
process.stdout.write( '> ' );
});
process.on( 'SIGINT', function() {
rli.output.write( eol );
process.stdout.write( eol + 'Note saved!' + eol );
process.exit( 0 );
});
process.stdout.write( '> ' );
rli.output.write( timestamp() + eol );
function printUsageAndExit () {
console.log('Usage: timestamp <filename>');
process.exit(1);
}
| #!/usr/bin/env node
const fs = require( 'fs' );
const path = require( 'path' );
const readline = require( 'readline' );
const eol = require( 'os' ).EOL;
if ( process.argv.length !== 3 ) printUsageAndExit();
const FILENAME = `${process.argv[2]}.txt`;
const FILEPATH = path.resolve( process.cwd(), './', FILENAME );
const timestamp = function() {
let seconds = process.hrtime(time)[0];
return calculateTimestamp(seconds);
}
const calculateTimestamp = function(seconds) {
const minutes = Math.floor(seconds / 60).toString();
let remainingSeconds = (seconds % 60).toString();
let formatedSeconds = remainingSeconds.length === 1 ? remainingSeconds + '0' : remainingSeconds;
return `${minutes}:${formatedSeconds}`;
}
const rli = readline.createInterface({
input: process.stdin,
output: fs.createWriteStream( FILEPATH, { flags: 'a' } )
});
let time = process.hrtime();
rli.on( 'line', function ( line ) {
rli.output.write( timestamp() + ' - ' + String( line ) + eol );
process.stdout.write( '> ' );
});
process.on( 'SIGINT', function() {
rli.output.write( eol );
process.stdout.write( eol + 'Note saved!' + eol );
process.exit( 0 );
});
process.stdout.write( '> ' );
rli.output.write( timestamp() + eol );
function printUsageAndExit () {
console.log('Usage: timestamp <filename>');
process.exit(1);
}
| Make timestamps relative to start time | Make timestamps relative to start time
| JavaScript | mit | jake-shasteen/timestamp-notes | ---
+++
@@ -4,8 +4,6 @@
const path = require( 'path' );
const readline = require( 'readline' );
const eol = require( 'os' ).EOL;
-const moment = require( 'moment' );
-const now = moment();
if ( process.argv.length !== 3 ) printUsageAndExit();
@@ -13,7 +11,15 @@
const FILEPATH = path.resolve( process.cwd(), './', FILENAME );
const timestamp = function() {
- return moment().format( 'hh:mm:ss A' );
+ let seconds = process.hrtime(time)[0];
+ return calculateTimestamp(seconds);
+}
+
+const calculateTimestamp = function(seconds) {
+ const minutes = Math.floor(seconds / 60).toString();
+ let remainingSeconds = (seconds % 60).toString();
+ let formatedSeconds = remainingSeconds.length === 1 ? remainingSeconds + '0' : remainingSeconds;
+ return `${minutes}:${formatedSeconds}`;
}
const rli = readline.createInterface({
@@ -21,8 +27,11 @@
output: fs.createWriteStream( FILEPATH, { flags: 'a' } )
});
+let time = process.hrtime();
+
+
rli.on( 'line', function ( line ) {
- rli.output.write( timestamp() + ' > ' + String( line ) + eol );
+ rli.output.write( timestamp() + ' - ' + String( line ) + eol );
process.stdout.write( '> ' );
});
@@ -39,3 +48,4 @@
console.log('Usage: timestamp <filename>');
process.exit(1);
}
+ |
491b72a59df3d5c4d67e55d4198b65eace1b971e | lib/colors.js | lib/colors.js | module.exports = function (expect) {
expect.output.addStyle('error', function (content) {
this.text(content, 'red, bold');
});
expect.output.addStyle('strings', function (content) {
this.text(content, '#CC7200');
});
expect.output.addStyle('key', function (content) {
this.text(content);
});
};
| module.exports = function (expect) {
expect.output.addStyle('error', function (content) {
this.text(content, 'red, bold');
});
expect.output.addStyle('strings', function (content) {
this.text(content, '#CC7200');
});
expect.output.addStyle('key', function (content) {
this.text(content);
});
// Intended to be redefined by a plugin that offers syntax highlighting:
expect.output.addStyle('code', function (content, language) {
this.text(content);
});
};
| Define a 'code' style that can be overwritten by plugins. | Define a 'code' style that can be overwritten by plugins.
| JavaScript | mit | alexjeffburke/unexpected,bruderstein/unexpected,bruderstein/unexpected,Munter/unexpected,unexpectedjs/unexpected,alexjeffburke/unexpected | ---
+++
@@ -8,4 +8,8 @@
expect.output.addStyle('key', function (content) {
this.text(content);
});
+ // Intended to be redefined by a plugin that offers syntax highlighting:
+ expect.output.addStyle('code', function (content, language) {
+ this.text(content);
+ });
}; |
7433ea7bdfa35b1ae53bce646b9646257a23e3e2 | lib/decode.js | lib/decode.js | 'use strict';
module.exports = function(){
};
| 'use strict';
module.exports = function(bin){
let data = {};
data.fin = !!(bin[0] >>> 7);
data.reserves = ((bin[0] >>> 4) - (data.fin ? 8 : 0));
data.opts = bin[0] - (data.fin ? 128 : 0) - data.reserves;
data.masked = !!(bin[1] >>> 7);
console.log(data);
return data;
};
| Add decoding of first byte and mask. | Add decoding of first byte and mask.
| JavaScript | mit | jamen/rela | ---
+++
@@ -1,5 +1,13 @@
'use strict';
-module.exports = function(){
+module.exports = function(bin){
+ let data = {};
+ data.fin = !!(bin[0] >>> 7);
+ data.reserves = ((bin[0] >>> 4) - (data.fin ? 8 : 0));
+ data.opts = bin[0] - (data.fin ? 128 : 0) - data.reserves;
+ data.masked = !!(bin[1] >>> 7);
+ console.log(data);
+
+ return data;
}; |
e20c6b47080c1778fdd37599486e8fb56b00e9fe | packages/core/lib/commands/db/index.js | packages/core/lib/commands/db/index.js | const OS = require("os");
const serveCommand = require("./commands/serve");
const usage =
"truffle db <sub-command> [options]" +
OS.EOL +
OS.EOL +
" Available sub-commands: " +
OS.EOL +
OS.EOL +
" serve \tStart the GraphQL server" +
OS.EOL;
const command = {
command: "db",
description: "Database interface commands",
builder: function (yargs) {
return yargs.command(serveCommand).demandCommand();
},
subCommands: {
serve: {
help: serveCommand.help,
description: serveCommand.description
}
},
help: {
usage,
options: []
},
run: async function (args) {
const [subCommand] = args._;
switch (subCommand) {
case "serve":
await serveCommand.run(args);
break;
default:
console.log(`Unknown command: ${subCommand}`);
}
}
};
module.exports = command;
| const OS = require("os");
const serveCommand = require("./commands/serve");
const usage =
"truffle db <sub-command> [options]" +
OS.EOL +
" Available sub-commands: " +
OS.EOL +
" serve \tStart the GraphQL server";
const command = {
command: "db",
description: "Database interface commands",
builder: function (yargs) {
return yargs.command(serveCommand).demandCommand();
},
subCommands: {
serve: {
help: serveCommand.help,
description: serveCommand.description
}
},
help: {
usage,
options: []
},
run: async function (args) {
const [subCommand] = args._;
switch (subCommand) {
case "serve":
await serveCommand.run(args);
break;
default:
console.log(`Unknown command: ${subCommand}`);
}
}
};
module.exports = command;
| Make minor edit to db help output | Make minor edit to db help output
| JavaScript | mit | ConsenSys/truffle | ---
+++
@@ -4,12 +4,9 @@
const usage =
"truffle db <sub-command> [options]" +
OS.EOL +
- OS.EOL +
" Available sub-commands: " +
OS.EOL +
- OS.EOL +
- " serve \tStart the GraphQL server" +
- OS.EOL;
+ " serve \tStart the GraphQL server";
const command = {
command: "db", |
244a3b852e7cee8392b1d6962b49f832ed47fb87 | src/main/helpers/SafeHelper.js | src/main/helpers/SafeHelper.js | const name = 'safe';
export default function SafeHelper(config, logger) {
const _logger = logger.child({helper: name});
return {
name,
cb: (string) => {
_logger.debug('Executing template safe helper.', {string});
if (string) {
return string.replace(/(\\[bfnrt"\\])/g, '\\$1');
} else {
return '';
}
}
};
}
| const chars = {
'\n': '\\\\n',
'\\': '\\\\'
};
const name = 'safe';
export default function SafeHelper(config, logger) {
const _logger = logger.child({helper: name});
return {
name,
cb: (string) => {
_logger.debug('Executing template safe helper.', {string});
if (string) {
return string.replace(/([\b\f\n\r\t"\\])/g, (match, char) => {
return chars[char] || '';
});
} else {
return '';
}
}
};
}
| Refactor JSON escaping to handle slashes better. | Refactor JSON escaping to handle slashes better.
| JavaScript | mit | ssube/eveningdriver,ssube/eveningdriver | ---
+++
@@ -1,3 +1,8 @@
+const chars = {
+ '\n': '\\\\n',
+ '\\': '\\\\'
+};
+
const name = 'safe';
export default function SafeHelper(config, logger) {
const _logger = logger.child({helper: name});
@@ -6,7 +11,9 @@
cb: (string) => {
_logger.debug('Executing template safe helper.', {string});
if (string) {
- return string.replace(/(\\[bfnrt"\\])/g, '\\$1');
+ return string.replace(/([\b\f\n\r\t"\\])/g, (match, char) => {
+ return chars[char] || '';
+ });
} else {
return '';
} |
37ad5a1744674b364044bc964808970e1b4cff86 | lib/config.js | lib/config.js | /**
* Main CLI parser class
*/
class Config
{
/**
* @param {Command} argv
*/
constructor (argv)
{
/**
* @private
* @type {boolean}
*/
this.dev = argv.d || argv.dev;
/**
* @private
* @type {boolean}
*/
this.debug = argv.debug;
/**
* @private
* @type {boolean}
*/
this.sourceMaps = argv.withSourceMaps;
/**
* @private
* @type {boolean}
*/
this.watch = argv.watch;
/**
* @private
* @type {boolean}
*/
this.lint = argv.lint;
}
/**
* Returns whether this is a debug build
*
* @return {boolean}
*/
isDebug ()
{
return this.debug || this.dev;
}
/**
* Returns whether to include sourcemaps
*
* @return {boolean}
*/
includeSourceMaps ()
{
return this.sourceMaps || this.dev;
}
/**
* Returns whether the watcher should be activated
*
* @return {boolean}
*/
isWatch ()
{
return this.watch || this.dev;
}
/**
* Returns whether the code should be linted
*
* @return {boolean}
*/
isLint ()
{
return this.lint || this.dev;
}
}
module.exports = Config;
| /**
* Main CLI parser class
*/
class Config
{
/**
* @param {Command} argv
*/
constructor (argv)
{
// commander just returns undefined for missing flags, so transform them to boolean
/**
* @private
* @type {boolean}
*/
this.dev = !!argv.d || !!argv.dev;
/**
* @private
* @type {boolean}
*/
this.debug = !!argv.debug;
/**
* @private
* @type {boolean}
*/
this.sourceMaps = !!argv.withSourceMaps;
/**
* @private
* @type {boolean}
*/
this.watch = !!argv.watch;
/**
* @private
* @type {boolean}
*/
this.lint = !!argv.lint;
}
/**
* Returns whether this is a debug build
*
* @return {boolean}
*/
isDebug ()
{
return this.debug || this.dev;
}
/**
* Returns whether to include sourcemaps
*
* @return {boolean}
*/
includeSourceMaps ()
{
return this.sourceMaps || this.dev;
}
/**
* Returns whether the watcher should be activated
*
* @return {boolean}
*/
isWatch ()
{
return this.watch || this.dev;
}
/**
* Returns whether the code should be linted
*
* @return {boolean}
*/
isLint ()
{
return this.lint || this.dev;
}
}
module.exports = Config;
| Fix parsing of commander options | Fix parsing of commander options
| JavaScript | bsd-3-clause | Becklyn/kaba,Becklyn/kaba | ---
+++
@@ -8,35 +8,36 @@
*/
constructor (argv)
{
+ // commander just returns undefined for missing flags, so transform them to boolean
/**
* @private
* @type {boolean}
*/
- this.dev = argv.d || argv.dev;
+ this.dev = !!argv.d || !!argv.dev;
/**
* @private
* @type {boolean}
*/
- this.debug = argv.debug;
+ this.debug = !!argv.debug;
/**
* @private
* @type {boolean}
*/
- this.sourceMaps = argv.withSourceMaps;
+ this.sourceMaps = !!argv.withSourceMaps;
/**
* @private
* @type {boolean}
*/
- this.watch = argv.watch;
+ this.watch = !!argv.watch;
/**
* @private
* @type {boolean}
*/
- this.lint = argv.lint;
+ this.lint = !!argv.lint;
}
|
71b6d8e2c3fcdc8d156cf2ba4009590a6e48a4b6 | src/LevelSelect.js | src/LevelSelect.js | import html from "innerself";
import Scene from "./Scene";
import { SCENES } from "./actions"
import { connect } from "./store";
function LevelScore(score, idx) {
return html`
<div class="box action"
onclick="goto(${SCENES.FIND}, ${idx})"
style="padding: .5rem; color: #666;">
${score}</div>
`;
}
function LevelSelect({results}) {
return Scene(
{id: SCENES.LEVELS, from: "black", to: "black"},
html`
<div class="ui black">
<div class="pad">
${results.map(LevelScore)}
<div class="action"
style="padding: .5rem;"
onclick="goto(${SCENES.FIND}, ${results.length})">next</div>
</div>
</div>`
);
}
export default connect(LevelSelect);
| import html from "innerself";
import Scene from "./Scene";
import { SCENES } from "./actions"
import { connect } from "./store";
function LevelScore(score, idx) {
return html`
<div class="box action"
onclick="goto(${SCENES.FIND}, ${idx})"
style="padding: .5rem; color: #666;">
${score}</div>
`;
}
function LevelSelect({results}) {
const total = results.reduce((acc, cur) => acc + cur);
const average = Math.floor(total / results.length);
// An inverted hyperbola with lim(x → ∞) = 1.
const threshold = 100 * (1 - 2.5 / results.length);
return Scene(
{id: SCENES.LEVELS, from: "black", to: "black"},
html`
<div class="ui black">
<div class="pad">
${results.map(LevelScore)}
${ average > threshold
? `<div class="action" style="padding: .5rem;"
onclick="goto(${SCENES.FIND}, ${results.length})">next</div>`
: `<div class="action" style="padding: .5rem;"
title="Your average so far is too low to advance.">
…?
</div>`
}
</div>
</div>`
);
}
export default connect(LevelSelect);
| Add a scalable threshold for advancing | Add a scalable threshold for advancing
| JavaScript | isc | piesku/moment-lost,piesku/moment-lost | ---
+++
@@ -13,15 +13,25 @@
}
function LevelSelect({results}) {
+ const total = results.reduce((acc, cur) => acc + cur);
+ const average = Math.floor(total / results.length);
+ // An inverted hyperbola with lim(x → ∞) = 1.
+ const threshold = 100 * (1 - 2.5 / results.length);
+
return Scene(
{id: SCENES.LEVELS, from: "black", to: "black"},
html`
<div class="ui black">
<div class="pad">
${results.map(LevelScore)}
- <div class="action"
- style="padding: .5rem;"
- onclick="goto(${SCENES.FIND}, ${results.length})">next</div>
+ ${ average > threshold
+ ? `<div class="action" style="padding: .5rem;"
+ onclick="goto(${SCENES.FIND}, ${results.length})">next</div>`
+ : `<div class="action" style="padding: .5rem;"
+ title="Your average so far is too low to advance.">
+ …?
+ </div>`
+ }
</div>
</div>`
); |
87cc2ce5b7fb2763e68c5a6e2639971618da0dd4 | bin/karma-ci.js | bin/karma-ci.js | var karma = require('karma');
var karmaConfig = require('karma/lib/config');
var config = karmaConfig.parseConfig(__dirname + '/../karma.conf.js', {
browsers: [],
oneShot: true,
});
var server = new karma.Server(config);
server.on('browser_complete', (completedBrowser) => {
if (completedBrowser.lastResult.failed > 0) {
process.exit(1);
} else {
process.exit(0);
}
});
server.start();
| var karma = require('karma');
var karmaConfig = require('karma/lib/config');
var config = karmaConfig.parseConfig(__dirname + '/../karma.conf.js', {
browsers: [],
oneShot: true,
});
var server = new karma.Server(config);
server.on('browser_complete', (completedBrowser) => {
console.log(completedBrowser);
if (completedBrowser.lastResult.error || completedBrowser.lastResult.failed > 0) {
process.exit(1);
} else {
process.exit(0);
}
});
server.start();
| Make sure test errors report as a failure | Make sure test errors report as a failure
| JavaScript | mpl-2.0 | Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy,Osmose/normandy,mozilla/normandy | ---
+++
@@ -9,7 +9,8 @@
var server = new karma.Server(config);
server.on('browser_complete', (completedBrowser) => {
- if (completedBrowser.lastResult.failed > 0) {
+ console.log(completedBrowser);
+ if (completedBrowser.lastResult.error || completedBrowser.lastResult.failed > 0) {
process.exit(1);
} else {
process.exit(0); |
ad5c38087abcaa54ac544313b693c1aa7e8c392b | lib/openers/atompdf-opener.js | lib/openers/atompdf-opener.js | 'use babel'
import Opener from '../opener'
export default class AtomPdfOpener extends Opener {
open (filePath, texPath, lineNumber, callback) {
// Opens PDF in a new pane -- requires pdf-view module
const openPanes = atom.workspace.getPaneItems()
for (const openPane of openPanes) {
// File is already open in another pane
if (openPane.filePath === filePath) { return }
}
const pane = atom.workspace.getActivePane()
// TODO: Make this configurable?
// FIXME: Migrate to Pane::splitRight.
const newPane = pane.split('horizontal', 'after')
// FIXME: Use public API instead.
atom.workspace.openURIInPane(filePath, newPane)
// TODO: Check for actual success?
if (callback) {
callback(0)
}
}
}
| 'use babel'
import Opener from '../opener'
export default class AtomPdfOpener extends Opener {
open (filePath, texPath, lineNumber, callback) {
// Opens PDF in a new pane -- requires pdf-view module
function forwardSync(pdfView) {
if (pdfView != null && pdfView.forwardSync != null) {
pdfView.forwardSync(texPath, lineNumber)
}
}
const openPaneItems = atom.workspace.getPaneItems()
for (const openPaneItem of openPaneItems) {
// File is already open in another pane
if (openPaneItem.filePath === filePath) {
forwardSync(openPaneItem)
return
}
}
const activePane = atom.workspace.getActivePane()
// TODO: Make this configurable?
atom.workspace.open(filePath, {'split': 'right'}).done(function (pdfView) {
forwardSync(pdfView)
})
// TODO: Check for actual success?
if (callback) {
callback(0)
}
}
}
| Add forward sync support to Atom PDF opener | Add forward sync support to Atom PDF opener
Calls forwardSync on the PDF view on opening
| JavaScript | mit | thomasjo/atom-latex,thomasjo/atom-latex,thomasjo/atom-latex | ---
+++
@@ -5,18 +5,27 @@
export default class AtomPdfOpener extends Opener {
open (filePath, texPath, lineNumber, callback) {
// Opens PDF in a new pane -- requires pdf-view module
- const openPanes = atom.workspace.getPaneItems()
- for (const openPane of openPanes) {
- // File is already open in another pane
- if (openPane.filePath === filePath) { return }
+
+ function forwardSync(pdfView) {
+ if (pdfView != null && pdfView.forwardSync != null) {
+ pdfView.forwardSync(texPath, lineNumber)
+ }
}
- const pane = atom.workspace.getActivePane()
+ const openPaneItems = atom.workspace.getPaneItems()
+ for (const openPaneItem of openPaneItems) {
+ // File is already open in another pane
+ if (openPaneItem.filePath === filePath) {
+ forwardSync(openPaneItem)
+ return
+ }
+ }
+
+ const activePane = atom.workspace.getActivePane()
// TODO: Make this configurable?
- // FIXME: Migrate to Pane::splitRight.
- const newPane = pane.split('horizontal', 'after')
- // FIXME: Use public API instead.
- atom.workspace.openURIInPane(filePath, newPane)
+ atom.workspace.open(filePath, {'split': 'right'}).done(function (pdfView) {
+ forwardSync(pdfView)
+ })
// TODO: Check for actual success?
if (callback) { |
c2643d208c692b94964cfaef6991c8d143ffc51f | src/dapps/index.js | src/dapps/index.js | import domainSale from '@/assets/images/icons/domain-sale.svg';
import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg';
import registerDomain from '@/assets/images/icons/domain.svg';
import registerDomainHov from '@/assets/images/icons/domain-hov.svg';
import secureTransaction from '@/assets/images/icons/button-key-hover.svg';
import secureTransactionHov from '@/assets/images/icons/button-key.svg';
import { ETH, GOERLI, ROP, RIN } from '@/networks/types';
const dapps = {
registerDomain: {
route: '/interface/dapps/register-domain',
icon: registerDomain,
iconDisabled: registerDomainHov,
title: 'interface.registerEns',
desc: 'interface.registerENSDescShort',
supportedNetworks: [ETH.name, GOERLI.name, ROP.name, RIN.name]
},
domainSale: {
route: '/interface/dapps/buy-subdomain',
icon: domainSale,
iconDisabled: domainSaleHov,
title: 'interface.subdomains',
desc: 'interface.buySubDomains',
supportedNetworks: [ETH.name]
},
secureTransaction: {
route: '/interface/dapps/secure-transaction',
icon: secureTransaction,
iconDisabled: secureTransactionHov,
title: 'dapps.safesend_title',
desc: 'dapps.safesend_desc',
supportedNetworks: [ETH.name]
}
};
export default dapps;
| import domainSale from '@/assets/images/icons/domain-sale.svg';
import domainSaleHov from '@/assets/images/icons/domain-sale-hov.svg';
import registerDomain from '@/assets/images/icons/domain.svg';
import registerDomainHov from '@/assets/images/icons/domain-hov.svg';
import secureTransaction from '@/assets/images/icons/button-key-hover.svg';
import secureTransactionHov from '@/assets/images/icons/button-key.svg';
import { ETH, GOERLI } from '@/networks/types';
const dapps = {
registerDomain: {
route: '/interface/dapps/register-domain',
icon: registerDomain,
iconDisabled: registerDomainHov,
title: 'interface.registerEns',
desc: 'interface.registerENSDescShort',
supportedNetworks: [ETH.name, GOERLI.name]
},
domainSale: {
route: '/interface/dapps/buy-subdomain',
icon: domainSale,
iconDisabled: domainSaleHov,
title: 'interface.subdomains',
desc: 'interface.buySubDomains',
supportedNetworks: [ETH.name]
},
secureTransaction: {
route: '/interface/dapps/secure-transaction',
icon: secureTransaction,
iconDisabled: secureTransactionHov,
title: 'dapps.safesend_title',
desc: 'dapps.safesend_desc',
supportedNetworks: [ETH.name]
}
};
export default dapps;
| Disable ens for rin and rop since they have a different implementation | Disable ens for rin and rop since they have a different implementation
| JavaScript | mit | MyEtherWallet/MyEtherWallet,MyEtherWallet/MyEtherWallet,MyEtherWallet/MyEtherWallet | ---
+++
@@ -4,7 +4,7 @@
import registerDomainHov from '@/assets/images/icons/domain-hov.svg';
import secureTransaction from '@/assets/images/icons/button-key-hover.svg';
import secureTransactionHov from '@/assets/images/icons/button-key.svg';
-import { ETH, GOERLI, ROP, RIN } from '@/networks/types';
+import { ETH, GOERLI } from '@/networks/types';
const dapps = {
registerDomain: {
@@ -13,7 +13,7 @@
iconDisabled: registerDomainHov,
title: 'interface.registerEns',
desc: 'interface.registerENSDescShort',
- supportedNetworks: [ETH.name, GOERLI.name, ROP.name, RIN.name]
+ supportedNetworks: [ETH.name, GOERLI.name]
},
domainSale: {
route: '/interface/dapps/buy-subdomain', |
59b97920a7a0fc39379d3883881bbe776dc53bf4 | tasks/config/webpack.js | tasks/config/webpack.js | var path = require('path');
var webpack = require('webpack');
var babelConfig = require('./babel.json');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/lib/App'
],
output: {
path: path.join(process.cwd(), 'public'),
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx'],
// These aliases are used to make it easier to import
// our own modules.
'alias': {
'app': path.join(process.cwd(), 'app'),
'components': 'app/lib/components',
'actions': 'app/lib/actions',
'etc': 'app/lib/etc',
'stores': 'app/lib/stores',
'pages': 'app/lib/pages'
}
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader?' + JSON.stringify(babelConfig)],
include: path.join(process.cwd(), 'app')
}]
}
};
| var path = require('path');
var webpack = require('webpack');
var babelConfig = require('./babel.json');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/lib/App'
],
output: {
path: path.join(process.cwd(), 'public'),
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.jsx'],
// These aliases are used to make it easier to import our own modules.
// This works in tandem with the import path described in package.json,
// which is used for the HTML rendering server code.
'alias': {
'app': path.join(process.cwd(), 'app'),
'components': 'app/lib/components',
'actions': 'app/lib/actions',
'etc': 'app/lib/etc',
'stores': 'app/lib/stores',
'pages': 'app/lib/pages'
}
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel-loader?' + JSON.stringify(babelConfig)],
include: path.join(process.cwd(), 'app')
}]
}
};
| Clarify the use of import aliases | Clarify the use of import aliases
| JavaScript | mit | msikma/react-hot-boilerplate,msikma/react-hot-boilerplate | ---
+++
@@ -19,8 +19,9 @@
],
resolve: {
extensions: ['', '.js', '.jsx'],
- // These aliases are used to make it easier to import
- // our own modules.
+ // These aliases are used to make it easier to import our own modules.
+ // This works in tandem with the import path described in package.json,
+ // which is used for the HTML rendering server code.
'alias': {
'app': path.join(process.cwd(), 'app'),
'components': 'app/lib/components', |
c9a9b1c06818c8f371a7ae53ead224f063a39086 | src/navigator/config/config.js | src/navigator/config/config.js | module.exports = {
stylePrefix: 'nv-',
// Enable/Disable globally the possibility to sort layers
sortable: 1,
// Enable/Disable globally the possibility to hide layers
hidable: 1,
// Hide textnodes
hideTextnode: 1,
// Indicates if the wrapper is visible in layers
showWrapper: 1
};
| module.exports = {
stylePrefix: 'nv-',
// Specify where to render layers on init, string (query) or HTMLElement
// With the empty value, layers won't be visible
el: '',
// Enable/Disable globally the possibility to sort layers
sortable: 1,
// Enable/Disable globally the possibility to hide layers
hidable: 1,
// Hide textnodes
hideTextnode: 1,
// Indicates if the wrapper is visible in layers
showWrapper: 1
};
| Add el option to layers | Add el option to layers
| JavaScript | bsd-3-clause | artf/grapesjs,artf/grapesjs,artf/grapesjs,QuorumDMS/grapesjs,QuorumDMS/grapesjs | ---
+++
@@ -1,5 +1,9 @@
module.exports = {
stylePrefix: 'nv-',
+
+ // Specify where to render layers on init, string (query) or HTMLElement
+ // With the empty value, layers won't be visible
+ el: '',
// Enable/Disable globally the possibility to sort layers
sortable: 1, |
6b93ddc8d3cb5f12490d58047e77deceec9aab7b | src/Console.js | src/Console.js | import React from 'react';
const { string, bool } = React.PropTypes;
const Console = (props) => {
if (props.log) {
console.log(props.log);
}
if (props.info) {
console.info(props.info);
}
if (props.error) {
console.error(props.error);
}
if (props.clear) {
console.clear();
}
return null;
};
Console.propTypes = {
log: string,
info: string,
error: string,
clear: bool,
};
Console.defaultProps = {
log: '',
info: '',
error: '',
clear: false,
};
export default Console;
| import React from 'react';
const { array, string, bool, shape } = React.PropTypes;
const Console = (props) => {
if (props.assert.assertion) {
console.assert(props.assert.assertion, props.assert.message);
}
if (props.clear) {
console.clear();
}
if (props.count) {
console.count(props.count);
}
if (props.error) {
console.error(props.error);
}
if (props.group) {
console.group();
}
if (props.groupColapsed) {
console.groupCollapsed();
}
if (props.groupEnd) {
console.groupEnd();
}
if (props.info) {
console.info(props.info);
}
if (props.log) {
console.log(props.log);
}
if (props.table.data.length) {
console.table(props.table.data, props.table.columns);
}
if (props.time) {
console.time(props.time);
}
if (props.timeEnd) {
console.timeEnd(props.timeEnd);
}
if (props.trace) {
console.trace();
}
if (props.warn) {
console.warn(props.warn);
}
return null;
};
Console.propTypes = {
assert: shape({
assertion: bool,
message: string,
}),
clear: bool,
count: string,
error: string,
group: bool,
groupColapsed: bool,
groupEnd: bool,
info: string,
log: string,
table: shape({
data: array,
columns: array,
}),
time: string,
timeEnd: string,
trace: bool,
warn: string,
};
Console.defaultProps = {
assert: {
assertion: false,
message: '',
},
clear: false,
count: '',
error: '',
group: false,
groupColapsed: false,
groupEnd: false,
info: '',
log: '',
table: {
data: [],
columns: [],
},
time: '',
timeEnd: '',
trace: false,
warn: '',
};
export default Console;
| Add missing functions from console api | Add missing functions from console api
| JavaScript | mit | sgnh/react-console-wrapper | ---
+++
@@ -1,39 +1,111 @@
import React from 'react';
-const { string, bool } = React.PropTypes;
+const { array, string, bool, shape } = React.PropTypes;
const Console = (props) => {
- if (props.log) {
- console.log(props.log);
+ if (props.assert.assertion) {
+ console.assert(props.assert.assertion, props.assert.message);
+ }
+
+ if (props.clear) {
+ console.clear();
+ }
+
+ if (props.count) {
+ console.count(props.count);
+ }
+
+ if (props.error) {
+ console.error(props.error);
+ }
+
+ if (props.group) {
+ console.group();
+ }
+
+ if (props.groupColapsed) {
+ console.groupCollapsed();
+ }
+
+ if (props.groupEnd) {
+ console.groupEnd();
}
if (props.info) {
console.info(props.info);
}
- if (props.error) {
- console.error(props.error);
+ if (props.log) {
+ console.log(props.log);
}
- if (props.clear) {
- console.clear();
+ if (props.table.data.length) {
+ console.table(props.table.data, props.table.columns);
+ }
+
+ if (props.time) {
+ console.time(props.time);
+ }
+
+ if (props.timeEnd) {
+ console.timeEnd(props.timeEnd);
+ }
+
+ if (props.trace) {
+ console.trace();
+ }
+
+ if (props.warn) {
+ console.warn(props.warn);
}
return null;
};
Console.propTypes = {
+ assert: shape({
+ assertion: bool,
+ message: string,
+ }),
+ clear: bool,
+ count: string,
+ error: string,
+ group: bool,
+ groupColapsed: bool,
+ groupEnd: bool,
+ info: string,
log: string,
- info: string,
- error: string,
- clear: bool,
+ table: shape({
+ data: array,
+ columns: array,
+ }),
+ time: string,
+ timeEnd: string,
+ trace: bool,
+ warn: string,
};
Console.defaultProps = {
+ assert: {
+ assertion: false,
+ message: '',
+ },
+ clear: false,
+ count: '',
+ error: '',
+ group: false,
+ groupColapsed: false,
+ groupEnd: false,
+ info: '',
log: '',
- info: '',
- error: '',
- clear: false,
+ table: {
+ data: [],
+ columns: [],
+ },
+ time: '',
+ timeEnd: '',
+ trace: false,
+ warn: '',
};
export default Console; |
176ab76963aac99fe1185901dd3b9b9087fa9304 | redpen-cli/sample/js/test/validator-js-test.js | redpen-cli/sample/js/test/validator-js-test.js | /*
tests validator.js implementation.
steps to run this test:
1. install mocha
$ npm install -g mocha
2. run RedPen in server mode
$ cd $REDPEN_HOME/bin
$ ./redpen-server
3. rename validator.js.example to enable the validator implementation
$ cd $REDPEN_HOME/sample
$ mv validator.js.example validator.js
4. run mocha
$ cd $REDPEN_HOME/sample
$ mocha
*/
var assert = require('assert');
var redpen = require('./redpen');
describe('redpen-test', function () {
it('test validator.js', function (done) {
var request = {
"document": "This sentence contains toolongword. This sentence doesn't contain too long word.",
"format": "json2",
"documentParser": "PLAIN",
"config": {
"lang": "en",
"validators": {
"JavaScript": {}
}
}
};
var assertion = function (errorSentences) {
// only one sentence contains error
assert.equal(errorSentences.length, 1);
firstErrorSentence = errorSentences[0];
assert.equal(firstErrorSentence.sentence, 'This sentence contains toolongword.');
// there is one too word exceeds 10 chalacteres long
assert.equal(1, firstErrorSentence.errors.length);
assert.equal('[validator.js] word [toolongword.] is too long. length: 12', firstErrorSentence.errors[0].message);
done();
};
redpen.callRedPen(request, assertion);
});
});
| /*
tests validator.js implementation.
steps to run this test:
1. install mocha
$ npm install -g mocha
2. run RedPen in server mode
$ cd $REDPEN_HOME/bin
$ ./redpen-server
3. rename validator.js.example to enable the validator implementation
$ cd $REDPEN_HOME/js
$ mv validator.js.example validator.js
4. run mocha
$ cd $REDPEN_HOME/js
$ mocha
*/
var assert = require('assert');
var redpen = require('./redpen');
describe('redpen-test', function () {
it('test validator.js', function (done) {
var request = {
"document": "This sentence contains toolongword. This sentence doesn't contain too long word.",
"format": "json2",
"documentParser": "PLAIN",
"config": {
"lang": "en",
"validators": {
"JavaScript": {}
}
}
};
var assertion = function (errorSentences) {
// only one sentence contains error
assert.equal(errorSentences.length, 1);
firstErrorSentence = errorSentences[0];
assert.equal(firstErrorSentence.sentence, 'This sentence contains toolongword.');
// there is one too word exceeds 10 chalacteres long
assert.equal(1, firstErrorSentence.errors.length);
assert.equal('[validator.js] word [toolongword.] is too long. length: 12', firstErrorSentence.errors[0].message);
done();
};
redpen.callRedPen(request, assertion);
});
});
| Correct directory names in test sample of javascript validator | Correct directory names in test sample of javascript validator
| JavaScript | apache-2.0 | gerryhocks/redpen,redpen-cc/redpen,recruit-tech/redpen,gerryhocks/redpen,redpen-cc/redpen,recruit-tech/redpen,recruit-tech/redpen,kenhys/redpen,redpen-cc/redpen,recruit-tech/redpen,gerryhocks/redpen,kenhys/redpen,kenhys/redpen,redpen-cc/redpen,redpen-cc/redpen,gerryhocks/redpen,kenhys/redpen | ---
+++
@@ -10,11 +10,11 @@
$ ./redpen-server
3. rename validator.js.example to enable the validator implementation
- $ cd $REDPEN_HOME/sample
+ $ cd $REDPEN_HOME/js
$ mv validator.js.example validator.js
4. run mocha
- $ cd $REDPEN_HOME/sample
+ $ cd $REDPEN_HOME/js
$ mocha
*/ |
58712600d1f6c1800ec8a036e27d9d4b4ac97829 | src/firefox/lib/main.js | src/firefox/lib/main.js | var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var { ToggleButton } = require("sdk/ui/button/toggle");
var btn_config = {};
var btn;
function tabToggle(tab) {
if (btn.state('window').checked) {
tab.attach({
contentScriptFile: data.url('embed.js')
});
} else {
tab.attach({
contentScript: [
'var s = document.createElement("script");',
's.setAttribute("src", "' + data.url('destroy.js') + '");',
'document.body.appendChild(s);'
]
});
}
}
btn_config = {
id: "hypothesis",
label: "Annotate",
icon: {
"18": './images/sleeping_18.png',
"32": './images/sleeping_32.png',
"36": './images/sleeping_36.png',
"64": './images/sleeping_64.png'
},
onClick: function(state) {
tabToggle(tabs.activeTab)
}
};
if (undefined === ToggleButton) {
btn = require("sdk/widget").Widget(btn_config);
} else {
btn = ToggleButton(btn_config);
}
tabs.on('open', function(tab) {
tab.on('activate', tabToggle);
tab.on('pageshow', tabToggle);
});
| const data = require("sdk/self").data;
const tabs = require("sdk/tabs");
const { ToggleButton } = require("sdk/ui/button/toggle");
var btn_config = {};
var btn;
function tabToggle(tab) {
if (btn.state('window').checked) {
tab.attach({
contentScriptFile: data.url('embed.js')
});
} else {
tab.attach({
contentScript: [
'var s = document.createElement("script");',
's.setAttribute("src", "' + data.url('destroy.js') + '");',
'document.body.appendChild(s);'
]
});
}
}
btn_config = {
id: "hypothesis",
label: "Annotate",
icon: {
"18": './images/sleeping_18.png',
"32": './images/sleeping_32.png',
"36": './images/sleeping_36.png',
"64": './images/sleeping_64.png'
},
onClick: function(state) {
tabToggle(tabs.activeTab)
}
};
if (undefined === ToggleButton) {
btn = require("sdk/widget").Widget(btn_config);
} else {
btn = ToggleButton(btn_config);
}
tabs.on('open', function(tab) {
tab.on('activate', tabToggle);
tab.on('pageshow', tabToggle);
});
| Use const instead of var | Use const instead of var
| JavaScript | bsd-2-clause | project-star/browser-extension,hypothesis/browser-extension,hypothesis/browser-extension,project-star/browser-extension,project-star/browser-extension,hypothesis/browser-extension,hypothesis/browser-extension | ---
+++
@@ -1,6 +1,6 @@
-var data = require("sdk/self").data;
-var tabs = require("sdk/tabs");
-var { ToggleButton } = require("sdk/ui/button/toggle");
+const data = require("sdk/self").data;
+const tabs = require("sdk/tabs");
+const { ToggleButton } = require("sdk/ui/button/toggle");
var btn_config = {};
var btn;
|
6584a037f09b832c8f12b1b1dccf6d90b8a84fd7 | test/fixtures/values.js | test/fixtures/values.js | const buffer = Buffer.from('This is a test string');
const base64 = buffer.toString('base64');
const hexString = buffer.toString('hex');
module.exports = {
buffer,
base64,
hexString
};
| const buffer = Buffer.from([0x72, 0x98, 0x4f, 0x96, 0x75, 0x03, 0xcd, 0x28, 0x38, 0xbf]);
const base64 = buffer.toString('base64');
const hexString = buffer.toString('hex');
module.exports = {
buffer,
base64,
hexString
};
| Use non utf8 buffer to help catch decoding errors e.g When using a utf8 string buffer we could store the buffer as a utf8 string and tests would pass. If you then tried to encode/decode an image you'd get incorrect results. | Use non utf8 buffer to help catch decoding errors
e.g When using a utf8 string buffer we could store the buffer as a utf8 string and tests would pass. If you then tried to encode/decode an image you'd get incorrect results.
| JavaScript | mit | lukechilds/base64-async | ---
+++
@@ -1,4 +1,4 @@
-const buffer = Buffer.from('This is a test string');
+const buffer = Buffer.from([0x72, 0x98, 0x4f, 0x96, 0x75, 0x03, 0xcd, 0x28, 0x38, 0xbf]);
const base64 = buffer.toString('base64');
const hexString = buffer.toString('hex');
|
157f799da26ef488802e98393f0f3cc1062a9436 | config.js | config.js | // These URL paths will be transformed to CN mirrors.
var mirrors = {
"//developers.google.com" : "//developers.google.cn",
"//firebase.google.com" : "//firebase.google.cn",
"//developer.android.com" : "//developer.android.google.cn",
"//angular.io" : "//angular.cn",
"google.com/maps" : "google.cn/maps",
}
// These URL paths are not available on CN mirrors, therefore won't be transformed.
var whitelist = [
"//developers.google.com/groups",
"//developers.google.com/events",
"//firebase.google.com/support/contact/",
]
function mirrorUrl(url) {
// Check for whitelisting.
for (var key in whitelist) {
if (url.includes(whitelist[key])) {
return url;
}
}
// Check for mapping.
for (var key in mirrors) {
if (url.includes(key)) {
url = url.replace(key, mirrors[key]);
break;
}
}
return url;
}
| // These URL paths will be transformed to CN mirrors.
var mirrors = {
"//developers.google.com" : "//developers.google.cn",
"//firebase.google.com" : "//firebase.google.cn",
"//developer.android.com" : "//developer.android.google.cn",
"//angular.io" : "//angular.cn",
"//maps.google.com" : "//maps.google.cn",
"google.com/maps" : "google.cn/maps",
}
// These URL paths are not available on CN mirrors, therefore won't be transformed.
var whitelist = [
"//developers.google.com/groups",
"//developers.google.com/events",
"//firebase.google.com/support/contact/",
]
function mirrorUrl(url) {
// Check for whitelisting.
for (var key in whitelist) {
if (url.includes(whitelist[key])) {
return url;
}
}
// Check for mapping.
for (var key in mirrors) {
if (url.includes(key)) {
url = url.replace(key, mirrors[key]);
break;
}
}
return url;
}
| Add another Google Maps URL. | Add another Google Maps URL. | JavaScript | apache-2.0 | chenzhuo914/google-cn-devsites-extension | ---
+++
@@ -4,6 +4,7 @@
"//firebase.google.com" : "//firebase.google.cn",
"//developer.android.com" : "//developer.android.google.cn",
"//angular.io" : "//angular.cn",
+ "//maps.google.com" : "//maps.google.cn",
"google.com/maps" : "google.cn/maps",
}
|
42a9ef188422e5d9289b62c13129bcb8a3eeb741 | test/protractor-conf.js | test/protractor-conf.js | exports.config = {
allScriptsTimeout: 11000,
specs: [
'e2e/*.js'
],
capabilities: {
'browserName': 'chrome',
'phantomjs.binary.path': './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/bin/phantomjs',
'phantomjs.cli.args': ['--debug=true', '--webdriver', '--webdriver-logfile=webdriver.log', '--webdriver-loglevel=DEBUG']
},
baseUrl: 'http://localhost:8000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
| exports.config = {
allScriptsTimeout: 11000,
specs: [
'e2e/*.js'
],
capabilities: {
'browserName': 'chrome',
'phantomjs.binary.path': './node_modules/karma-phantomjs-launcher/node_modules/phantomjs/bin/phantomjs',
'phantomjs.cli.args': ['--debug=true', '--webdriver', '--webdriver-logfile=webdriver.log', '--webdriver-loglevel=DEBUG']
},
baseUrl: 'http://localhost:8000/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000,
onComplete: function(){
browser.driver.executeScript("return __coverage__;").then(function(val) {
fs.writeFileSync("./coverage/e2e/coverage.json", JSON.stringify(val));
});
}
}
};
| Add code coverage to protractor | Add code coverage to protractor
| JavaScript | mit | double16/switchmin-ng,double16/switchmin-ng | ---
+++
@@ -16,6 +16,11 @@
framework: 'jasmine',
jasmineNodeOpts: {
- defaultTimeoutInterval: 30000
+ defaultTimeoutInterval: 30000,
+ onComplete: function(){
+ browser.driver.executeScript("return __coverage__;").then(function(val) {
+ fs.writeFileSync("./coverage/e2e/coverage.json", JSON.stringify(val));
+ });
+ }
}
}; |
8b908f8adfb54e60e2886751bd67be645e1807c9 | src/jasmine.js | src/jasmine.js | /* eslint-env jasmine */
import { assertions } from 'redux-actions-assertions-js';
const toDispatchActions = () => {
return {
compare(action, expectedActions, done) {
assertions.toDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
}
};
};
const toNotDispatchActions = () => {
return {
compare(action, expectedActions, done) {
assertions.toNotDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
}
};
};
const toDispatchActionsWithState = () => {
return {
compare(action, state, expectedActions, done) {
assertions.toDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
}
};
};
const toNotDispatchActionsWithState = () => {
return {
compare(action, state, expectedActions, done) {
assertions.toNotDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
}
};
};
const matchers = {
toDispatchActions,
toNotDispatchActions,
toDispatchActionsWithState,
toNotDispatchActionsWithState
};
const registerAssertions = () => {
jasmine.addMatchers(matchers);
};
export {
registerAssertions,
matchers
};
| /* eslint-env jasmine */
import { assertions } from 'redux-actions-assertions-js';
function toDispatchActions() {
return {
compare(action, expectedActions, done) {
assertions.toDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
},
negativeCompare(action, expectedActions, done) {
assertions.toNotDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
}
};
}
function toNotDispatchActions() {
return {
compare(action, expectedActions, done) {
assertions.toNotDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
}
};
}
function toDispatchActionsWithState() {
return {
compare(action, state, expectedActions, done) {
assertions.toDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
},
negativeCompare(action, state, expectedActions, done) {
assertions.toNotDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
}
};
}
function toNotDispatchActionsWithState() {
return {
compare(action, state, expectedActions, done) {
assertions.toNotDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
}
};
}
const matchers = {
toDispatchActions,
toNotDispatchActions,
toDispatchActionsWithState,
toNotDispatchActionsWithState
};
function registerAssertions() {
jasmine.addMatchers(matchers);
}
export {
registerAssertions,
matchers
};
| Add support for negativeCompare, use function syntax | Add support for negativeCompare, use function syntax
| JavaScript | mit | redux-things/redux-actions-assertions,dmitry-zaets/redux-actions-assertions | ---
+++
@@ -1,41 +1,49 @@
/* eslint-env jasmine */
import { assertions } from 'redux-actions-assertions-js';
-const toDispatchActions = () => {
+function toDispatchActions() {
return {
compare(action, expectedActions, done) {
assertions.toDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
+ },
+ negativeCompare(action, expectedActions, done) {
+ assertions.toNotDispatchActions(action, expectedActions, done, done.fail);
+ return { pass: true };
}
};
-};
+}
-const toNotDispatchActions = () => {
+function toNotDispatchActions() {
return {
compare(action, expectedActions, done) {
assertions.toNotDispatchActions(action, expectedActions, done, done.fail);
return { pass: true };
}
};
-};
+}
-const toDispatchActionsWithState = () => {
+function toDispatchActionsWithState() {
return {
compare(action, state, expectedActions, done) {
assertions.toDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
+ },
+ negativeCompare(action, state, expectedActions, done) {
+ assertions.toNotDispatchActionsWithState(state, action, expectedActions, done, done.fail);
+ return { pass: true };
}
};
-};
+}
-const toNotDispatchActionsWithState = () => {
+function toNotDispatchActionsWithState() {
return {
compare(action, state, expectedActions, done) {
assertions.toNotDispatchActionsWithState(state, action, expectedActions, done, done.fail);
return { pass: true };
}
};
-};
+}
const matchers = {
toDispatchActions,
@@ -44,9 +52,9 @@
toNotDispatchActionsWithState
};
-const registerAssertions = () => {
+function registerAssertions() {
jasmine.addMatchers(matchers);
-};
+}
export {
registerAssertions, |
aa8f76eb6ce96023a96aa847b8e724cd6d18cd81 | src/components/Sass.js | src/components/Sass.js | let Preprocessor = require('./Preprocessor');
class Sass extends Preprocessor {
/**
* Required dependencies for the component.
*/
dependencies() {
this.requiresReload = true;
let dependencies = ['sass', 'sass-loader@7.*'];
if (Config.processCssUrls) {
dependencies.push('resolve-url-loader@2.3.1');
}
return dependencies;
}
/**
* Register the component.
*
* @param {*} src
* @param {string} output
* @param {Object} pluginOptions
* @param {Array} postCssPlugins
*/
register(src, output, pluginOptions = {}, postCssPlugins = []) {
return this.preprocess(
'sass',
src,
output,
this.pluginOptions(pluginOptions),
postCssPlugins
);
}
/**
* Build the plugin options for sass-loader.
*
* @param {Object} pluginOptions
* @returns {Object}
*/
pluginOptions(pluginOptions) {
return Object.assign(
{
precision: 8,
outputStyle: 'expanded',
implementation: () => require('sass')
},
pluginOptions,
{ sourceMap: true }
);
}
}
module.exports = Sass;
| let Preprocessor = require('./Preprocessor');
class Sass extends Preprocessor {
/**
* Required dependencies for the component.
*/
dependencies() {
this.requiresReload = true;
let dependencies = ['sass-loader@7.*'];
try {
require.resolve('node-sass');
dependencies.push('node-sass');
} catch (e) {
dependencies.push('sass');
}
if (Config.processCssUrls) {
dependencies.push('resolve-url-loader@2.3.1');
}
return dependencies;
}
/**
* Register the component.
*
* @param {*} src
* @param {string} output
* @param {Object} pluginOptions
* @param {Array} postCssPlugins
*/
register(src, output, pluginOptions = {}, postCssPlugins = []) {
return this.preprocess(
'sass',
src,
output,
this.pluginOptions(pluginOptions),
postCssPlugins
);
}
/**
* Build the plugin options for sass-loader.
*
* @param {Object} pluginOptions
* @returns {Object}
*/
pluginOptions(pluginOptions) {
return Object.assign(
{
precision: 8,
outputStyle: 'expanded',
implementation: () => require('sass')
},
pluginOptions,
{ sourceMap: true }
);
}
}
module.exports = Sass;
| Determine which sass package to install | Determine which sass package to install
| JavaScript | mit | JeffreyWay/laravel-mix | ---
+++
@@ -7,7 +7,15 @@
dependencies() {
this.requiresReload = true;
- let dependencies = ['sass', 'sass-loader@7.*'];
+ let dependencies = ['sass-loader@7.*'];
+
+ try {
+ require.resolve('node-sass');
+
+ dependencies.push('node-sass');
+ } catch (e) {
+ dependencies.push('sass');
+ }
if (Config.processCssUrls) {
dependencies.push('resolve-url-loader@2.3.1'); |
d22383b18b375f1b579ed0a6f0c1aad12cd7d2bd | src/containers/Todo.js | src/containers/Todo.js | import { PropTypes } from 'react'
import {connect} from 'react-redux'
import {updateTodo, deleteTodo, showDeleteButtonOnTodo} from 'actions/actionCreators'
import TodoPresentation from 'components/TodoPresentation/TodoPresentation'
const mapStateToProps = (state, {todo}) => {
return {
deleteButtonVisible: state.deleteButtonOnTodo === todo.id
}
}
const mapDispatchToProps = (dispatch, {todo}) => {
return {
onCompleted: () => {
dispatch(updateTodo(todo, {completed: !todo.completed}))
},
onDelete: () => {
dispatch(deleteTodo(todo))
},
onDeleteButtonShown: () => {
dispatch(showDeleteButtonOnTodo(todo.id))
},
onDeleteButtonHidden: () => {
dispatch(showDeleteButtonOnTodo(null))
}
}
}
const Todo = connect(mapStateToProps, mapDispatchToProps)(TodoPresentation)
Todo.propTypes = {
todo: PropTypes.object.isRequired
}
export default Todo
| import { PropTypes } from 'react'
import {connect} from 'react-redux'
import {updateTodo, deleteTodo, showDeleteButtonOnTodo} from 'actions/actionCreators'
import TodoPresentation from 'components/TodoPresentation/TodoPresentation'
const mapStateToProps = (state, {todo}) => {
return {
deleteButtonVisible: state.deleteButtonOnTodo === todo.id
}
}
const mapDispatchToProps = (dispatch, {todo}) => {
return {
onCompleted () {
dispatch(updateTodo(todo, {completed: !todo.completed}))
},
onDelete () {
dispatch(deleteTodo(todo))
},
onDeleteButtonShown () {
dispatch(showDeleteButtonOnTodo(todo.id))
},
onDeleteButtonHidden () {
dispatch(showDeleteButtonOnTodo(null))
}
}
}
const Todo = connect(mapStateToProps, mapDispatchToProps)(TodoPresentation)
Todo.propTypes = {
todo: PropTypes.object.isRequired
}
export default Todo
| Use object literal syntax in mapDispatchToProps | Use object literal syntax in mapDispatchToProps
| JavaScript | mit | stefanwille/react-todo,stefanwille/react-todo | ---
+++
@@ -12,19 +12,19 @@
const mapDispatchToProps = (dispatch, {todo}) => {
return {
- onCompleted: () => {
+ onCompleted () {
dispatch(updateTodo(todo, {completed: !todo.completed}))
},
- onDelete: () => {
+ onDelete () {
dispatch(deleteTodo(todo))
},
- onDeleteButtonShown: () => {
+ onDeleteButtonShown () {
dispatch(showDeleteButtonOnTodo(todo.id))
},
- onDeleteButtonHidden: () => {
+ onDeleteButtonHidden () {
dispatch(showDeleteButtonOnTodo(null))
}
} |
8854c7b43b617fe43694dcb015a016cfe6fa869d | sashimi-webapp/test/unit/specs/Content.spec.js | sashimi-webapp/test/unit/specs/Content.spec.js | import Vue from 'vue';
import Content from 'src/components/editor-viewer/Content';
describe('Content.vue', () => {
it('should render Editor component', () => {
const Constructor = Vue.extend(Content);
const vm = new Constructor().$mount();
expect(vm.$el.querySelector('.group .editor'))
.to.not.equal(null);
});
it('should render Viewer component', () => {
const Constructor = Vue.extend(Content);
const vm = new Constructor().$mount();
expect(vm.$el.querySelector('.group .viewer'))
.to.not.equal(null);
});
});
| import Vue from 'vue';
import Content from 'src/components/editor-viewer/Content';
const VIEWER_CONTAINER_ID = 'viewer-container';
describe('Content.vue', () => {
// A mock viewer-container DOM is needed for this test.
// It will be created before all the test are ran, and remove
// when all the tests are finished.
before(() => {
const mockContainer = document.createElement('DIV');
mockContainer.setAttribute('id', VIEWER_CONTAINER_ID);
document.body.appendChild(mockContainer);
});
after(() => {
const mockContainer = document.getElementById(VIEWER_CONTAINER_ID);
if (mockContainer) { mockContainer.remove(); }
});
it('should render Editor component', () => {
const Constructor = Vue.extend(Content);
const vm = new Constructor().$mount();
expect(vm.$el.querySelector('.group .editor'))
.to.not.equal(null);
});
it('should render Viewer component', () => {
const Constructor = Vue.extend(Content);
const vm = new Constructor().$mount();
expect(vm.$el.querySelector('.group .viewer'))
.to.not.equal(null);
});
});
| Fix Vue test which require the presence of viewer-element dom object | Fix Vue test which require the presence of viewer-element dom object
| JavaScript | mit | nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note | ---
+++
@@ -1,7 +1,23 @@
import Vue from 'vue';
import Content from 'src/components/editor-viewer/Content';
+const VIEWER_CONTAINER_ID = 'viewer-container';
+
describe('Content.vue', () => {
+ // A mock viewer-container DOM is needed for this test.
+ // It will be created before all the test are ran, and remove
+ // when all the tests are finished.
+ before(() => {
+ const mockContainer = document.createElement('DIV');
+ mockContainer.setAttribute('id', VIEWER_CONTAINER_ID);
+ document.body.appendChild(mockContainer);
+ });
+
+ after(() => {
+ const mockContainer = document.getElementById(VIEWER_CONTAINER_ID);
+ if (mockContainer) { mockContainer.remove(); }
+ });
+
it('should render Editor component', () => {
const Constructor = Vue.extend(Content);
const vm = new Constructor().$mount(); |
466f69074c3bfb76b05b9d487d0fb0b06cf0f17a | test/unit/karma.conf.js | test/unit/karma.conf.js | // This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
| // This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
browserNoActivityTimeout: 180000, // 3 mins
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
| Extend browser no activity timeout to 3 minutes. | Extend browser no activity timeout to 3 minutes.
| JavaScript | mit | sc0Vu/vuethwallet,sc0Vu/vue-ethwallet,sc0Vu/vuethwallet,sc0Vu/vue-ethwallet | ---
+++
@@ -8,6 +8,7 @@
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
+ browserNoActivityTimeout: 180000, // 3 mins
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'], |
c2e049dbab33af881c4942fed405c7eba4d986af | test/unit/kernelTest.js | test/unit/kernelTest.js | /*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var assert = require('assert');
var prepareConfig = require('../helpers/prepare-config');
var Kernel = require('../../lib/kernel');
describe('kernel load test', function() {
it('should load the kernel on a good config', function(done){
var config = prepareConfig(require('../data/basic-config'));
new Kernel(config, function(err) {
assert(!err);
done();
});
});
});
| /*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var assert = require('assert');
var prepareConfig = require('../helpers/prepare-config');
var Kernel = require('../../lib/kernel');
describe('kernel load test', function() {
it('should load the kernel on a good config', function(done){
this.timeout(10000);
var config = prepareConfig(require('../data/basic-config'));
new Kernel(config, function(err) {
assert(!err);
done();
});
});
});
| Add timeout for kernel boot test for travis. | Add timeout for kernel boot test for travis.
| JavaScript | artistic-2.0 | nearform/nscale-kernel,nearform/nscale-kernel | ---
+++
@@ -21,6 +21,7 @@
describe('kernel load test', function() {
it('should load the kernel on a good config', function(done){
+ this.timeout(10000);
var config = prepareConfig(require('../data/basic-config'));
new Kernel(config, function(err) {
assert(!err); |
3fbb2a32da8aacec98b52033736a3a38d18a6006 | src/components/Star.js | src/components/Star.js | import React from 'react';
import PropTypes from 'prop-types';
import FaStar from 'react-icons/fa/star';
import FaStarO from 'react-icons/fa/star-o';
const Star = ({ colored, ...props }) => (
<div {...props}>
{ colored ? <FaStar /> : <FaStarO /> }
</div>
);
Star.propTypes = {
colored: PropTypes.bool
}
export default Star; | import React from 'react';
import PropTypes from 'prop-types';
import FaStar from 'react-icons/fa/star';
import FaStarO from 'react-icons/fa/star-o';
const Star = ({ colored, fillColor, strokeColor, width = 14, height = 14, ...props }) => (
<div {...props}>
{ colored ?
<FaStar style={ fillColor ? { color: fillColor, width, height } : { width, height } } /> :
<FaStarO style={ strokeColor ? { color: strokeColor, width, height } : { width, height } } />
}
</div>
);
Star.propTypes = {
colored: PropTypes.bool,
fillColor: PropTypes.string,
strokeColor: PropTypes.string
}
export default Star; | Allow star fill and stroke color to be editted along with width and height | Allow star fill and stroke color to be editted along with width and height
| JavaScript | mit | danielzy95/mechanic-finder,danielzy95/mechanic-finder | ---
+++
@@ -4,14 +4,19 @@
import FaStar from 'react-icons/fa/star';
import FaStarO from 'react-icons/fa/star-o';
-const Star = ({ colored, ...props }) => (
+const Star = ({ colored, fillColor, strokeColor, width = 14, height = 14, ...props }) => (
<div {...props}>
- { colored ? <FaStar /> : <FaStarO /> }
+ { colored ?
+ <FaStar style={ fillColor ? { color: fillColor, width, height } : { width, height } } /> :
+ <FaStarO style={ strokeColor ? { color: strokeColor, width, height } : { width, height } } />
+ }
</div>
);
Star.propTypes = {
- colored: PropTypes.bool
+ colored: PropTypes.bool,
+ fillColor: PropTypes.string,
+ strokeColor: PropTypes.string
}
export default Star; |
fa7eb2766beab22ba22ac38caaee4d592eddd99d | src/components/View.js | src/components/View.js | // @flow
// @jsx glam
import React from 'react';
import glam from 'glam';
import { Div, Img } from '../primitives';
import { type PropsWithStyles } from '../types';
import { className } from '../utils';
import { getSource } from './component-helpers';
import componentBaseClassNames from './componentBaseClassNames';
type Props = PropsWithStyles & {
data: Object,
isFullscreen: boolean,
isModal: boolean,
};
export const viewCSS = () => ({
lineHeight: 0,
position: 'relative',
textAlign: 'center',
});
const viewBaseClassName = componentBaseClassNames.View;
const View = (props: Props) => {
const { data, formatters, getStyles, index, isFullscreen, isModal } = props;
const innerProps = {
alt: formatters.getAltText({ data, index }),
src: getSource({ data, isFullscreen }),
};
return (
<Div
css={getStyles(viewBaseClassName, props)}
className={className(viewBaseClassName, { isFullscreen, isModal })}
>
<Img
{...innerProps}
className={className('view-image', { isFullscreen, isModal })}
css={{
height: 'auto',
maxHeight: '100vh',
maxWidth: '100vw',
userSelect: 'none',
}}
/>
</Div>
);
};
export default View;
| // @flow
// @jsx glam
import React from 'react';
import glam from 'glam';
import { Div, Img } from '../primitives';
import { type PropsWithStyles } from '../types';
import { className } from '../utils';
import { getSource } from './component-helpers';
import componentBaseClassNames from './componentBaseClassNames';
type Props = PropsWithStyles & {
data: Object,
isFullscreen: boolean,
isModal: boolean,
};
export const viewCSS = () => ({
lineHeight: 0,
position: 'relative',
textAlign: 'center',
});
const viewBaseClassName = componentBaseClassNames.View;
const View = (props: Props) => {
const { data, formatters, getStyles, index, isFullscreen, isModal } = props;
const innerProps = {
alt: formatters.getAltText({ data, index }),
src: getSource({ data, isFullscreen }),
};
return (
<Div
css={getStyles(viewBaseClassName, props)}
className={className(viewBaseClassName, { isFullscreen, isModal })}
>
<Img
{...innerProps}
className={className('view-image', { isFullscreen, isModal })}
css={{
height: 'auto',
maxHeight: '100%',
maxWidth: '100%',
userSelect: 'none',
}}
/>
</Div>
);
};
export default View;
| Fix oversized images in carousel component | :ambulance: Fix oversized images in carousel component
| JavaScript | mit | jossmac/react-images | ---
+++
@@ -40,8 +40,8 @@
className={className('view-image', { isFullscreen, isModal })}
css={{
height: 'auto',
- maxHeight: '100vh',
- maxWidth: '100vw',
+ maxHeight: '100%',
+ maxWidth: '100%',
userSelect: 'none',
}}
/> |
c458350df358e796e9d7848f068d42c15d709729 | src/cg-inject.js | src/cg-inject.js | (function (ng) {
'use strict';
var $inject = function (cls, self, args) {
var i;
var key;
var str;
var func;
var depNames = [];
var deps = [];
var l = cls.$inject.length;
for (i = 0; i < l; i++) {
key = '_' + cls.$inject[i];
self[key] = args[i];
}
for (key in self) {
if (typeof self[key] === 'function') {
func = self[key];
str = func.toString();
// Skip functions with dependency injection not enabled.
if (str.indexOf('/* $inject: enabled */') === -1) continue;
// List of parameter names in the function signature.
depNames = str.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].split(',');
// Map the dependency names to the actual dependencies.
args = depNames.map(function (name) {
return self['_' + name.trim()];
});
// Add the "this" value to the arguments list.
args.unshift(func);
self[key] = func.bind.apply(func, args);
}
}
};
ng.module('cg.inject', [])
.service('$inject', $inject);
})(angular);
| (function (ng) {
'use strict';
/**
* Angular.js utility for cleaner dependency injection.
*/
var $inject = function (cls, self, args) {
var i;
var key;
var str;
var func;
var depNames = [];
var deps = [];
var l = cls.$inject.length;
// Inject all dependencies into the self reference.
for (i = 0; i < l; i++) {
key = '_' + cls.$inject[i];
self[key] = args[i];
}
for (key in cls.prototype) {
if (typeof cls.prototype[key] === 'function') {
func = cls.prototype[key];
str = func.toString();
// List of dependencies.
depNames = str.match(/\/\*\s*\$inject:([^*]+)/);
// Skip methods without the $inject comment.
if (depNames.length < 2) continue;
depNames = depNames[1].split(',');
// Map the dependency names to the actual dependencies.
args = depNames.map(function (name) {
return self['_' + name.trim()];
});
// Add the "this" value to the arguments list.
args.unshift(func);
self[key] = func.bind.apply(func, args);
}
}
};
var $injectService = function () {
return $inject;
};
ng.module('cg.inject', [])
.factory('$inject', $injectService);
})(angular);
| Add $inject comment for DI in methods | Add $inject comment for DI in methods
| JavaScript | mit | ngonzalvez/cg-inject | ---
+++
@@ -1,6 +1,9 @@
(function (ng) {
'use strict';
+ /**
+ * Angular.js utility for cleaner dependency injection.
+ */
var $inject = function (cls, self, args) {
var i;
var key;
@@ -10,21 +13,24 @@
var deps = [];
var l = cls.$inject.length;
+ // Inject all dependencies into the self reference.
for (i = 0; i < l; i++) {
key = '_' + cls.$inject[i];
self[key] = args[i];
}
- for (key in self) {
- if (typeof self[key] === 'function') {
- func = self[key];
+ for (key in cls.prototype) {
+ if (typeof cls.prototype[key] === 'function') {
+ func = cls.prototype[key];
str = func.toString();
- // Skip functions with dependency injection not enabled.
- if (str.indexOf('/* $inject: enabled */') === -1) continue;
+ // List of dependencies.
+ depNames = str.match(/\/\*\s*\$inject:([^*]+)/);
- // List of parameter names in the function signature.
- depNames = str.match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].split(',');
+ // Skip methods without the $inject comment.
+ if (depNames.length < 2) continue;
+
+ depNames = depNames[1].split(',');
// Map the dependency names to the actual dependencies.
args = depNames.map(function (name) {
@@ -39,6 +45,10 @@
}
};
+ var $injectService = function () {
+ return $inject;
+ };
+
ng.module('cg.inject', [])
- .service('$inject', $inject);
+ .factory('$inject', $injectService);
})(angular); |
0fe4bb704f77c8c966b3adacfdad472b37181259 | src/query/formatter.js | src/query/formatter.js | const Formatter = require('knex/lib/formatter');
class FormatterSOQL extends Formatter {
wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
return this._wrapString(`${value}`);
}
outputQuery(compiled) {
let sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select') {
sql = `(${sql})`;
if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
}
}
return sql;
}
}
module.exports = FormatterSOQL;
| const Formatter = require('knex/lib/formatter');
class FormatterSOQL extends Formatter {
wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
// save compatibility with older knex.js versions
return (this.wrapString || this._wrapString).call(this, `${value}`);
}
outputQuery(compiled) {
let sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select') {
sql = `(${sql})`;
if (compiled.as) return this.alias(sql, this.wrap(compiled.as));
}
}
return sql;
}
}
module.exports = FormatterSOQL;
| Support for wrapString in newer knex versions | Support for wrapString in newer knex versions
| JavaScript | mit | jsarafajr/knex-soql | ---
+++
@@ -10,7 +10,8 @@
if (raw) return raw;
if (typeof value === 'number') return value;
- return this._wrapString(`${value}`);
+ // save compatibility with older knex.js versions
+ return (this.wrapString || this._wrapString).call(this, `${value}`);
}
outputQuery(compiled) { |
20a1a979313ba7a3840d208c921d527176aadc83 | src/goo/fsmpack/statemachine/actions/TagAction.js | src/goo/fsmpack/statemachine/actions/TagAction.js | define([
'goo/fsmpack/statemachine/actions/Action',
'goo/entities/components/ProximityComponent'
],
/** @lends */
function(
Action,
ProximityComponent
) {
'use strict';
function TagAction(/*id, settings*/) {
Action.apply(this, arguments);
}
TagAction.prototype = Object.create(Action.prototype);
TagAction.prototype.constructor = TagAction;
TagAction.external = {
name: 'Tag',
type: 'collision',
description: 'Sets a tag on the entity. Use tags to be able to capture collision events with the \'Collides\' action',
parameters: [{
name: 'Tag',
key: 'tag',
type: 'dropdown',
description: 'Checks for collisions with other ojects having this tag',
'default': 'red',
options: ['red', 'blue', 'green', 'yellow']
}],
transitions: []
};
TagAction.prototype._run = function (fsm) {
var entity = fsm.getOwnerEntity();
if (entity.proximityComponent) {
if (entity.proximityComponent.tag !== this.tag) {
entity.clearComponent('ProximityComponent');
entity.setComponent(new ProximityComponent(this.tag));
}
} else {
entity.setComponent(new ProximityComponent(this.tag));
}
};
return TagAction;
}); | define([
'goo/fsmpack/statemachine/actions/Action',
'goo/entities/components/ProximityComponent'
],
/** @lends */
function(
Action,
ProximityComponent
) {
'use strict';
function TagAction(/*id, settings*/) {
Action.apply(this, arguments);
}
TagAction.prototype = Object.create(Action.prototype);
TagAction.prototype.constructor = TagAction;
TagAction.external = {
name: 'Tag',
type: 'collision',
description: 'Sets a tag on the entity. Use tags to be able to capture collision events with the \'Collides\' action',
parameters: [{
name: 'Tag',
key: 'tag',
type: 'dropdown',
description: 'Checks for collisions with other ojects having this tag',
'default': 'red',
options: ['red', 'blue', 'green', 'yellow']
}],
transitions: []
};
TagAction.prototype._run = function (fsm) {
var entity = fsm.getOwnerEntity();
if (entity.proximityComponent) {
if (entity.proximityComponent.tag !== this.tag) {
entity.clearComponent('ProximityComponent');
entity.setComponent(new ProximityComponent(this.tag));
}
} else {
entity.setComponent(new ProximityComponent(this.tag));
}
};
TagAction.prototype.cleanup = function (fsm) {
var entity = fsm.getOwnerEntity();
entity.clearComponent('ProximityComponent');
};
return TagAction;
}); | Fix for tags not being cleaned up | Fix for tags not being cleaned up
| JavaScript | mit | GooTechnologies/goojs,GooTechnologies/goojs,GooTechnologies/goojs | ---
+++
@@ -43,5 +43,10 @@
}
};
+ TagAction.prototype.cleanup = function (fsm) {
+ var entity = fsm.getOwnerEntity();
+ entity.clearComponent('ProximityComponent');
+ };
+
return TagAction;
}); |
39c39af8e3d0ef2d74b11973c6ab79e7891a9578 | src/js/components/profile/OtherProfileDataList.js | src/js/components/profile/OtherProfileDataList.js | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ProfileData from './ProfileData'
export default class OtherProfileDataList extends Component {
static propTypes = {
profileWithMetadata: PropTypes.array.isRequired,
metadata : PropTypes.object.isRequired,
};
render() {
const {profileWithMetadata, metadata} = this.props;
let lines = [];
profileWithMetadata.forEach(
category => {
if (Object.keys(category.fields).length === 0 || !Object.keys(category.fields).some(profileDataKey => category.fields[profileDataKey].value)) {
return;
}
lines.push(<div key={category.label} className="profile-category"><h3>{category.label}</h3></div>);
Object.keys(category.fields).forEach(
profileDataKey => {
if (category.fields[profileDataKey].value && metadata[profileDataKey].visible !== false) {
lines.push(<ProfileData key={profileDataKey} name={category.fields[profileDataKey].text} value={category.fields[profileDataKey].value} forceLong={category.fields[profileDataKey].type === 'textarea'}/>);
}
});
});
return (
<div className="profile-data-list">
{lines}
</div>
);
}
}
| import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ProfileData from './ProfileData'
export default class OtherProfileDataList extends Component {
static propTypes = {
profileWithMetadata: PropTypes.array.isRequired,
metadata : PropTypes.object.isRequired,
};
render() {
const {profileWithMetadata, metadata} = this.props;
let lines = [];
profileWithMetadata.forEach(
category => {
if (Object.keys(category.fields).length === 0 || !Object.keys(category.fields).some(profileDataKey => category.fields[profileDataKey].value)) {
return;
}
lines.push(<div key={category.label} className="profile-category"><h3>{category.label}</h3></div>);
Object.keys(category.fields).forEach(
profileDataKey => {
if (category.fields[profileDataKey].value && metadata[profileDataKey].hidden !== true) {
lines.push(<ProfileData key={profileDataKey} name={category.fields[profileDataKey].text} value={category.fields[profileDataKey].value} forceLong={category.fields[profileDataKey].type === 'textarea'}/>);
}
});
});
return (
<div className="profile-data-list">
{lines}
</div>
);
}
}
| Enable hidden metadata option on other people´s profile | QS-1486: Enable hidden metadata option on other people´s profile
| JavaScript | agpl-3.0 | nekuno/client,nekuno/client | ---
+++
@@ -20,7 +20,7 @@
lines.push(<div key={category.label} className="profile-category"><h3>{category.label}</h3></div>);
Object.keys(category.fields).forEach(
profileDataKey => {
- if (category.fields[profileDataKey].value && metadata[profileDataKey].visible !== false) {
+ if (category.fields[profileDataKey].value && metadata[profileDataKey].hidden !== true) {
lines.push(<ProfileData key={profileDataKey} name={category.fields[profileDataKey].text} value={category.fields[profileDataKey].value} forceLong={category.fields[profileDataKey].type === 'textarea'}/>);
}
}); |
ddd97429877bf574098d86b63f60933b7e9fe66b | src/reducers/Recipes.js | src/reducers/Recipes.js | import { ADD_RECIPE, EDIT_RECIPE, REMOVE_RECIPE } from '../actions';
import { v4 } from 'uuid';
export const defaultRecipes = [
{
titleDetails: {
title: 'Pumpkin Pie',
servings: '4',
allergens: 'Eggs, Milk'
},
ingredients: [
{ name: 'Pumpkin Puree'},
{ name: 'Sweetened Condensed Milk' },
{ name: 'Eggs' },
{ name: 'Pumpkin Pie Spice' },
{ name: 'Pie Crust'}
],
id: v4()
},
{
titleDetails: {
title: 'Spaghetti',
ingredients: 'Noodles, Pasta Sauce, Meatballs',
},
ingredients: [
{ name: 'Noodles' },
{ name: 'Pasta Sauce' },
{ name: 'Meatballs' }
],
id: v4()
}
];
const Recipes = (state = defaultRecipes, action) => {
switch (action.type) {
case ADD_RECIPE:
return [
...state,
action.recipe
];
case EDIT_RECIPE:
return state.map(recipe => {
return recipe.id === action.id ? action.recipe : recipe;
});
case REMOVE_RECIPE:
return state.filter(recipe => recipe.id !== action.id);
default:
return state;
}
};
export default Recipes;
| import { ADD_RECIPE, EDIT_RECIPE, REMOVE_RECIPE } from '../actions';
import { v4 } from 'uuid';
export const defaultRecipes = [
{
titleDetails: {
title: 'Pumpkin Pie',
servings: '4',
allergens: 'Eggs, Milk'
},
ingredients: [
{ name: 'Pumpkin Puree'},
{ name: 'Sweetened Condensed Milk' },
{ name: 'Eggs' },
{ name: 'Pumpkin Pie Spice' },
{ name: 'Pie Crust'}
],
id: v4()
},
{
titleDetails: {
title: 'Spaghetti',
servings: '4',
allergens: 'Tomatoes'
},
ingredients: [
{ name: 'Noodles' },
{ name: 'Pasta Sauce' },
{ name: 'Meatballs' }
],
id: v4()
}
];
const Recipes = (state = defaultRecipes, action) => {
switch (action.type) {
case ADD_RECIPE:
return [
...state,
action.recipe
];
case EDIT_RECIPE:
return state.map(recipe => {
return recipe.id === action.id ? action.recipe : recipe;
});
case REMOVE_RECIPE:
return state.filter(recipe => recipe.id !== action.id);
default:
return state;
}
};
export default Recipes;
| Update Spaghetti default recipe to have servings and allergens. | Update Spaghetti default recipe to have servings and allergens.
| JavaScript | mit | phuchle/recipeas,phuchle/recipeas | ---
+++
@@ -20,7 +20,8 @@
{
titleDetails: {
title: 'Spaghetti',
- ingredients: 'Noodles, Pasta Sauce, Meatballs',
+ servings: '4',
+ allergens: 'Tomatoes'
},
ingredients: [
{ name: 'Noodles' }, |
62d5b3a311971c3cab5e7c903387ef572739a86a | js/Controllers.js | js/Controllers.js | //placing both controllers her b/c short program, otherwise would make partial
Todos.TodosController = Ember.ArrayController.extend ({
actions: {
createNewTodo: function() {
var newVal = this.get('newTodo'); // gets new todo Val
var todo = this.store.createRecord('todo' , { //Creates a new todo type
val: newVal , // gets new val
completed: false // sets to false completed
});
this.set('newtodo', ''); // set new todo to blank and save prev value to list
todo.save();
} ,
clearCompleted: function() {
var completed = this.filterBy('completed', true);//find all TRUE completed items
completed.invoke('deleteRecord'); //invoke this deletedRecord on all TRUE completed
completed.invoke('save'); // Save the view with after deleted TRUE completed items
}
}
});
Todos.TodoController = Ember.ObjectController.extend({
//Will define actions that can happen to the object
actions: {
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
}
}
}); | //placing both controllers her b/c short program, otherwise would make partial
Todos.TodosController = Ember.ArrayController.extend ({
actions: {
createNewTodo: function() {
var newVal = this.get('newTodo'); // gets new todo Val
var todo = this.store.createRecord('todo' , { //Creates a new todo type
val: newVal , // gets new val
completed: false // sets to false completed
});
this.set('newTodo', ''); // set new todo to blank and save prev value to list
todo.save();
} ,
clearCompleted: function() {
var completed = this.filterBy('completed', true);//find all TRUE completed items
completed.invoke('deleteRecord'); //invoke this deletedRecord on all TRUE completed
completed.invoke('save'); // Save the view with after deleted TRUE completed items
}
}
});
Todos.TodoController = Ember.ObjectController.extend({
//Will define actions that can happen to the object
actions: {
removeTodo: function () {
var todo = this.get('model');
todo.deleteRecord();
todo.save();
}
}
}); | Clear input after submit now functinal | Clear input after submit now functinal
| JavaScript | mit | mema82/TheAftermath,mema82/TheAftermath | ---
+++
@@ -8,7 +8,7 @@
val: newVal , // gets new val
completed: false // sets to false completed
});
- this.set('newtodo', ''); // set new todo to blank and save prev value to list
+ this.set('newTodo', ''); // set new todo to blank and save prev value to list
todo.save();
} ,
clearCompleted: function() { |
34c43896fa91a3b4d90632d380a0d985ba7f8744 | lib/logger.js | lib/logger.js | var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG: ';
}
this.util.log(type + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
| var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG';
}
this.util.log(type + ": " + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
| Tweak logging to add space and colon between type and msg | Tweak logging to add space and colon between type and msg
| JavaScript | mit | cit-lab/statsd,Mindera/statsd,aronatkins/statsd,Yelp/statsd,Yelp/statsd,roflmao/statsd,joshughes/statsd,blurredbits/statsd,sax/statsd,pagerinc/statsd,jmptrader/statsd,ShalomCohen/statsd,DataDog/statsd,cit-lab/statsd,AdamMagaluk/statsd-cloudwatch,jxqlovejava/statsd,Charlesdong/statsd,omniti-labs/statsd,cit-lab/statsd,blurredbits/statsd,zzzbit/statsd,omniti-labs/statsd,bartoszcisek/statsd,kickstarter/statsd,kickstarter/statsd,tuxinaut/statsd,cit-lab/statsd,kickstarter/statsd,abhi1021/statsd,kickstarter/statsd,easybiblabs/statsd,abhi1021/statsd,tsheasha/statsd,sax/statsd,ShalomCohen/statsd,AdamMagaluk/statsd-cloudwatch,roflmao/statsd,MichaelLiZhou/statsd,jxqlovejava/statsd,abhi1021/statsd,roflmao/statsd,roflmao/statsd,ShalomCohen/statsd,Mindera/statsd,Charlesdong/statsd,crashlytics/statsd,mdobson/link-statsd-elasticsearch,rex/statsd,sax/statsd,easybiblabs/statsd,crashlytics/statsd,aronatkins/statsd,joshughes/statsd,sdgdsffdsfff/statsd,DataDog/statsd,sax/statsd,etsy/statsd,VivienBarousse/statsd,ScottKaiGu/statsd,jmptrader/statsd,Yelp/statsd,abhi1021/statsd,kickstarter/statsd,DataDog/statsd,easybiblabs/statsd,ShalomCohen/statsd,abhi1021/statsd,ScottKaiGu/statsd,joshughes/statsd,joshughes/statsd,joshughes/statsd,roflmao/statsd,mdobson/link-statsd-elasticsearch,Yelp/statsd,AdamMagaluk/statsd-cloudwatch,pagerinc/statsd,aronatkins/statsd,crashlytics/statsd,aronatkins/statsd,tuxinaut/statsd,omniti-labs/statsd,abhi1021/statsd,DataDog/statsd,kickstarter/statsd,VivienBarousse/statsd,hjhart/statsd,tuxinaut/statsd,VivienBarousse/statsd,zzzbit/statsd,cit-lab/statsd,jxqlovejava/statsd,omniti-labs/statsd,MichaelLiZhou/statsd,joshughes/statsd,jxqlovejava/statsd,sdgdsffdsfff/statsd,sax/statsd,kickstarter/statsd,blurredbits/statsd,bmhatfield/statsd,atsid/statsd,wyzssw/statsd,Yelp/statsd,jmptrader/statsd,Yelp/statsd,roflmao/statsd,VivienBarousse/statsd,jmptrader/statsd,sax/statsd,jmptrader/statsd,sdgdsffdsfff/statsd,aronatkins/statsd,DataDog/statsd,jxqlovejava/statsd,zzzbit/statsd,ShalomCohen/statsd,ShalomCohen/statsd,abhi1021/statsd,Yelp/statsd,jxqlovejava/statsd,DataDog/statsd,Mindera/statsd,sax/statsd,Yelp/statsd,zzzbit/statsd,sax/statsd,Charlesdong/statsd,jxqlovejava/statsd,hjhart/statsd,omniti-labs/statsd,blurredbits/statsd,DataDog/statsd,aronatkins/statsd,roflmao/statsd,ngpestelos/statsd,tuxinaut/statsd,Mindera/statsd,cit-lab/statsd,VivienBarousse/statsd,etsy/statsd,jasonchaffee/statsd,ngpestelos/statsd,blurredbits/statsd,jmptrader/statsd,tsheasha/statsd,omniti-labs/statsd,joshughes/statsd,wyzssw/statsd,jxqlovejava/statsd,mdobson/link-statsd-elasticsearch,rex/statsd,ShalomCohen/statsd,kickstarter/statsd,atsid/statsd,jasonchaffee/statsd,bmhatfield/statsd,Mindera/statsd,bmhatfield/statsd,VivienBarousse/statsd,abhi1021/statsd,pagerinc/statsd,aronatkins/statsd,roflmao/statsd,Mindera/statsd,tuxinaut/statsd,jasonchaffee/statsd,jxqlovejava/statsd,roflmao/statsd,jmptrader/statsd,Mindera/statsd,joshughes/statsd,blurredbits/statsd,cit-lab/statsd,cit-lab/statsd,etsy/statsd,wyzssw/statsd,tuxinaut/statsd,VivienBarousse/statsd,atsid/statsd,blurredbits/statsd,tuxinaut/statsd,jmptrader/statsd,cit-lab/statsd,Mindera/statsd,tuxinaut/statsd,sax/statsd,omniti-labs/statsd,blurredbits/statsd,Yelp/statsd,VivienBarousse/statsd,rex/statsd,tuxinaut/statsd,bartoszcisek/statsd,DataDog/statsd,DataDog/statsd,ngpestelos/statsd,zzzbit/statsd,MichaelLiZhou/statsd,joshughes/statsd,ShalomCohen/statsd,zzzbit/statsd,zzzbit/statsd,zzzbit/statsd,tsheasha/statsd,omniti-labs/statsd,kickstarter/statsd,zzzbit/statsd,ScottKaiGu/statsd,Mindera/statsd,aronatkins/statsd,blurredbits/statsd,jmptrader/statsd,abhi1021/statsd,aronatkins/statsd,VivienBarousse/statsd,omniti-labs/statsd,ShalomCohen/statsd,bartoszcisek/statsd | ---
+++
@@ -18,9 +18,9 @@
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
- type = 'DEBUG: ';
+ type = 'DEBUG';
}
- this.util.log(type + msg);
+ this.util.log(type + ": " + msg);
} else {
if (!type) {
type = this.level |
0d4b6860d5756ee1c481abbbdce0be6ed663b315 | lib/routes.js | lib/routes.js | Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: {
initiatives: function() {
return Initiatives.find({}, {$sort: {votes: -1}});
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
initiative: Initiatives.findOne(this.params._id)
}
}
});
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
}); | Router.configure({
layoutTemplate: '_layout'
});
//From what I can tell this has been depreciated
//https://github.com/iron-meteor/iron-router/blob/739bcc1445db3ad6bf90bda4e0cab3203a0ae526/lib/router.js#L88
Router.map(function() {
// initiative routes
this.route('initiatives', {
path: '/',
template: 'initiatives',
data: function() {
return {
initiatives: Initiatives.find({}, {sort: {votes: -1}})
}
}
});
this.route('initiative', {
path: '/initiative/:_id',
template: 'initiativeShow',
data: function () {
return {
initiative: Initiatives.findOne(this.params._id)
}
}
});
// login routes
this.route('login', {
path: '/login',
template: 'publicLogin'
});
this.route('about');
}); | Fix Initiative sorting on landing page. | Fix Initiative sorting on landing page.
| JavaScript | mit | mtr-cherish/cherish,mtr-cherish/cherish | ---
+++
@@ -9,9 +9,9 @@
this.route('initiatives', {
path: '/',
template: 'initiatives',
- data: {
- initiatives: function() {
- return Initiatives.find({}, {$sort: {votes: -1}});
+ data: function() {
+ return {
+ initiatives: Initiatives.find({}, {sort: {votes: -1}})
}
}
}); |
3348944c657664642cfd2e2e6625e71f8c262d94 | app/stores/index.js | app/stores/index.js | import { browserHistory } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from '../utils/local-storage';
import { reducer } from '../reducers';
const initialState = loadState();
const router = routerMiddleware(browserHistory);
export const Store = createStore(reducer, initialState, applyMiddleware(thunkMiddleware, router));
Store.subscribe(() => saveState(Store.getState()));
| import { browserHistory } from 'react-router';
import { createStore, applyMiddleware, compose } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from '../utils/local-storage';
import { reducer } from '../reducers';
const initialState = loadState();
const router = routerMiddleware(browserHistory);
const composeEnhancers = process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const Store = createStore(reducer, initialState, composeEnhancers(applyMiddleware(thunkMiddleware, router)));
Store.subscribe(() => saveState(Store.getState()));
| Add hook for redux devtools | chore(devtools): Add hook for redux devtools
| JavaScript | mit | pokedextracker/pokedextracker.com,pokedextracker/pokedextracker.com,pokedextracker/pokedextracker.com | ---
+++
@@ -1,7 +1,7 @@
-import { browserHistory } from 'react-router';
-import { createStore, applyMiddleware } from 'redux';
-import { routerMiddleware } from 'react-router-redux';
-import thunkMiddleware from 'redux-thunk';
+import { browserHistory } from 'react-router';
+import { createStore, applyMiddleware, compose } from 'redux';
+import { routerMiddleware } from 'react-router-redux';
+import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from '../utils/local-storage';
import { reducer } from '../reducers';
@@ -9,6 +9,8 @@
const initialState = loadState();
const router = routerMiddleware(browserHistory);
-export const Store = createStore(reducer, initialState, applyMiddleware(thunkMiddleware, router));
+const composeEnhancers = process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+
+export const Store = createStore(reducer, initialState, composeEnhancers(applyMiddleware(thunkMiddleware, router)));
Store.subscribe(() => saveState(Store.getState())); |
19eb30243b27572597b84420a255b3eb74800265 | src/type/mongoId.js | src/type/mongoId.js |
import { ObjectId } from 'mongodb';
import Type from '../core/type';
export const MongoIdType = new Type({
name: 'mongoid',
generatePrimaryKeyVal() {
return new ObjectId();
},
fromString(str) {
return ObjectId(str);
},
fromClient(field, value) {
if (value instanceof ObjectId) {
return value;
}
if (value) {
const str = value.toString();
// we don't want to accept 12-byte strings from the client
if (str.length !== 24) {
throw new Error('Invalid ObjectId');
}
return ObjectId(str);
}
//return undefined;
},
toClient(field, value) {
return value ? value.toString() : value;
}
});
|
import { ObjectId } from 'mongodb';
import Type from '../core/type';
export const MongoIdType = new Type({
name: 'mongoid',
generatePrimaryKeyVal() {
return new ObjectId();
},
fromString(str) {
return ObjectId(str);
},
fromClient(field, value) {
if (value instanceof ObjectId) {
return value;
}
if (value) {
const str = value.toString();
// we don't want to accept 12-byte strings from the client
if (str.length !== 24) {
throw new Error(`Invalid ObjectId for field ${field}`);
}
return ObjectId(str);
}
//return undefined;
},
toClient(field, value) {
return value ? value.toString() : value;
}
});
| Add `field` to error message | Add `field` to error message | JavaScript | apache-2.0 | tyranid-org/tyranid,tyranid-org/tyranid,tyranid-org/tyranid,tyranid-org/tyranid | ---
+++
@@ -21,7 +21,7 @@
const str = value.toString();
// we don't want to accept 12-byte strings from the client
if (str.length !== 24) {
- throw new Error('Invalid ObjectId');
+ throw new Error(`Invalid ObjectId for field ${field}`);
}
return ObjectId(str); |
78d2786d95c6bfb4252c84185dcf0ad6fd62bc11 | tasks/build.js | tasks/build.js | var build = require("../index").build;
module.exports = function(grunt){
grunt.registerMultiTask("steal-build", "Build a steal project into bundles.", function(){
var done = this.async();
var options = this.options();
var system = options.system;
var buildOptions = options.buildOptions;
// Run the build with the provided options
build(system, buildOptions).then(function(){
grunt.log.writeln("Build was successful.");
done();
});
});
};
| var build = require("../index").build;
module.exports = function(grunt){
grunt.registerMultiTask("steal-build", "Build a steal project into bundles.", function(){
var done = this.async();
var options = this.options();
var system = options.system;
var buildOptions = options.buildOptions;
// Run the build with the provided options
var promise = build(system, buildOptions);
if(promise.then) {
promise.then(function(){
grunt.log.writeln("Build was successful.");
done();
});
}
});
};
| Allow the grunt task to work with the watch mode | Allow the grunt task to work with the watch mode
| JavaScript | mit | stealjs/steal-tools,stealjs/steal-tools,mcanthony/steal-tools,mcanthony/steal-tools | ---
+++
@@ -10,11 +10,14 @@
var buildOptions = options.buildOptions;
// Run the build with the provided options
- build(system, buildOptions).then(function(){
- grunt.log.writeln("Build was successful.");
+ var promise = build(system, buildOptions);
+ if(promise.then) {
+ promise.then(function(){
+ grunt.log.writeln("Build was successful.");
- done();
- });
+ done();
+ });
+ }
});
|
c355dd7b32ad2cd22e761a2b254e55ad79cf1032 | front/js/tobthebot.js | front/js/tobthebot.js | $( function() {
}) ; | $( function() {
var socket = io.connect('http://localhost:8080');
var timeouts = { 37:null, 38:null, 39:null, 40:null } ;
var LEFT = 37,
UP = 38,
RIGHT = 39,
DOWN = 40 ;
var getDisableCallback = function getDisableCallback( key ) {
return function() {
socket.emit( 'message', { key: key, active: false } ) ;
clearTimeout( timeouts[key] );
timeouts[key] = null ;
} ;
}
$( document ).keydown( function( event ) {
var key = event.which;
if( key >= LEFT && key <= DOWN ) {
var hasTimeout = ( timeouts[key] !== null ) ;
if( hasTimeout ) {
clearTimeout( timeouts[key] );
}
else {
socket.emit( 'message', { key: key, active: true } ) ;
}
timeouts[key] = setTimeout( getDisableCallback( key ), 1000 ) ;
}
});
$(document).keyup(function( event ){
var key = event.which;
if( key >= LEFT && key <= DOWN ) {
getDisableCallback( key )() ;
}
});
}) ; | Add minimal keyboard handling for control | Add minimal keyboard handling for control
| JavaScript | mit | jbouny/tobthebot | ---
+++
@@ -1,3 +1,39 @@
$( function() {
-
+ var socket = io.connect('http://localhost:8080');
+
+ var timeouts = { 37:null, 38:null, 39:null, 40:null } ;
+
+ var LEFT = 37,
+ UP = 38,
+ RIGHT = 39,
+ DOWN = 40 ;
+
+ var getDisableCallback = function getDisableCallback( key ) {
+ return function() {
+ socket.emit( 'message', { key: key, active: false } ) ;
+ clearTimeout( timeouts[key] );
+ timeouts[key] = null ;
+ } ;
+ }
+
+ $( document ).keydown( function( event ) {
+ var key = event.which;
+ if( key >= LEFT && key <= DOWN ) {
+ var hasTimeout = ( timeouts[key] !== null ) ;
+ if( hasTimeout ) {
+ clearTimeout( timeouts[key] );
+ }
+ else {
+ socket.emit( 'message', { key: key, active: true } ) ;
+ }
+ timeouts[key] = setTimeout( getDisableCallback( key ), 1000 ) ;
+ }
+ });
+
+ $(document).keyup(function( event ){
+ var key = event.which;
+ if( key >= LEFT && key <= DOWN ) {
+ getDisableCallback( key )() ;
+ }
+ });
}) ; |
44ad848316649b5d7e507928cd45a7640842d4ad | www/PreferencesManager.js | www/PreferencesManager.js | var PreferencesManager = function() {
};
PreferencesManager.exec = function() {
var logRestoredValue = function(value) {
console.log(value)
}
var successfully = function () {
console.log("Success");
cordova.exec(logRestoredValue, failed, "PreferencesManager", "restore", [2, "test"]);
};
var failed = function () {
console.log("Failed");
};
cordova.exec(successfully, failed, "PreferencesManager", "store", [2, "test", 1080982423420]);
};
module.exports = PreferencesManager;
| var PreferencesManager = function() {
};
PreferencesManager.store = function(type, key, value) {
var logStoredValue = function(value) {
console.log(value)
}
var successfully = function () {
cordova.exec(logStoredValue, failed, "PreferencesManager", "restore", [type, key]);
};
var failed = function () {
console.log("Failed");
};
cordova.exec(successfully, failed, "PreferencesManager", "store", [type, key, value]);
};
PreferencesManager.restore = function(type, key) {
var successfully = function (value) {
console.log(value)
};
var failed = function () {
console.log("Failed");
};
cordova.exec(successfully, failed, "PreferencesManager", "restore", [type, key]);
};
module.exports = PreferencesManager;
| Add function do restore data from SharedPreferences | Add function do restore data from SharedPreferences
| JavaScript | mit | carloseduardosx/PreferencesManager,carloseduardosx/PreferencesManager | ---
+++
@@ -1,20 +1,32 @@
var PreferencesManager = function() {
};
-PreferencesManager.exec = function() {
+PreferencesManager.store = function(type, key, value) {
- var logRestoredValue = function(value) {
+ var logStoredValue = function(value) {
console.log(value)
}
+
var successfully = function () {
- console.log("Success");
- cordova.exec(logRestoredValue, failed, "PreferencesManager", "restore", [2, "test"]);
+ cordova.exec(logStoredValue, failed, "PreferencesManager", "restore", [type, key]);
};
var failed = function () {
console.log("Failed");
};
- cordova.exec(successfully, failed, "PreferencesManager", "store", [2, "test", 1080982423420]);
+ cordova.exec(successfully, failed, "PreferencesManager", "store", [type, key, value]);
+};
+
+PreferencesManager.restore = function(type, key) {
+
+ var successfully = function (value) {
+ console.log(value)
+ };
+
+ var failed = function () {
+ console.log("Failed");
+ };
+ cordova.exec(successfully, failed, "PreferencesManager", "restore", [type, key]);
};
module.exports = PreferencesManager; |
f810aa8689b1149aef7fa70cb36bcf8b0d17089d | grunt/options/copy.js | grunt/options/copy.js | module.exports = {
main: {
files: [
{
expand: true,
cwd: 'assets/',
src: ['**'],
dest: 'out/'
}
]
},
require: {
src: 'vendor/requirejs/require.js',
dest: 'out/js/lib/require.js'
},
jQuery: {
src: 'vendor/jquery/dist/jquery.js',
dest: 'out/js/lib/jquery.js'
},
jQueryMin: {
src: 'vendor/jquery/dist/jquery.min.js',
dest: 'out/js/lib/jquery.min.js'
},
js: {
files: [
{
expand: true,
cwd: 'src/js/app',
src: ['**/*.js'],
dest: 'out/js/app'
}
]
},
libs: {
files: [
{
expand: true,
cwd: 'vendor',
src: ['**/*.js'],
dest: 'out/js/lib'
}
]
},
fonts: {
files: [
{
expand: true,
cwd: 'src/icons/generated/',
src: ['*.eot', '*.svg', '*.ttf', '*.woff'],
dest: 'out/fonts'
}
]
},
leaflet: {
files: [
{
expand: true,
cwd: 'vendor/leaflet-dist/images',
src: ['**'],
dest: 'out/leaflet/images'
}
]
}
}; | module.exports = {
main: {
files: [
{
expand: true,
cwd: 'assets/',
src: ['**', '.htaccess'],
dest: 'out/'
}
]
},
require: {
src: 'vendor/requirejs/require.js',
dest: 'out/js/lib/require.js'
},
jQuery: {
src: 'vendor/jquery/dist/jquery.js',
dest: 'out/js/lib/jquery.js'
},
jQueryMin: {
src: 'vendor/jquery/dist/jquery.min.js',
dest: 'out/js/lib/jquery.min.js'
},
js: {
files: [
{
expand: true,
cwd: 'src/js/app',
src: ['**/*.js'],
dest: 'out/js/app'
}
]
},
libs: {
files: [
{
expand: true,
cwd: 'vendor',
src: ['**/*.js'],
dest: 'out/js/lib'
}
]
},
fonts: {
files: [
{
expand: true,
cwd: 'src/icons/generated/',
src: ['*.eot', '*.svg', '*.ttf', '*.woff'],
dest: 'out/fonts'
}
]
},
leaflet: {
files: [
{
expand: true,
cwd: 'vendor/leaflet-dist/images',
src: ['**'],
dest: 'out/leaflet/images'
}
]
}
}; | Copy the .htaccess to the release directory | Copy the .htaccess to the release directory
| JavaScript | mit | vitch/nakeditchyfeet,vitch/nakeditchyfeet | ---
+++
@@ -4,7 +4,7 @@
{
expand: true,
cwd: 'assets/',
- src: ['**'],
+ src: ['**', '.htaccess'],
dest: 'out/'
}
] |
7cedcd5af9a6a12e7edb6a3bf91b55f6cf95d90d | api/register/registerController.js | api/register/registerController.js | const userModel = require('../../models/users')
const validator = require('./registerValidation')
const { buildResponse } = require('../../utils/responseService')
module.exports = (req, res) => {
const {error, value} = validator.validate(req.body)
if (error) {
return buildResponse(res, 400, { message: error.details[0].message })
}
userModel.findOne(value.username)
.then(user => {
if (user) {
buildResponse(res, 403, { message: 'user already exists' })
} else {
userModel.createUser(value)
.then(user => {
buildResponse(res, 200, { message: 'successfully created user.', user })
})
.catch(error => {
buildResponse(res, 500, { message: 'something happened', error })
})
}
})
}
| const userModel = require('../../models/users')
const validator = require('./registerValidation')
const { buildResponse } = require('../../utils/responseService')
module.exports = (req, res) => {
const {error, value} = validator.validate(req.body)
if (error) {
return buildResponse(res, 400, { message: error.details[0].message })
}
userModel.findOne(value.username)
.then(user => {
if (user) {
buildResponse(res, 422, { message: 'user already exists' })
} else {
userModel.createUser(value)
.then(user => {
buildResponse(res, 200, { message: 'successfully created user.', user })
})
.catch(error => {
buildResponse(res, 500, { message: 'something happened', error })
})
}
})
}
| Change status code for resouce confilcts to 422 'Unprocessable Entity' | Change status code for resouce confilcts to 422 'Unprocessable Entity'
| JavaScript | mit | byteBridge/transcriptus-api | ---
+++
@@ -11,7 +11,7 @@
userModel.findOne(value.username)
.then(user => {
if (user) {
- buildResponse(res, 403, { message: 'user already exists' })
+ buildResponse(res, 422, { message: 'user already exists' })
} else {
userModel.createUser(value)
.then(user => { |
5bb346232d400257f186c2af83c0e4ef8825c502 | hold-and-fifo/fifo.js | hold-and-fifo/fifo.js | module.exports = function(RED) {
"use strict";
function Fifo(config) {
RED.nodes.createNode(this,config);
var me = this;
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
this.on('input', function (msg) {
// are we full?
// if so, boot some out
if (this.queue.length >= this.depth) {
while (this.queue.length >= this.depth) {
var msg = this.queue.shift();
this.send(msg);
}
}
// clone the message and whack it in the queue
this.queue.push(msg);
if (this.queue.length == this.depth) {
// queue is full
this.status({fill: "green", shape: "dot",
text: this.queue.length + "/" +
this.depth + " msgs"});
} else {
// queue is partially full
this.status({fill: "green", shape: "ring",
text: this.queue.length + "/" +
this.depth + " msgs"});
}
});
this.on("close", function() {
});
}
RED.nodes.registerType("fifo",Fifo);
}
| module.exports = function(RED) {
"use strict";
function Fifo(config) {
RED.nodes.createNode(this,config);
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
this.on('input', function (msg) {
// are we full?
// if so, boot some out
if (this.queue.length >= this.depth) {
while (this.queue.length >= this.depth) {
var outgoing = this.queue.shift();
this.send(outgoing);
}
}
// clone the message and whack it in the queue
this.queue.push(msg);
if (this.queue.length == this.depth) {
// queue is full
this.status({fill: "green", shape: "dot",
text: this.queue.length + "/" +
this.depth + " msgs"});
} else {
// queue is partially full
this.status({fill: "green", shape: "ring",
text: this.queue.length + "/" +
this.depth + " msgs"});
}
});
this.on("close", function() {
});
}
RED.nodes.registerType("fifo",Fifo);
}
| Fix some code idiocies that lambdagrrl found. | Fix some code idiocies that lambdagrrl found.
| JavaScript | mit | cheesestraws/redstuff,cheesestraws/redstuff | ---
+++
@@ -4,8 +4,6 @@
function Fifo(config) {
RED.nodes.createNode(this,config);
- var me = this;
-
this.queue = [];
this.depth = config.depth;
this.status({fill:"red",shape:"ring",text:"no value"});
@@ -15,8 +13,8 @@
// if so, boot some out
if (this.queue.length >= this.depth) {
while (this.queue.length >= this.depth) {
- var msg = this.queue.shift();
- this.send(msg);
+ var outgoing = this.queue.shift();
+ this.send(outgoing);
}
}
|
15e44f2281f1265fd29dc6894f2264f372e95513 | app/decorators/Data/connectData.js | app/decorators/Data/connectData.js | import React, { Component } from 'react';
import hoistStatics from 'hoist-non-react-statics';
/*
When this decorator is used, it MUST be the first (outermost) decorator.
Otherwise, we cannot find and call the fetchData methods.
*/
export default function connectData(fetchData, clientOnly = false) {
return function wrapWithFetchData(WrappedComponent) {
class ConnectData extends Component {
render() {
return <WrappedComponent { ...this.props } />;
}
}
ConnectData.fetchData = fetchData;
ConnectData.fetchInClientOnly = clientOnly;
return hoistStatics(ConnectData, WrappedComponent);
};
}
| import React, { Component } from 'react';
import hoistStatics from 'hoist-non-react-statics';
/*
When this decorator is used, it MUST be the first (outermost) decorator.
Otherwise, we cannot find and call the fetchData methods.
*/
export default function connectData(fetchData, clientOnly = false) {
return function wrapWithFetchData(WrappedComponent) {
class ConnectData extends Component {
static fetchData = fetchData;
static fetchInClientOnly = clientOnly;
render() {
return <WrappedComponent { ...this.props } />;
}
}
return hoistStatics(ConnectData, WrappedComponent);
};
}
| Move statics to the class | Move statics to the class
| JavaScript | mit | tco/r3ign | ---
+++
@@ -10,14 +10,14 @@
return function wrapWithFetchData(WrappedComponent) {
class ConnectData extends Component {
+ static fetchData = fetchData;
+ static fetchInClientOnly = clientOnly;
+
render() {
return <WrappedComponent { ...this.props } />;
}
}
- ConnectData.fetchData = fetchData;
- ConnectData.fetchInClientOnly = clientOnly;
-
return hoistStatics(ConnectData, WrappedComponent);
};
} |
0e6fc4bc05ca1f17ec51657b151b495aa8c94054 | test/test_parser.js | test/test_parser.js | var fs = require("fs");
var PEG = require("pegjs");
var parser = PEG.buildParser(fs.readFileSync("parser.pegjs", "utf8"));
var tunes = fs.readFileSync("test/tunes.txt", "utf8").split("\n\n");
var mistakes = 0;
tunes.forEach(function(p) {
try {
var parsed = parser.parse(p + "\n");
console.log("\x1B[0;32m:)\x1B[0m " + parsed.header.title)
console.log(JSON.stringify(parsed, null, 2))
}
catch (error) {
console.log("\x1B[0;31m\nSyntax Error:");
console.log(error.message);
console.log("line: " + error.line);
console.log("column: " + error.column);
var debugLine = Array(error.column).join("-") + "^";
var debugMargin = Array(error.line.toString().length + 2).join("-");
var i;
var lines = p.split("\n");
for (i = 0; i < error.line; i++)
console.log((i + 1) + " " + lines[i]);
console.log(debugMargin + debugLine)
for (i = error.line + 1; i < lines.length; i++)
console.log(i + " " + lines[i]);
mistakes += 1;
}
});
process.exit(mistakes.length);
| var fs = require("fs");
var PEG = require("pegjs");
var parser = PEG.buildParser(fs.readFileSync("parser.pegjs", "utf8"));
var tunes = fs.readFileSync("test/tunes.txt", "utf8").split("\n\n");
var mistakes = 0;
tunes.forEach(function(p) {
try {
var parsed = parser.parse(p + "\n");
console.log("\x1B[0;32m:)\x1B[0m " + parsed.header.title)
//console.log(JSON.stringify(parsed, null, 2))
}
catch (error) {
console.log("\x1B[0;31m\nSyntax Error:");
console.log(error.message);
console.log("line: " + error.line);
console.log("column: " + error.column);
var debugLine = Array(error.column).join("-") + "^";
var debugMargin = Array(error.line.toString().length + 2).join("-");
var i;
var lines = p.split("\n");
for (i = 0; i < error.line; i++)
console.log((i + 1) + " " + lines[i]);
console.log(debugMargin + debugLine)
for (i = error.line + 1; i < lines.length; i++)
console.log(i + " " + lines[i]);
mistakes += 1;
}
});
process.exit(mistakes.length);
| Comment too-verbose JSON structure logging | Comment too-verbose JSON structure logging
| JavaScript | mpl-2.0 | sergi/abcnode | ---
+++
@@ -9,7 +9,7 @@
try {
var parsed = parser.parse(p + "\n");
console.log("\x1B[0;32m:)\x1B[0m " + parsed.header.title)
- console.log(JSON.stringify(parsed, null, 2))
+ //console.log(JSON.stringify(parsed, null, 2))
}
catch (error) {
console.log("\x1B[0;31m\nSyntax Error:"); |
c5d99943bbc4d2067c12fcbe103e7f3a26502e72 | test/net/tcp-server.js | test/net/tcp-server.js | var net = require('net');
var server, port;
server = net.createServer(function (conn) {
console.log("Server: connected");
conn.on("data", function (data) {
if (data.length == 1 && data[0] == 0xef) {
console.log("Server: abridgedFlag detected");
} else {
console.log("Server: echo data of length %s:", data.length);
console.log(data);
conn.write(data);
}
})
});
port = 2001;
server.listen(port, function () {
console.log("Server bound on port %s\n", port);
})
exports.port = port; | var net = require('net');
var server, port;
server = net.createServer(function (conn) {
console.log("Server: connected");
conn.on("data", function (data) {
if (data.length == 1 && data[0] == 0xef) {
console.log("Server: abridgedFlag detected");
} else {
console.log("Server: echo data of length %s:", data.length);
console.log(data);
conn.write(data);
}
})
});
port = 2002;
server.listen(port, function () {
console.log("Server bound on port %s\n", port);
})
exports.port = port; | Move tcp test to port 2002 | Move tcp test to port 2002 | JavaScript | mit | enricostara/telegram-mt-node,cgvarela/telegram-mt-node,piranna/telegram-mt-node | ---
+++
@@ -13,7 +13,7 @@
}
})
});
-port = 2001;
+port = 2002;
server.listen(port, function () {
console.log("Server bound on port %s\n", port);
}) |
5ec305c02a4202789ceb371924894d68be90fb02 | client/react/src/reducers.js | client/react/src/reducers.js | import { combineReducers } from 'redux'
import { WS_MSG } from './actions'
function auth(state = {isAuthenticated: false}, action) {
switch (action.type) {
case WS_MSG:
let msg = action.msg
switch (msg.type) {
case "valid_login":
return {
...state,
isAuthenticated: true
}
default:
break
}
break
default:
break
}
return state;
}
const tarabishApp = combineReducers({
auth
})
export default tarabishApp
| import { combineReducers } from 'redux'
import { WS_MSG } from './actions'
// TODO: Should just one reducer accept WS_MSG
// and repack the message and resend them?
function auth(state = {isAuthenticated: false}, action) {
switch (action.type) {
case WS_MSG:
let msg = action.msg
switch (msg.type) {
case "valid_login":
return {
...state,
isAuthenticated: true
}
default:
break
}
break
default:
break
}
return state;
}
function tables(state = {tableList: []}, action) {
switch (action.type) {
// get-tables, sit, stand...
case WS_MSG:
let msg = action.msg
switch (msg.type) {
case "tables":
return {
...state,
tableList: msg.tables,
}
default:
break
}
break
default:
break
}
return state;
}
const tarabishApp = combineReducers({
auth,
tables
})
export default tarabishApp
| Add a tables reducer to the lobby table list. | Add a tables reducer to the lobby table list.
| JavaScript | mit | KenMacD/tarabish,KenMacD/tarabish,KenMacD/tarabish,KenMacD/tarabish | ---
+++
@@ -1,5 +1,9 @@
import { combineReducers } from 'redux'
import { WS_MSG } from './actions'
+
+
+// TODO: Should just one reducer accept WS_MSG
+// and repack the message and resend them?
function auth(state = {isAuthenticated: false}, action) {
switch (action.type) {
@@ -21,8 +25,31 @@
return state;
}
+function tables(state = {tableList: []}, action) {
+ switch (action.type) {
+ // get-tables, sit, stand...
+ case WS_MSG:
+ let msg = action.msg
+ switch (msg.type) {
+ case "tables":
+ return {
+ ...state,
+ tableList: msg.tables,
+ }
+ default:
+ break
+ }
+ break
+ default:
+ break
+ }
+ return state;
+}
+
+
const tarabishApp = combineReducers({
- auth
+ auth,
+ tables
})
export default tarabishApp |
575e2d482b52bcea36f6a7a6cc357e3ee6d0efbd | templates/_js_header.js | templates/_js_header.js | /*
* Looking for the full, uncompressed source? Try here:
*
* https://github.com/js/{{ REPOSITORY_NAME }}
*
* The following files are included in this compressed version:
*{% for path in paths %}
* {{ path }}{% endfor %}
*/
| /*
* Looking for the full, uncompressed source? Try here:
*
* https://github.com/inn/{{ REPOSITORY_NAME }}
*
* The following files are included in this compressed version:
*{% for path in paths %}
* {{ path }}{% endfor %}
*/
| Fix the js header for real | Fix the js header for real
| JavaScript | mit | INN/app-template,INN/app-template,INN/app-template,INN/app-template | ---
+++
@@ -1,7 +1,7 @@
/*
* Looking for the full, uncompressed source? Try here:
*
- * https://github.com/js/{{ REPOSITORY_NAME }}
+ * https://github.com/inn/{{ REPOSITORY_NAME }}
*
* The following files are included in this compressed version:
*{% for path in paths %} |
9c6684c06d070ab77fbd4f48fd5c10ca24de806c | packages/storybook/examples/Popover/DemoList.js | packages/storybook/examples/Popover/DemoList.js | import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function DemoButton(props) {
return (
<Button
bold
minified={false}
color="black"
{...props} />
);
}
function DemoList() {
return (
<List>
<ListRow>
<DemoButton basic="Row 1" onClick={action('click.1')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 2" onClick={action('click.2')} />
</ListRow>
<ListRow>
<DemoButton basic="Row 3" onClick={action('click.3')} />
</ListRow>
</List>
);
}
export default DemoList;
| import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from '@ichef/gypcrete/src/Button';
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
function ButtonRow(props) {
return (
<ListRow>
<Button
minified={false}
{...props} />
</ListRow>
);
}
function DemoList() {
return (
<List>
<ButtonRow basic="Row 1" onClick={action('click.1')} />
<ButtonRow basic="Row 2" onClick={action('click.2')} />
<ButtonRow basic="Row 3" onClick={action('click.3')} />
<ButtonRow basic="Link row" tagName="a" href="https://apple.com" />
</List>
);
}
export default DemoList;
| Update demo list for popover to add row of hyperlink button | Update demo list for popover to add row of hyperlink button
| JavaScript | apache-2.0 | iCHEF/gypcrete,iCHEF/gypcrete | ---
+++
@@ -5,28 +5,24 @@
import List from '@ichef/gypcrete/src/List';
import ListRow from '@ichef/gypcrete/src/ListRow';
-function DemoButton(props) {
+function ButtonRow(props) {
return (
- <Button
- bold
- minified={false}
- color="black"
- {...props} />
+ <ListRow>
+ <Button
+ minified={false}
+ {...props} />
+ </ListRow>
);
}
function DemoList() {
return (
<List>
- <ListRow>
- <DemoButton basic="Row 1" onClick={action('click.1')} />
- </ListRow>
- <ListRow>
- <DemoButton basic="Row 2" onClick={action('click.2')} />
- </ListRow>
- <ListRow>
- <DemoButton basic="Row 3" onClick={action('click.3')} />
- </ListRow>
+ <ButtonRow basic="Row 1" onClick={action('click.1')} />
+ <ButtonRow basic="Row 2" onClick={action('click.2')} />
+ <ButtonRow basic="Row 3" onClick={action('click.3')} />
+
+ <ButtonRow basic="Link row" tagName="a" href="https://apple.com" />
</List>
);
} |
abdb70dedb04fa2f97cdc08664e591e45e9591d9 | bin/temp-es6-fix.js | bin/temp-es6-fix.js | // This is a temporary fix for supporting es6 scripts
// We will add support for es6->es5 transforms in Lively and this can go away
var babel = require("babel-core");
var child_process = require("child_process");
var fs = require("fs");
var lang = require("lively.lang");
var found = child_process.execSync('find core \\( -iname ".svn" -o -iname ".git" -o -iname "node_modules" -o -iname "combined.js" -o -iname "BootstrapDebugger.js" \\) -prune -o -type f -iname "*.js" -print'),
files = lang.arr.compact(lang.string.lines(found.toString()));
var visitor = {ArrowFunctionExpression: function (node, st) { st.es6 = true; }},
es6Files = files.filter(f => {
try {
var ast = acorn.parse(fs.readFileSync(f).toString(), {ecmaVersion: 6});
var state = {es6: false};
acorn.walk.simple(ast, visitor, null, state);
return state.es6
} catch (e) {
console.log(f);
console.error(e);
return false;
}
});
es6Files.forEach(f => {
var tfmed = babel.transformFileSync(f, {compact: false, comments: true}).code;
tfmed = tfmed.replace(/^'use strict';\n*/m, "");
fs.writeFileSync(f, tfmed);
});
| // This is a temporary fix for supporting es6 scripts
// We will add support for es6->es5 transforms in Lively and this can go away
var babel = require("babel-core");
var child_process = require("child_process");
var fs = require("fs");
var lang = require("lively.lang");
var found = child_process.execSync('find core \\( -iname ".svn" -o -iname ".git" -o -iname "node_modules" -o -iname "combined.js" -o -iname "BootstrapDebugger.js" \\) -prune -o -type f -iname "*.js" -print'),
files = lang.string.lines(found.toString()).compact();
var visitor = {ArrowFunctionExpression: function (node, st) { st.es6 = true; }},
es6Files = files.filter(f => {
try {
var ast = acorn.parse(fs.readFileSync(f).toString(), {ecmaVersion: 6});
var state = {es6: false};
acorn.walk.simple(ast, visitor, null, state);
return state.es6
} catch (e) {
console.log(f);
console.error(e);
return false;
}
});
es6Files.forEach(f => {
var tfmed = babel.transformFileSync(f, {compact: false, comments: true}).code;
tfmed = tfmed.replace(/^'use strict';\n*/m, "");
fs.writeFileSync(f, tfmed);
});
| Revert "es6 fix fix fix" | Revert "es6 fix fix fix"
This reverts commit 6cb64f9a18bff189ccb41580590f48142deab629.
| JavaScript | mit | NikolaySuslov/LivelyKernel,NikolaySuslov/LivelyKernel,LivelyKernel/LivelyKernel,NikolaySuslov/LivelyKernel,LivelyKernel/LivelyKernel,LivelyKernel/LivelyKernel | ---
+++
@@ -7,7 +7,7 @@
var lang = require("lively.lang");
var found = child_process.execSync('find core \\( -iname ".svn" -o -iname ".git" -o -iname "node_modules" -o -iname "combined.js" -o -iname "BootstrapDebugger.js" \\) -prune -o -type f -iname "*.js" -print'),
- files = lang.arr.compact(lang.string.lines(found.toString()));
+ files = lang.string.lines(found.toString()).compact();
var visitor = {ArrowFunctionExpression: function (node, st) { st.es6 = true; }},
es6Files = files.filter(f => { |
3b8650f1ecac51b9a9f78944b0843e3af0dca252 | Standards/WCAG2AAA/Sniffs/Principle2/Guideline2_4/2_4_4.js | Standards/WCAG2AAA/Sniffs/Principle2/Guideline2_4/2_4_4.js | var HTMLCS_WCAG2AAA_Sniffs_Principle2_Guideline2_4_2_4_4 = {
register: function()
{
return ['a'];
},
process: function(element)
{
HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context identifies the purpose of the link.', 'H77-81');
}
};
| var HTMLCS_WCAG2AAA_Sniffs_Principle2_Guideline2_4_2_4_4 = {
register: function()
{
return ['a'];
},
process: function(element)
{
if (element.hasAttribute('title') === true) {
HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context, or its title attribute, identifies the purpose of the link.', 'H77-81H33');
} else {
HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context identifies the purpose of the link.', 'H77-81');
}
}
};
| Add title attribute test to 2.4.4 (H33). | Add title attribute test to 2.4.4 (H33).
This is another "in context" notice. Only one notice will be thrown per link: if there is a title attribute, one notice will point to H77-81 AND H33 at once, if not, just to H77-81.
| JavaScript | bsd-3-clause | telesma/HTML_CodeSniffer,telesma/HTML_CodeSniffer,daam/HTML_CodeSniffer,lwright-sq/HTML_CodeSniffer,daam/HTML_CodeSniffer,adelevie/HTML_CodeSniffer,daam/HTML_CodeSniffer,adelevie/HTML_CodeSniffer,telesma/HTML_CodeSniffer,squizlabs/HTML_CodeSniffer,ironikart/HTML_CodeSniffer,squizlabs/HTML_CodeSniffer,squizlabs/HTML_CodeSniffer,ironikart/HTML_CodeSniffer,ironikart/HTML_CodeSniffer,lwright-sq/HTML_CodeSniffer,adelevie/HTML_CodeSniffer,lwright-sq/HTML_CodeSniffer | ---
+++
@@ -7,7 +7,11 @@
process: function(element)
{
- HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context identifies the purpose of the link.', 'H77-81');
+ if (element.hasAttribute('title') === true) {
+ HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context, or its title attribute, identifies the purpose of the link.', 'H77-81H33');
+ } else {
+ HTMLCS.addMessage(HTMLCS.NOTICE, element, 'Check that the link text combined with programmatically determined link context identifies the purpose of the link.', 'H77-81');
+ }
}
}; |
1653dda921b8eb321b573230bc267091468a62aa | server/emails/managerBookingUpdated.js | server/emails/managerBookingUpdated.js | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = values.participants.map(p => <li key={p.id}>{p.name}</li>);
return renderEmail(
<Email title={`${values.event.customQuestions.emailSubjectTag} Booking Updated`}>
<Item>
<p>Hi {values.emailUser.userName},</p>
<p>{values.userName} has updated booking to {values.event.name}. They have
booked {values.participants.length} {values.participants.length === 1 ? 'person' : 'people'}:</p>
<p>
<ul>{participantsList}</ul>
</p>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `${values.event.customQuestions.emailSubjectTag} Booking Updated`;
} | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
export function html(values) {
const participantsList = values.participants.map(p => <li key={p.id}>{p.name}</li>);
return renderEmail(
<Email title={`${values.event.customQuestions.emailSubjectTag} Booking Updated`}>
<Item>
<p>Hi {values.emailUser.userName},</p>
<p>{values.userName} has updated their booking {values.district ? `for ${values.district}` : ''} to {values.event.name}. They have
booked {values.participants.length} {values.participants.length === 1 ? 'person' : 'people'}:</p>
<p>
<ul>{participantsList}</ul>
</p>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `${values.event.customQuestions.emailSubjectTag} Booking Updated`;
} | Include district in updated e-mail. | Include district in updated e-mail.
| JavaScript | mit | RalphSleigh/bookings,RalphSleigh/bookings,RalphSleigh/bookings | ---
+++
@@ -18,7 +18,7 @@
<Email title={`${values.event.customQuestions.emailSubjectTag} Booking Updated`}>
<Item>
<p>Hi {values.emailUser.userName},</p>
- <p>{values.userName} has updated booking to {values.event.name}. They have
+ <p>{values.userName} has updated their booking {values.district ? `for ${values.district}` : ''} to {values.event.name}. They have
booked {values.participants.length} {values.participants.length === 1 ? 'person' : 'people'}:</p>
<p>
<ul>{participantsList}</ul> |
9e542db20917f9d5855d4e420f874690bb91f33f | test/ws/index.js | test/ws/index.js | const { it } = require('mocha');
const initSocket = require('../../src/ws');
const { IO } = require('./util');
module.exports = ({ server }) => {
let connect;
initSocket({
on(connection, f) {
connect = f;
},
}, server.handler);
it('connects', () => {
const io = new IO();
connect(io);
});
it('joins the correct room', done => {
const io = new IO();
io.join = function (room) {
if (room === '/status') {
return done();
}
done(false);
};
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
});
it('receives status messages', done => {
const io = new IO();
io.on('message', arg => {
if (['ok', '👍', '⚠', '🚨'].includes(arg)) {
done();
} else {
done(new Error('bad message: ' + require('util').inspect(arg, { depth: null })));
}
});
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
io.on('error', err => {
console.log('err!', err);
done(err);
io.close();
});
});
};
| const { it } = require('mocha');
const debug = require('debug')('nails:test');
const initSocket = require('../../src/ws');
const { IO } = require('./util');
module.exports = ({ server }) => {
let connect;
initSocket({
on(connection, f) {
connect = f;
},
}, server.handler);
it('connects', () => {
const io = new IO();
connect(io);
});
it('joins the correct room', done => {
const io = new IO();
io.join = function (room) {
if (room === '/status') {
return done();
}
done(false);
};
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
});
it('receives status messages', done => {
const io = new IO();
io.on('message', arg => {
if (['ok', '👍', '⚠', '🚨'].includes(arg)) {
done();
} else {
done(new Error('bad message: ' + require('util').inspect(arg, { depth: null })));
}
});
connect(io);
process.nextTick(() => {
io.emit('join', '/status');
});
io.on('error', err => {
debug('err!', err);
done(err);
io.close();
});
});
};
| Use `debug` instead of `console.log` | Use `debug` instead of `console.log`
| JavaScript | mit | ArtOfCode-/nails,ArtOfCode-/nails | ---
+++
@@ -1,4 +1,6 @@
const { it } = require('mocha');
+
+const debug = require('debug')('nails:test');
const initSocket = require('../../src/ws');
const { IO } = require('./util');
@@ -41,7 +43,7 @@
io.emit('join', '/status');
});
io.on('error', err => {
- console.log('err!', err);
+ debug('err!', err);
done(err);
io.close();
}); |
20aaa71468178ee64fca249fdc00119f5b9886a4 | assets/scripts/settings-content.js | assets/scripts/settings-content.js | function setupBoolPreference(name) {
document.getElementById(name).checked = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
Preferences[name].value = e.target.checked;
});
}
function setupNumberPreference(name) {
document.getElementById(name).value = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
console.log("ping");
Preferences[name].value = e.target.value;
});
}
for(var name in Preferences) {
if(Preferences[name].type == "bool") {
setupBoolPreference(name);
}
else {
setupNumberPreference(name);
}
}
if(!navigator.vibrate) {
document.getElementById("vibration").setAttribute("disabled", true);
}
var strbundle = new StringBundle(document.getElementById("strings"));
document.querySelector("[data-l10n-id='settings_highscores_clear']").addEventListener("click", function() {
if(window.confirm(strbundle.getString("highscores_confirm_clear"))) {
Highscores.clear();
removeDynamicItems();
noresults.classList.remove("hidden");
}
});
document.getElementById("header").addEventListener("action", function() {
window.location = "index.html";
}, false);
| function setupBoolPreference(name) {
document.getElementById(name).checked = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
Preferences[name].value = e.target.checked;
});
}
function setupNumberPreference(name) {
document.getElementById(name).value = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
Preferences[name].value = e.target.value;
});
}
for(var name in Preferences) {
if(Preferences[name].type == "bool") {
setupBoolPreference(name);
}
else {
setupNumberPreference(name);
}
}
if(!navigator.vibrate) {
document.getElementById("vibration").setAttribute("disabled", true);
}
var strbundle = new StringBundle(document.getElementById("strings"));
document.querySelector("[data-l10n-id='settings_highscores_clear']").addEventListener("click", function() {
if(window.confirm(strbundle.getString("highscores_confirm_clear"))) {
Highscores.clear();
removeDynamicItems();
noresults.classList.remove("hidden");
}
});
document.getElementById("header").addEventListener("action", function() {
window.location = "index.html";
}, false);
| Remove a debug logging call | Remove a debug logging call
| JavaScript | mpl-2.0 | freaktechnik/mines.js,freaktechnik/mines.js | ---
+++
@@ -10,7 +10,6 @@
document.getElementById(name).value = Preferences[name].value;
document.getElementById(name).addEventListener("change", function(e) {
- console.log("ping");
Preferences[name].value = e.target.value;
});
} |
497ebdbb95474e1f912654463ee16e2e2cf25466 | analytics_dashboard/static/js/enrollment-geography-main.js | analytics_dashboard/static/js/enrollment-geography-main.js | /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-view'],
function(DataTableView, WorldMapView) {
// Enrollment by country map
var enrollmentGeographyMap = new WorldMapView({
el: '[data-view=world-map]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
// eslint-disable-next-line max-len
tooltip: gettext('Learner location is determined from IP address. This map shows where learners ' +
'most recently connected.')
}),
// Enrollment by country table
enrollmentGeographyTable = new DataTableView({
el: '[data-role=enrollment-location-table]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
columns: [
{key: 'countryName', title: gettext('Country')},
{key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'},
// Translators: The noun count (e.g. number of learners)
{key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'}
],
sorting: ['-count']
});
enrollmentGeographyTable.renderIfDataAvailable();
enrollmentGeographyMap.renderIfDataAvailable();
}
);
});
| /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-view'],
function(DataTableView, WorldMapView) {
// Enrollment by country map
var enrollmentGeographyMap = new WorldMapView({
el: '[data-view=world-map]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
// eslint-disable-next-line max-len
tooltip: gettext('Learner location is determined from IP address. This map shows where learners most recently connected.')
}),
// Enrollment by country table
enrollmentGeographyTable = new DataTableView({
el: '[data-role=enrollment-location-table]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
columns: [
{key: 'countryName', title: gettext('Country')},
{key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'},
// Translators: The noun count (e.g. number of learners)
{key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'}
],
sorting: ['-count']
});
enrollmentGeographyTable.renderIfDataAvailable();
enrollmentGeographyMap.renderIfDataAvailable();
}
);
});
| Address review: Put translated line on one line. | Address review: Put translated line on one line.
| JavaScript | agpl-3.0 | Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,edx/edx-analytics-dashboard | ---
+++
@@ -15,8 +15,7 @@
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
// eslint-disable-next-line max-len
- tooltip: gettext('Learner location is determined from IP address. This map shows where learners ' +
- 'most recently connected.')
+ tooltip: gettext('Learner location is determined from IP address. This map shows where learners most recently connected.')
}),
// Enrollment by country table
enrollmentGeographyTable = new DataTableView({ |
9e96485498225a552aa8ce95ffa337d5d8b42944 | app/assets/javascripts/spree/frontend/spree_cwilt_theme.js | app/assets/javascripts/spree/frontend/spree_cwilt_theme.js | // Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'
var index = 1;
$(document).ready(function() {
startSlider();
});
function startSlider() {
images = $("#showcase_inner_container > img");
count = images.size();
loop = setInterval( function() {
document.getElementById("showcase_inner_container").className = "showcase_img";
$("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)");
if (index == count) {
index = 0;
document.getElementById("showcase_inner_container").className = "showcase_img_reset";
$("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)");
}
index += 1;
}, 5000);
}
| // Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'
var index = 1;
$(document).ready(function() {
if (window.location.pathname == "/") {
startSlider();
}
});
function startSlider() {
images = $("#showcase_inner_container > img");
count = images.size();
loop = setInterval( function() {
document.getElementById("showcase_inner_container").className = "showcase_img";
$("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)");
if (index == count) {
index = 0;
document.getElementById("showcase_inner_container").className = "showcase_img_reset";
$("#showcase_inner_container").css("transform", "translateX(" + (index * -663) + "px)");
}
index += 1;
}, 5000);
}
| Check path of current page before starting the slider. | Check path of current page before starting the slider.
| JavaScript | bsd-3-clause | clomax/spree_cwilt_theme,clomax/spree_cwilt_theme,clomax/spree_cwilt_theme | ---
+++
@@ -4,7 +4,9 @@
var index = 1;
$(document).ready(function() {
- startSlider();
+ if (window.location.pathname == "/") {
+ startSlider();
+ }
});
|
218389b20da780e987bb12352964ec713e447f55 | bundle.js | bundle.js | var fs = require('fs'),
path = require('path'),
browserify = require('browserify'),
cardGenerator = require('./card-generator.js');
var script;
var cards;
exports.init = function(options) {
// Write new cards file
var cedict = fs.readFileSync(path.join(__dirname, 'assets/cedict/cedict_ts.u8'), 'utf-8'),
vocabulary = fs.readFileSync(options.vocabularyFile, 'utf-8');
cards = cardGenerator.generateCardsFromVocabulary(vocabulary);
script = browserify(path.join(__dirname, 'lightcards/main.js'));
};
exports.pipe = function(stream) {
script.bundle({
insertGlobalVars: {
cards: function() {
return JSON.stringify(cards);
}
}
}).pipe(stream);
};
| var fs = require('fs'),
path = require('path'),
browserify = require('browserify'),
cardGenerator = require('./card-generator.js');
var script;
var cards;
exports.init = function(options) {
// Write new cards file
var vocabulary = fs.readFileSync(options.vocabularyFile, 'utf-8');
cards = cardGenerator.generateCardsFromVocabulary(vocabulary);
script = browserify(path.join(__dirname, 'lightcards/main.js'));
};
exports.pipe = function(stream) {
script.bundle({
insertGlobalVars: {
cards: function() {
return JSON.stringify(cards);
}
}
}).pipe(stream);
};
| Remove old reference to cedict file | Remove old reference to cedict file
Change-Id: I3fc1682679b99c8a188be8d848990b7de8346b33
| JavaScript | mit | odsod/lightcards,odsod/lightcards | ---
+++
@@ -8,8 +8,7 @@
exports.init = function(options) {
// Write new cards file
- var cedict = fs.readFileSync(path.join(__dirname, 'assets/cedict/cedict_ts.u8'), 'utf-8'),
- vocabulary = fs.readFileSync(options.vocabularyFile, 'utf-8');
+ var vocabulary = fs.readFileSync(options.vocabularyFile, 'utf-8');
cards = cardGenerator.generateCardsFromVocabulary(vocabulary);
script = browserify(path.join(__dirname, 'lightcards/main.js'));
}; |
0e20ff615134f2b6719e9ba46b3ebfce101651fc | src/notebook/components/cell/inputs.js | src/notebook/components/cell/inputs.js | import React, { PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
export default class Inputs extends React.Component {
static propTypes = {
executionCount: PropTypes.any,
running: PropTypes.bool,
};
constructor(props) {
super(props);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
render() {
const { executionCount, running } = this.props;
const count = !executionCount ? ' ' : executionCount;
const input = running ? '*' : count;
return (
<div className="prompt">
[{input}]
</div>
);
}
}
| // @flow
import React, { PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
export default class Inputs extends React.Component {
constructor(props) {
super(props);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
props: {
executionCount: any,
running: boolean,
};
render() {
const { executionCount, running } = this.props;
const count = !executionCount ? ' ' : executionCount;
const input = running ? '*' : count;
return (
<div className="prompt">
[{input}]
</div>
);
}
}
| Add Flow types to Inputs | chore(Inputs): Add Flow types to Inputs
| JavaScript | bsd-3-clause | temogen/nteract,jdetle/nteract,captainsafia/nteract,rgbkrk/nteract,captainsafia/nteract,nteract/composition,captainsafia/nteract,captainsafia/nteract,nteract/nteract,0u812/nteract,nteract/nteract,rgbkrk/nteract,rgbkrk/nteract,nteract/nteract,temogen/nteract,rgbkrk/nteract,jdfreder/nteract,jdfreder/nteract,rgbkrk/nteract,nteract/composition,nteract/nteract,nteract/nteract,temogen/nteract,0u812/nteract,jdetle/nteract,jdetle/nteract,nteract/composition,jdfreder/nteract,0u812/nteract,jdetle/nteract,0u812/nteract,jdfreder/nteract | ---
+++
@@ -1,16 +1,17 @@
+// @flow
import React, { PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
export default class Inputs extends React.Component {
- static propTypes = {
- executionCount: PropTypes.any,
- running: PropTypes.bool,
- };
-
constructor(props) {
super(props);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
+
+ props: {
+ executionCount: any,
+ running: boolean,
+ };
render() {
const { executionCount, running } = this.props; |
ddb89805a2e7c9a7b7a0b514a043a690a9704367 | app/js/services/login-service.js | app/js/services/login-service.js | angular.module('fleetonrails.services.login-service', [])
.service('LoginService', ['$http', 'GlobalSettings', function ($http, GlobalSettings) {
var loginWithPassword = function (email, password) {
var params = {
'grant_type': 'password',
'client_id': GlobalSettings.api_client_id,
'client_secret': GlobalSettings.api_client_secret,
'email': email,
'password': password
};
return $http({
method: 'POST',
url: GlobalSettings.api_base_url + '/oauth/token',
params: params
})
};
var loginWithRefreshToken = function () {
var params = {
'grant_type': 'refresh_token',
'client_id': '2abe8af97a1e45ee655b5f19d9fb4977990374c2a2895b4aaa6a9d80aa7edeeb',
'client_secret': '33d91b9efcea015b8acaff960ae49164c15da62ff895a253bbfd819b883ba5f6',
'refresh_token': localStorage.getItem("refresh_token")
};
return $http({
method: "POST",
url: GlobalSettings.api_base_url + '/oauth/token',
params: params
})
};
return {
loginWithPassword: loginWithPassword,
loginWithRefreshToken: loginWithRefreshToken
};
}]); | angular.module('fleetonrails.services.login-service', [])
.service('LoginService', ['$http', 'GlobalSettings', function ($http, GlobalSettings) {
var loginWithPassword = function (email, password) {
var params = {
'grant_type' : 'password',
'client_id' : GlobalSettings.api_client_id,
'client_secret' : GlobalSettings.api_client_secret,
'email' : email,
'password' : password
};
return $http({
method : 'POST',
url : GlobalSettings.api_base_url + '/oauth/token',
params : params
})
};
var loginWithRefreshToken = function () {
var params = {
'grant_type' : 'refresh_token',
'client_id' : GlobalSettings.api_client_id,
'client_secret' : GlobalSettings.api_client_secret,
'refresh_token' : localStorage.getItem("refresh_token")
};
return $http({
method : "POST",
url : GlobalSettings.api_base_url + '/oauth/token',
params : params
})
};
var logout = function () {
// TODO = implement a logout function
}
return {
loginWithPassword : loginWithPassword,
loginWithRefreshToken : loginWithRefreshToken,
logout : logout
};
}]); | Add some global variables. this will be handy when we change to production environment. just have to change a few variables. | Add some global variables. this will be handy when we change to production environment. just have to change a few variables.
| JavaScript | mit | FleetOnRails/fleet-web-app,FleetOnRails/fleet-web-app,FleetOnRails/fleet-web-app,FleetOnRails/fleet-web-app | ---
+++
@@ -3,36 +3,41 @@
.service('LoginService', ['$http', 'GlobalSettings', function ($http, GlobalSettings) {
var loginWithPassword = function (email, password) {
var params = {
- 'grant_type': 'password',
- 'client_id': GlobalSettings.api_client_id,
- 'client_secret': GlobalSettings.api_client_secret,
- 'email': email,
- 'password': password
+ 'grant_type' : 'password',
+ 'client_id' : GlobalSettings.api_client_id,
+ 'client_secret' : GlobalSettings.api_client_secret,
+ 'email' : email,
+ 'password' : password
};
return $http({
- method: 'POST',
- url: GlobalSettings.api_base_url + '/oauth/token',
- params: params
+ method : 'POST',
+ url : GlobalSettings.api_base_url + '/oauth/token',
+ params : params
})
};
var loginWithRefreshToken = function () {
var params = {
- 'grant_type': 'refresh_token',
- 'client_id': '2abe8af97a1e45ee655b5f19d9fb4977990374c2a2895b4aaa6a9d80aa7edeeb',
- 'client_secret': '33d91b9efcea015b8acaff960ae49164c15da62ff895a253bbfd819b883ba5f6',
- 'refresh_token': localStorage.getItem("refresh_token")
+ 'grant_type' : 'refresh_token',
+ 'client_id' : GlobalSettings.api_client_id,
+ 'client_secret' : GlobalSettings.api_client_secret,
+ 'refresh_token' : localStorage.getItem("refresh_token")
};
return $http({
- method: "POST",
- url: GlobalSettings.api_base_url + '/oauth/token',
- params: params
+ method : "POST",
+ url : GlobalSettings.api_base_url + '/oauth/token',
+ params : params
})
};
+ var logout = function () {
+// TODO = implement a logout function
+ }
+
return {
- loginWithPassword: loginWithPassword,
- loginWithRefreshToken: loginWithRefreshToken
+ loginWithPassword : loginWithPassword,
+ loginWithRefreshToken : loginWithRefreshToken,
+ logout : logout
};
}]); |
ac152b5051176d9a45a43a05aa0efa3f73399057 | src/scripts/app/cms/concepts/controller.js | src/scripts/app/cms/concepts/controller.js | 'use strict';
module.exports =
/*@ngInject*/
function ConceptsCmsCtrl (
$scope, ConceptsFBService, _
) {
ConceptsFBService.get().then(function (c) {
$scope.concepts = c;
console.log(c);
});
$scope.getQuestionLength = function (questions) {
return _.keys(questions).length;
};
$scope.getTotalConcepts = function (concepts) {
return _.keys(concepts).length;
};
$scope.getTotalQuestions = function (concepts) {
return _.reduce(concepts, function (sum, c) {
if (_.isNaN(sum)) {
sum = 0;
}
return Number(sum) + Number(_.keys(c.questions).length);
});
};
};
| 'use strict';
module.exports =
/*@ngInject*/
function ConceptsCmsCtrl (
$scope, ConceptsFBService, _
) {
ConceptsFBService.get().then(function (c) {
$scope.concepts = c;
});
$scope.getQuestionLength = function (questions) {
return _.keys(questions).length;
};
$scope.getTotalConcepts = function (concepts) {
return _.keys(concepts).length;
};
$scope.getTotalQuestions = function (concepts) {
return _.reduce(concepts, function (sum, c) {
if (_.isNaN(sum)) {
sum = 0;
}
return Number(sum) + Number(_.keys(c.questions).length);
});
};
};
| Remove log concepts in concepts ctrl | Remove log concepts in concepts ctrl
| JavaScript | agpl-3.0 | ddmck/Quill-Grammar,empirical-org/Quill-Grammar,empirical-org/Quill-Grammar,ddmck/Quill-Grammar,ddmck/Quill-Grammar,empirical-org/Quill-Grammar | ---
+++
@@ -8,7 +8,6 @@
) {
ConceptsFBService.get().then(function (c) {
$scope.concepts = c;
- console.log(c);
});
$scope.getQuestionLength = function (questions) { |
421c6cf22118c3b9cf28c8683199c34bd37fe931 | web/www/js/index.js | web/www/js/index.js | function loadData(view) {
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) {
var table = `<div class="table-responsive"><table class="table table-striped"><thead><tr>`;
view.headers.forEach(function (header) {
table += "<th>" + header.text + "</th>";
});
table += `</tr></thead><tbody>`;
view.data.forEach(function (datum) {
table += `<tr>`;
view.headers.forEach(function (header) {
table += "<td>" + getDescendantProp(datum, header.value) + "</td>";
});
table += `</tr>`;
});
table += `</tbody></table></div>`
$(".main").html(table);
$('table').DataTable({
"order": []
});
});
});
}
/* http://stackoverflow.com/a/8052100 */
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
loadData("matches"); | var views = [];
$.get("http://127.0.0.1:1338/views", function (views) {
window.views = views;
});
function loadData(view) {
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) {
var table = `<div class="table-responsive"><table class="table table-striped"><thead><tr>`;
view.headers.forEach(function (header) {
table += "<th>" + header.text + "</th>";
});
table += `</tr></thead><tbody>`;
view.data.forEach(function (datum) {
table += `<tr>`;
view.headers.forEach(function (header) {
table += "<td>" + getDescendantProp(datum, header.value) + "</td>";
});
table += `</tr>`;
});
table += `</tbody></table></div>`
$(".main").html(table);
$('table').DataTable({
"order": []
});
});
});
}
/* http://stackoverflow.com/a/8052100 */
function getDescendantProp(obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
}
loadData("matches"); | Write Views to Global Obj. | Write Views to Global Obj.
| JavaScript | bsd-2-clause | FRCteam4909/FRC-Scouting,FRCteam4909/FRC-Scouting,FRCteam4909/FRC-Scouting | ---
+++
@@ -1,3 +1,9 @@
+var views = [];
+
+$.get("http://127.0.0.1:1338/views", function (views) {
+ window.views = views;
+});
+
function loadData(view) {
$.get("http://127.0.0.1:1338/data/" + view, function (views) {
views.forEach(function (view) { |
2277378d2a3d9b211dd06fabe692f67d1577bff1 | grunt.js | grunt.js | /*global module: true*/
module.exports = function( grunt ) {
// Project configuration.
grunt.initConfig({
lint: {
files: [ "grunt.js", "sizzle.js", "test/unit/*.js" ]
},
qunit: {
files: [ "test/**/*.html" ]
},
watch: {
files: "<config:lint.files>",
tasks: "default"
},
jshint: {
options: {
evil: true,
browser: true,
wsh: true,
eqnull: true,
expr: true,
curly: true,
trailing: true,
undef: true,
smarttabs: true,
maxerr: 100
},
globals: {
jQuery: true
}
}
});
// Default task.
grunt.registerTask( "default", "lint" );
};
| /*global module: true*/
module.exports = function( grunt ) {
// Project configuration.
grunt.initConfig({
lint: {
files: [ "grunt.js", "sizzle.js", "test/unit/*.js" ]
},
qunit: {
files: [ "test/**/*.html" ]
},
watch: {
files: "<config:lint.files>",
tasks: "default"
},
jshint: {
options: {
evil: true,
browser: true,
wsh: true,
eqnull: true,
expr: true,
curly: true,
trailing: true,
undef: true,
smarttabs: true,
maxerr: 100
},
globals: {
jQuery: true,
define: true
}
}
});
// Default task.
grunt.registerTask( "default", "lint" );
};
| Add define to jshint globals | Add define to jshint globals
| JavaScript | mit | npmcomponent/cristiandouce-sizzle,mzgol/sizzle | ---
+++
@@ -27,7 +27,8 @@
maxerr: 100
},
globals: {
- jQuery: true
+ jQuery: true,
+ define: true
}
}
}); |
a3f8a7715347ee6c94940e2ac4f3d3fc6ee21cec | lib/handlers/patch/sparql-update-patcher.js | lib/handlers/patch/sparql-update-patcher.js | // Performs an application/sparql-update patch on a graph
module.exports = patch
const $rdf = require('rdflib')
const debug = require('../../debug').handlers
const error = require('../../http-error')
// Patches the given graph
function patch (targetKB, targetURI, patchText) {
return new Promise((resolve, reject) => {
// Parse the patch document
debug('PATCH -- Parsing patch...')
const patchURI = targetURI // @@@ beware the triples from the patch ending up in the same place
const patchKB = $rdf.graph()
var patchObject
try {
// Must parse relative to document's base address but patch doc should get diff URI
patchObject = $rdf.sparqlUpdateParser(patchText, patchKB, patchURI)
} catch (e) {
return reject(error(400, 'Patch format syntax error:\n' + e + '\n'))
}
debug('PATCH -- reading target file ...')
// Apply the patch to the target graph
var target = patchKB.sym(targetURI)
targetKB.applyPatch(patchObject, target, function (err) {
if (err) {
var message = err.message || err // returns string at the moment
debug('PATCH FAILED. Returning 409. Message: \'' + message + '\'')
return reject(error(409, 'Error when applying the patch'))
}
resolve(targetKB)
})
})
}
| // Performs an application/sparql-update patch on a graph
module.exports = patch
const $rdf = require('rdflib')
const debug = require('../../debug').handlers
const error = require('../../http-error')
// Patches the given graph
function patch (targetKB, targetURI, patchText) {
const patchKB = $rdf.graph()
const target = patchKB.sym(targetURI)
// Must parse relative to document's base address but patch doc should get diff URI
// @@@ beware the triples from the patch ending up in the same place
const patchURI = targetURI
return parsePatchDocument(patchURI, patchText, patchKB)
.then(patchObject => applyPatch(patchObject, target, targetKB))
}
// Parses the given SPARQL UPDATE document
function parsePatchDocument (patchURI, patchText, patchKB) {
debug('PATCH -- Parsing patch...')
return new Promise((resolve, reject) => {
try {
resolve($rdf.sparqlUpdateParser(patchText, patchKB, patchURI))
} catch (err) {
reject(error(400, 'Patch format syntax error:\n' + err + '\n'))
}
})
}
// Applies the patch to the target graph
function applyPatch (patchObject, target, targetKB) {
return new Promise((resolve, reject) =>
targetKB.applyPatch(patchObject, target, (err) => {
if (err) {
const message = err.message || err // returns string at the moment
debug('PATCH FAILED. Returning 409. Message: \'' + message + '\'')
return reject(error(409, 'Error when applying the patch'))
}
resolve(targetKB)
})
)
}
| Refactor SPARQL update patcher with promises. | Refactor SPARQL update patcher with promises.
This improves reuse for future parsers.
| JavaScript | mit | dmitrizagidulin/solid-server-unstable,linkeddata/ldnode,linkeddata/ldnode,dmitrizagidulin/solid-server-unstable,dmitrizagidulin/solid-server-unstable | ---
+++
@@ -8,29 +8,39 @@
// Patches the given graph
function patch (targetKB, targetURI, patchText) {
+ const patchKB = $rdf.graph()
+ const target = patchKB.sym(targetURI)
+
+ // Must parse relative to document's base address but patch doc should get diff URI
+ // @@@ beware the triples from the patch ending up in the same place
+ const patchURI = targetURI
+
+ return parsePatchDocument(patchURI, patchText, patchKB)
+ .then(patchObject => applyPatch(patchObject, target, targetKB))
+}
+
+// Parses the given SPARQL UPDATE document
+function parsePatchDocument (patchURI, patchText, patchKB) {
+ debug('PATCH -- Parsing patch...')
return new Promise((resolve, reject) => {
- // Parse the patch document
- debug('PATCH -- Parsing patch...')
- const patchURI = targetURI // @@@ beware the triples from the patch ending up in the same place
- const patchKB = $rdf.graph()
- var patchObject
try {
- // Must parse relative to document's base address but patch doc should get diff URI
- patchObject = $rdf.sparqlUpdateParser(patchText, patchKB, patchURI)
- } catch (e) {
- return reject(error(400, 'Patch format syntax error:\n' + e + '\n'))
+ resolve($rdf.sparqlUpdateParser(patchText, patchKB, patchURI))
+ } catch (err) {
+ reject(error(400, 'Patch format syntax error:\n' + err + '\n'))
}
- debug('PATCH -- reading target file ...')
+ })
+}
- // Apply the patch to the target graph
- var target = patchKB.sym(targetURI)
- targetKB.applyPatch(patchObject, target, function (err) {
+// Applies the patch to the target graph
+function applyPatch (patchObject, target, targetKB) {
+ return new Promise((resolve, reject) =>
+ targetKB.applyPatch(patchObject, target, (err) => {
if (err) {
- var message = err.message || err // returns string at the moment
+ const message = err.message || err // returns string at the moment
debug('PATCH FAILED. Returning 409. Message: \'' + message + '\'')
return reject(error(409, 'Error when applying the patch'))
}
resolve(targetKB)
})
- })
+ )
} |
cbe814a0b4c6aa0d73b422cf2410702898639f4e | lib/defaults.js | lib/defaults.js | /* jshint node: true */
'use strict';
module.exports.host = 'api.logentries.com';
module.exports.levels = [
'debug', 'info', 'notice', 'warning', 'err', 'crit', 'alert', 'emerg'
];
module.exports.bunyanLevels = [
'trace', 'debug', 'info', 'warn', 'error', 'fatal'
];
module.exports.port = 10000;
module.exports.portSecure = 20000;
module.exports.timeout = 3 * 60 * 1000;
| /* jshint node: true */
'use strict';
module.exports.host = 'data.logentries.com';
module.exports.levels = [
'debug', 'info', 'notice', 'warning', 'err', 'crit', 'alert', 'emerg'
];
module.exports.bunyanLevels = [
'trace', 'debug', 'info', 'warn', 'error', 'fatal'
];
module.exports.port = 80;
module.exports.portSecure = 443;
module.exports.timeout = 3 * 60 * 1000;
| Use ports 80&443 and data.logentries.com endpoint | Use ports 80&443 and data.logentries.com endpoint
| JavaScript | bsd-3-clause | bathos/logentries-client | ---
+++
@@ -1,7 +1,7 @@
/* jshint node: true */
'use strict';
-module.exports.host = 'api.logentries.com';
+module.exports.host = 'data.logentries.com';
module.exports.levels = [
'debug', 'info', 'notice', 'warning', 'err', 'crit', 'alert', 'emerg'
@@ -11,8 +11,8 @@
'trace', 'debug', 'info', 'warn', 'error', 'fatal'
];
-module.exports.port = 10000;
+module.exports.port = 80;
-module.exports.portSecure = 20000;
+module.exports.portSecure = 443;
module.exports.timeout = 3 * 60 * 1000; |
e7aa24eb6b83f9c95663afe20e250b25f344fdf3 | lib/install.js | lib/install.js | 'use strict';
const binBuild = require('bin-build');
const log = require('logalot');
const path = require('path');
const bin = require('.');
bin.run(['-version']).then(() => {
log.success('cwebp pre-build test passed successfully');
}).catch(error => {
log.warn(error.message);
log.warn('cwebp pre-build test failed');
log.info('compiling from source');
binBuild.file(path.resolve(__dirname, '../vendor/source/libwebp-1.1.0.tar.gz'), [
`./configure --disable-shared --prefix="${bin.dest()}" --bindir="${bin.dest()}"`,
'make && make install'
]).then(() => { // eslint-disable-line promise/prefer-await-to-then
log.success('cwebp built successfully');
}).catch(error => {
log.error(error.stack);
});
});
| 'use strict';
const binBuild = require('bin-build');
const log = require('logalot');
const path = require('path');
const bin = require('.');
bin.run(['-version']).then(() => {
log.success('cwebp pre-build test passed successfully');
}).catch(error => {
log.warn(error.message);
log.warn('cwebp pre-build test failed');
log.info('compiling from source');
binBuild.file(path.resolve(__dirname, '../vendor/source/libwebp-1.1.0.tar.gz'), [
`./configure --disable-shared --prefix="${bin.dest()}" --bindir="${bin.dest()}"`,
'make && make install'
]).then(() => { // eslint-disable-line promise/prefer-await-to-then
log.success('cwebp built successfully');
}).catch(error => {
log.error(error.stack);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
});
});
| Exit with non-zero when error occurs | Exit with non-zero when error occurs
| JavaScript | mit | imagemin/cwebp-bin | ---
+++
@@ -18,5 +18,8 @@
log.success('cwebp built successfully');
}).catch(error => {
log.error(error.stack);
+
+ // eslint-disable-next-line unicorn/no-process-exit
+ process.exit(1);
});
}); |
beb0616bb555211e6a2b4b49f1532fb0d74b2da7 | api/models/MembershipGroup.js | api/models/MembershipGroup.js | module.exports = {
attributes: {
child_group: {
model: 'Group'
},
parent_group: {
model: 'Group'
},
lastsynch: 'datetime',
active: 'boolean',
synchronized: 'boolean'
}
};
| module.exports = {
attributes: {
child_group: {
model: 'Group'
},
parent_group: {
model: 'Group'
},
lastsynch: 'datetime',
active: 'boolean',
synchronized: 'boolean'
},
afterCreate: async (newlyCreatedRecord, proceed) => {
await SqlService.refreshMaterializedView('person');
proceed();
},
afterUpdate: async (updatedRecord, proceed) => {
await SqlService.refreshMaterializedView('person');
proceed();
},
afterDestroy: async (destroyedRecord, proceed) => {
await SqlService.refreshMaterializedView('person');
proceed();
}
};
| Add afterCreate, afterUpdate, afterDestroy for membershipgroup: update person view | Add afterCreate, afterUpdate, afterDestroy for membershipgroup: update person view
| JavaScript | mit | scientilla/scientilla,scientilla/scientilla,scientilla/scientilla | ---
+++
@@ -9,5 +9,17 @@
lastsynch: 'datetime',
active: 'boolean',
synchronized: 'boolean'
+ },
+ afterCreate: async (newlyCreatedRecord, proceed) => {
+ await SqlService.refreshMaterializedView('person');
+ proceed();
+ },
+ afterUpdate: async (updatedRecord, proceed) => {
+ await SqlService.refreshMaterializedView('person');
+ proceed();
+ },
+ afterDestroy: async (destroyedRecord, proceed) => {
+ await SqlService.refreshMaterializedView('person');
+ proceed();
}
}; |
c158dc6d285f28eae9197a942c79e9537071fc39 | example/run-example.js | example/run-example.js | require('coffee-script/register');
var path = require('path');
var Jasmine = require('jasmine');
var SpecReporter = require('../src/jasmine-spec-reporter.js');
var noop = function () {};
var jrunner = new Jasmine();
jrunner.configureDefaultReporter({print: noop});
jasmine.getEnv().addReporter(new SpecReporter({
displayStacktrace: 'none',
displayFailuresSummary: true,
displayPendingSummary: true,
displaySuccessfulSpec: true,
displayFailedSpec: true,
displayPendingSpec: true,
displaySpecDuration: false,
displaySuiteNumber: false,
colors: {
success: 'green',
failure: 'red',
pending: 'yellow'
},
prefixes: {
success: '✓ ',
failure: '✗ ',
pending: '* '
},
customProcessors: []
}));
jrunner.projectBaseDir = '';
jrunner.specDir = '';
jrunner.addSpecFiles([path.resolve('example/example-spec.coffee')]);
jrunner.execute();
| require('coffee-script/register');
var path = require('path');
var Jasmine = require('jasmine');
var SpecReporter = require('../src/jasmine-spec-reporter.js');
var noop = function () {};
var jrunner = new Jasmine();
jrunner.configureDefaultReporter({print: noop});
jasmine.getEnv().addReporter(new SpecReporter({
displayStacktrace: 'none',
displayFailuresSummary: true,
displayPendingSummary: true,
displaySuccessfulSpec: true,
displayFailedSpec: true,
displayPendingSpec: true,
displaySpecDuration: false,
displaySuiteNumber: false,
colors: {
success: 'green',
failure: 'red',
pending: 'yellow'
},
prefixes: {
success: '✓ ',
failure: '✗ ',
pending: '* '
},
customProcessors: []
}));
jrunner.projectBaseDir = '';
jrunner.specDir = '';
jrunner.randomizeTests(false);
jrunner.addSpecFiles([path.resolve('example/example-spec.coffee')]);
jrunner.execute();
| Add randomized option for example | Add randomized option for example
| JavaScript | apache-2.0 | bcaudan/jasmine-spec-reporter,nbuso/protractor-html-spec-reporter,nbuso/protractor-html-spec-reporter,bcaudan/jasmine-spec-reporter | ---
+++
@@ -29,5 +29,6 @@
}));
jrunner.projectBaseDir = '';
jrunner.specDir = '';
+jrunner.randomizeTests(false);
jrunner.addSpecFiles([path.resolve('example/example-spec.coffee')]);
jrunner.execute(); |
3a848855fcc4395d03be9d2fc5c5d7cef85b4459 | lib/systemd.js | lib/systemd.js | var net = require('net');
var Server = net.Server.prototype;
var Pipe = process.binding('pipe_wrap').Pipe;
var oldListen = Server.listen;
Server.listen = function () {
var self = this;
if (arguments.length === 1 && arguments[0] === 'systemd') {
if (!process.env.LISTEN_FDS || process.env.LISTEN_FDS !== 1) {
throw('No or too many file descriptors received.');
}
self._handle = new Pipe();
self._handle.open(3);
self._listen2(null, -1, -1);
} else {
oldListen.apply(self, arguments);
}
};
| var net = require('net');
var Server = net.Server.prototype;
var Pipe = process.binding('pipe_wrap').Pipe;
var oldListen = Server.listen;
Server.listen = function () {
var self = this;
if (arguments.length === 1 && arguments[0] === 'systemd') {
if (!process.env.LISTEN_FDS || process.env.LISTEN_FDS !== 1) {
throw(new Error('No or too many file descriptors received.'));
}
self._handle = new Pipe();
self._handle.open(3);
self._listen2(null, -1, -1);
} else {
oldListen.apply(self, arguments);
}
};
| Throw an error instead of a string. | Throw an error instead of a string.
Related to https://github.com/rubenv/node-systemd/issues/5 (#5).
| JavaScript | mit | stephank/node-systemd,rubenv/node-systemd,kapouer/node-systemd | ---
+++
@@ -9,7 +9,7 @@
if (arguments.length === 1 && arguments[0] === 'systemd') {
if (!process.env.LISTEN_FDS || process.env.LISTEN_FDS !== 1) {
- throw('No or too many file descriptors received.');
+ throw(new Error('No or too many file descriptors received.'));
}
self._handle = new Pipe(); |
e2502f2436d9ed0c2d534fddacf31d6a3d82df90 | worker.js | worker.js | require('newrelic')
var DateTime = require('dateutils').DateTime
var dao = require('./src/dao')
var daysAhead = 0
var maxDaysAhead = 60
doRefresh()
setInterval(() => {
doRefresh()
}, 1000 * 60 * 10)
function doRefresh() {
dao.refresh(new DateTime().plusDays(daysAhead).toISODateString(), 1, () => { })
if (daysAhead > maxDaysAhead) daysAhead = 0
else daysAhead++
}
| require('newrelic')
var DateTime = require('dateutils').DateTime
var dao = require('./src/dao')
var daysAhead = 0
var maxDaysAhead = 60
doRefresh()
setInterval(() => {
doRefresh()
}, 1000 * 60 * 5)
function doRefresh() {
dao.refresh(new DateTime().plusDays(daysAhead).toISODateString(), 1, () => { })
if (daysAhead > maxDaysAhead) daysAhead = 0
else daysAhead++
}
| Make updating twice more frequent: calls every 5 minutes | Make updating twice more frequent: calls every 5 minutes
| JavaScript | apache-2.0 | eeroan/tennishelsinki,eeroan/tennisvuorot,eeroan/tennisvuorot,eeroan/tennisvuorot,eeroan/tennishelsinki | ---
+++
@@ -7,7 +7,7 @@
doRefresh()
setInterval(() => {
doRefresh()
-}, 1000 * 60 * 10)
+}, 1000 * 60 * 5)
function doRefresh() {
dao.refresh(new DateTime().plusDays(daysAhead).toISODateString(), 1, () => { }) |
0ce21c74ac2e121547a742f5fd2bf15231c1ad65 | index.js | index.js | const marked = require("marked")
module.exports = function () {
this.filter("transformerName", (source, options) => {
try {
return source
} catch (e) { throw e }
})
}
| const marked = require("marked")
module.exports = function () {
this.filter("transformerName", (source, options) => {
try {
return marked(src)
} catch (e) { throw e }
})
}
| Add marked and call it | Add marked and call it
| JavaScript | mit | MadcapJake/fly-marked | ---
+++
@@ -2,7 +2,7 @@
module.exports = function () {
this.filter("transformerName", (source, options) => {
try {
- return source
+ return marked(src)
} catch (e) { throw e }
})
} |
2032587b60965620a6f0bd9d8a040e6f3e098413 | index.js | index.js | const dotenv = require('dotenv-safe');
const fs = require('fs');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = DotenvPlugin;
function DotenvPlugin(options) {
options = options || {};
if (!options.sample) options.sample = './.env.default';
if (!options.path) options.path = './.env';
dotenv.config(options);
this.example = dotenv.parse(fs.readFileSync(options.sample));
this.env = dotenv.parse(fs.readFileSync(options.path));
}
DotenvPlugin.prototype.apply = function(compiler) {
const plugin = Object.keys(this.example).reduce((definitions, key) => {
const existing = process.env[key];
if (existing) {
definitions[`process.env.${key}`] = JSON.stringify(existing);
return definitions;
}
const value = this.env[key];
if (value) definitions[`process.env.${key}`] = JSON.stringify(value);
return definitions;
}, {});
compiler.apply(new DefinePlugin(plugin));
};
| const dotenv = require('dotenv-safe');
const fs = require('fs');
const DefinePlugin = require('webpack').DefinePlugin;
module.exports = DotenvPlugin;
function DotenvPlugin(options) {
options = options || {};
if (!options.sample) options.sample = './.env.default';
if (!options.path) options.path = './.env';
dotenv.config(options);
this.example = dotenv.parse(fs.readFileSync(options.sample));
this.env = dotenv.parse(fs.readFileSync(options.path));
}
DotenvPlugin.prototype.apply = function(compiler) {
const definitions = Object.keys(this.example).reduce((definitions, key) => {
const existing = process.env[key];
if (existing) {
definitions[key] = JSON.stringify(existing);
return definitions;
}
const value = this.env[key];
if (value) definitions[key] = JSON.stringify(value);
return definitions;
}, {});
const plugin = {
'process.env': definitions,
};
compiler.apply(new DefinePlugin(plugin));
};
| Make fix to use process.env as a global variable and not process.env.KEY | Make fix to use process.env as a global variable and not process.env.KEY
| JavaScript | mit | nwinch/webpack-dotenv-plugin | ---
+++
@@ -15,19 +15,23 @@
}
DotenvPlugin.prototype.apply = function(compiler) {
- const plugin = Object.keys(this.example).reduce((definitions, key) => {
+ const definitions = Object.keys(this.example).reduce((definitions, key) => {
const existing = process.env[key];
if (existing) {
- definitions[`process.env.${key}`] = JSON.stringify(existing);
+ definitions[key] = JSON.stringify(existing);
return definitions;
}
const value = this.env[key];
- if (value) definitions[`process.env.${key}`] = JSON.stringify(value);
+ if (value) definitions[key] = JSON.stringify(value);
return definitions;
}, {});
+ const plugin = {
+ 'process.env': definitions,
+ };
+
compiler.apply(new DefinePlugin(plugin));
}; |
adddbc8b13d7495c97681071246a813bb4fb2059 | index.js | index.js | var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');
(function() {
function readConfig(callback) {
try {
var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
if (doc.config !== undefined && doc.config.port !== undefined &&
doc.config.path !== undefined && doc.config.secret !== undefined) {
callback(undefined, doc.config);
} else {
callback("Malformed .deploy.yml.", undefined);
}
} catch (e) {
callback(e, undefined);
}
}
readConfig(function(err, data) {
if (err) {
console.log(err);
} else {
var pot = new chimneypot({
port: data.port,
path: data.path,
secret: data.secret
});
pot.route('push', function (event) {
spawn('sh', ['pull.sh']);
});
pot.listen();
}
});
})();
| var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');
(function() {
function readConfig(callback) {
var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
if (doc.config !== undefined && doc.config.port !== undefined &&
doc.config.path !== undefined && doc.config.secret !== undefined) {
callback(undefined, doc.config);
} else {
callback("Malformed .deploy.yml.", undefined);
}
}
readConfig(function(err, data) {
if (err) {
console.log(err);
} else {
var pot = new chimneypot({
port: data.port,
path: data.path,
secret: data.secret
});
pot.route('push', function (event) {
spawn('sh', ['pull.sh']);
});
pot.listen();
}
});
})();
| Remove callback on error - let the error bubble up | Remove callback on error - let the error bubble up
| JavaScript | unlicense | WDOTS/deploy,WDOTS/deploy | ---
+++
@@ -6,16 +6,13 @@
(function() {
function readConfig(callback) {
- try {
- var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
- if (doc.config !== undefined && doc.config.port !== undefined &&
- doc.config.path !== undefined && doc.config.secret !== undefined) {
- callback(undefined, doc.config);
- } else {
- callback("Malformed .deploy.yml.", undefined);
- }
- } catch (e) {
- callback(e, undefined);
+ var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
+
+ if (doc.config !== undefined && doc.config.port !== undefined &&
+ doc.config.path !== undefined && doc.config.secret !== undefined) {
+ callback(undefined, doc.config);
+ } else {
+ callback("Malformed .deploy.yml.", undefined);
}
}
|
4096ba80cf5b96b95713e3a8ba6d2ec0a0fb6817 | index.js | index.js | import * as components from './components';
const VuePlugin = {
install(Vue){
if (VuePlugin.installed) return;
VuePlugin.installed = true;
for (let key in components) {
Vue.component(key, components[key])
}
}
};
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(VuePlugin);
}
export default VuePlugin; | import * as components from './components';
const VuePlugin = {
install: function (Vue) {
if (VuePlugin.installed) return;
VuePlugin.installed = true;
for (let key in components) {
Vue.component(key, components[key])
}
}
};
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(VuePlugin);
}
export default VuePlugin; | Use old function syntax for better UglifyJs compability | Use old function syntax for better UglifyJs compability
| JavaScript | mit | wheldring/bootstrap-vue-compiled,sschadwick/bootstrap-vue,mosinve/bootstrap-vue,mosinve/bootstrap-vue,SirLamer/bootstrap-vue,sschadwick/bootstrap-vue,bootstrap-vue/bootstrap-vue,sschadwick/bootstrap-vue,SirLamer/bootstrap-vue,bootstrap-vue/bootstrap-vue,wheldring/bootstrap-vue-compiled,wheldring/bootstrap-vue-compiled,tmorehouse/bootstrap-vue,tmorehouse/bootstrap-vue | ---
+++
@@ -1,7 +1,7 @@
import * as components from './components';
const VuePlugin = {
- install(Vue){
+ install: function (Vue) {
if (VuePlugin.installed) return;
VuePlugin.installed = true;
for (let key in components) { |
6a4c9a4d035dc2725821530ca9ad670947e9682f | index.js | index.js | var Filter = require('broccoli-filter')
var coffeeScript = require('coffee-script')
module.exports = CoffeeScriptFilter
CoffeeScriptFilter.prototype = Object.create(Filter.prototype)
CoffeeScriptFilter.prototype.constructor = CoffeeScriptFilter
function CoffeeScriptFilter (inputTree, options) {
if (!(this instanceof CoffeeScriptFilter)) return new CoffeeScriptFilter(inputTree, options)
Filter.call(this, inputTree, options)
options = options || {}
this.bare = options.bare
}
CoffeeScriptFilter.prototype.extensions = ['coffee']
CoffeeScriptFilter.prototype.targetExtension = 'js'
CoffeeScriptFilter.prototype.processString = function (string) {
var coffeeScriptOptions = { bare: this.bare }
try {
return coffeeScript.compile(string, coffeeScriptOptions)
} catch (err) {
err.line = err.location && err.location.first_line
err.column = err.location && err.location.first_column
throw err
}
}
| var Filter = require('broccoli-filter')
var coffeeScript = require('coffee-script')
module.exports = CoffeeScriptFilter
CoffeeScriptFilter.prototype = Object.create(Filter.prototype)
CoffeeScriptFilter.prototype.constructor = CoffeeScriptFilter
function CoffeeScriptFilter (inputTree, options) {
if (!(this instanceof CoffeeScriptFilter)) return new CoffeeScriptFilter(inputTree, options)
Filter.call(this, inputTree, options)
options = options || {}
this.bare = options.bare
}
CoffeeScriptFilter.prototype.extensions = ['coffee','litcoffee','coffee.md']
CoffeeScriptFilter.prototype.targetExtension = 'js'
CoffeeScriptFilter.prototype.processString = function (string) {
var coffeeScriptOptions = { bare: this.bare }
try {
return coffeeScript.compile(string, coffeeScriptOptions)
} catch (err) {
err.line = err.location && err.location.first_line
err.column = err.location && err.location.first_column
throw err
}
}
| Add support for literate coffeescript files | Add support for literate coffeescript files
Although the CoffeeScript processor can handle [literate CoffeeScript](http://coffeescript.org/#literate) files, they were not being included in the filter.
| JavaScript | mit | tsing80/broccoli-coffee,joliss/broccoli-coffee,timmfin/broccoli-coffee | ---
+++
@@ -11,7 +11,7 @@
this.bare = options.bare
}
-CoffeeScriptFilter.prototype.extensions = ['coffee']
+CoffeeScriptFilter.prototype.extensions = ['coffee','litcoffee','coffee.md']
CoffeeScriptFilter.prototype.targetExtension = 'js'
CoffeeScriptFilter.prototype.processString = function (string) { |
e3e433a08c6c99f7a2b6b58a6cd425aef58081fb | index.js | index.js | var Rx = require('rx'),
_ = require('lodash');
function readMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
readMessage(sqs, params, callback);
});
}
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.create(function (observer) {
readMessage(sqs, params, function (err, data) {
if (err) {
observer.onError(err);
} else if (data && data.Messages) {
_.forEach(data.Messages, function (message) {
observer.onNext(message);
});
}
return function () {
/* Clean up */
};
});
});
}; | var Rx = require('rx'),
_ = require('lodash');
function receiveMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
receiveMessage(sqs, params, callback);
});
}
exports.observerFromQueue = function (sqs, params) {
return Rx.Observer.create(function (messageParams) {
sqs.sendMessage(_.defaults(messageParams, params), function (err, data) {
});
});
};
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.create(function (observer) {
receiveMessage(sqs, params, function (err, data) {
if (err) {
observer.onError(err);
} else if (data && data.Messages) {
_.forEach(data.Messages, function (message) {
observer.onNext(message);
});
}
return function () {
/* Clean up */
};
});
});
};
| Support for pushing to a queue via observer. | Support for pushing to a queue via observer.
| JavaScript | mit | lebek/RxSQS | ---
+++
@@ -1,16 +1,24 @@
var Rx = require('rx'),
_ = require('lodash');
-function readMessage(sqs, params, callback) {
+function receiveMessage(sqs, params, callback) {
sqs.receiveMessage(params, function (err, data) {
callback(err, data);
- readMessage(sqs, params, callback);
+ receiveMessage(sqs, params, callback);
});
}
+exports.observerFromQueue = function (sqs, params) {
+ return Rx.Observer.create(function (messageParams) {
+ sqs.sendMessage(_.defaults(messageParams, params), function (err, data) {
+
+ });
+ });
+};
+
exports.observableFromQueue = function (sqs, params) {
return Rx.Observable.create(function (observer) {
- readMessage(sqs, params, function (err, data) {
+ receiveMessage(sqs, params, function (err, data) {
if (err) {
observer.onError(err); |
90b96de8a1bda1218591787e709de7d6450618fc | index.js | index.js | 'use strict';
var ExecBuffer = require('exec-buffer');
var imageType = require('image-type');
var through = require('through2');
var webp = require('cwebp-bin').path;
/**
* webp imagemin plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
opts = opts || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (['jpg', 'png', 'tif'].indexOf(imageType(file.contents)) === -1) {
cb(null, file);
return;
}
var exec = new ExecBuffer();
var args = ['-quiet'];
exec
.use(webp, args.concat([exec.src(), '-o', exec.dest()]))
.run(file.contents, function (err, buf) {
if (err) {
cb(err);
return;
}
file.contents = buf;
cb(null, file);
});
});
};
| 'use strict';
var ExecBuffer = require('exec-buffer');
var imageType = require('image-type');
var path = require('path');
var through = require('through2');
var webp = require('cwebp-bin').path;
/**
* webp imagemin plugin
*
* @param {Object} opts
* @api public
*/
module.exports = function (opts) {
opts = opts || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
cb(null, file);
return;
}
if (file.isStream()) {
cb(new Error('Streaming is not supported'));
return;
}
if (['jpg', 'png', 'tif'].indexOf(imageType(file.contents)) === -1) {
cb(null, file);
return;
}
var exec = new ExecBuffer();
var args = ['-quiet'];
exec
.use(webp, args.concat([exec.src(), '-o', exec.dest()]))
.run(file.contents, function (err, buf) {
if (err) {
cb(err);
return;
}
if (file.path && typeof file.path === 'string') {
var name = path.basename(file.path, path.extname(file.path)) + '.webp';
file.path = path.join(path.dirname(file.path), name);
}
file.contents = buf;
cb(null, file);
});
});
};
| Replace file extension when optimizing | Replace file extension when optimizing
| JavaScript | mit | imagemin/imagemin-webp | ---
+++
@@ -2,6 +2,7 @@
var ExecBuffer = require('exec-buffer');
var imageType = require('image-type');
+var path = require('path');
var through = require('through2');
var webp = require('cwebp-bin').path;
@@ -42,6 +43,11 @@
return;
}
+ if (file.path && typeof file.path === 'string') {
+ var name = path.basename(file.path, path.extname(file.path)) + '.webp';
+ file.path = path.join(path.dirname(file.path), name);
+ }
+
file.contents = buf;
cb(null, file);
}); |
854f861c6e85c9e024885aa634623f38fa345254 | index.js | index.js | const Octokat = require('octokat')
const open = require('open')
const Promise = require('bluebird')
var octo, organization, repository
module.exports = function openNotifications (input, opts, token) {
octo = new Octokat({
token: token || process.env.GITHUB_OGN_TOKEN
})
var amount = opts.amount || 30
if (input[0].split('/').length === 2) {
organization = input[0].split('/')[0]
repository = input[0].split('/')[1]
if (Number.isInteger(input[1])) {
amount = input[1]
}
} else {
organization = input[0]
repository = input[1]
amount = input[2] || amount
}
return Promise.resolve().then(() => {
if (!organization && !repository) {
return octo.notifications.fetch({
participating: opts.participating || false
})
} else {
return octo.repos(organization, repository, 'notifications').fetch()
}
}).then((result) => {
if (result) {
return Promise.some(result, amount).map((repo) => {
var res = repo.subject.url
.replace(/(https\:\/\/)api\./, '$1')
.replace(/\/repos\//, '/')
.replace(/\/pulls\//, '/pull/')
open(res)
return `Opened notifications.`
})
} else {
return `No notifications.`
}
}).catch((err) => {
console.log(err)
})
}
| const Octokat = require('octokat')
const open = require('open')
const Promise = require('bluebird')
var octo, organization, repository
module.exports = function openNotifications (input, opts, token) {
octo = new Octokat({
token: token || process.env.GITHUB_OGN_TOKEN
})
var amount = opts.amount || 30
if (input[0].split('/').length === 2) {
organization = input[0].split('/')[0]
repository = input[0].split('/')[1]
if (Number.isInteger(input[1])) {
amount = input[1]
}
} else {
organization = input[0]
repository = input[1]
amount = input[2] || amount
}
return Promise.resolve().then(() => {
if (!organization && !repository) {
return octo.notifications.fetch({
participating: opts.participating || false
})
} else {
return octo.repos(organization, repository, 'notifications').fetch()
}
}).then((result) => {
if (result) {
if (result.length < amount) {
amount = result.length
}
return Promise.some(result, amount).map((repo) => {
var res = repo.subject.url
.replace(/(https\:\/\/)api\./, '$1')
.replace(/\/repos\//, '/')
.replace(/\/pulls\//, '/pull/')
open(res)
}).then(() => `Opened notifications.`)
} else {
return `No notifications.`
}
}).catch((err) => {
console.log(err)
})
}
| Fix some amount, returned one log | Fix some amount, returned one log
| JavaScript | mit | RichardLitt/open-github-notifications | ---
+++
@@ -31,14 +31,16 @@
}
}).then((result) => {
if (result) {
+ if (result.length < amount) {
+ amount = result.length
+ }
return Promise.some(result, amount).map((repo) => {
var res = repo.subject.url
.replace(/(https\:\/\/)api\./, '$1')
.replace(/\/repos\//, '/')
.replace(/\/pulls\//, '/pull/')
open(res)
- return `Opened notifications.`
- })
+ }).then(() => `Opened notifications.`)
} else {
return `No notifications.`
} |
2b37b4b4f5131333b3101eb9bafb4e8715cd71bf | index.js | index.js | var extractHearingType = function(hearingRow) {
return hearingRow.querySelectorAll('td')[4].textContent.trim();
};
var isPrelim = function(hearingRow) {
return extractHearingType(hearingRow) == "PRELIMINARY HEARING";
};
var hearingNodes = function() {
return document.querySelectorAll('tr[id^="tr_row"]');
};
var nodeListToArray = function(nodeList) {
var a = [];
for (var i = 0, l = nodeList.length; i < l; i += 1) {
a[a.length] = nodeList[i];
};
return a;
};
var extractHearings = function() {
return nodeListToArray(hearingNodes());
};
var filterPrelims = function(hearings) {
return hearings.filter(isPrelim);
};
var hearings = extractHearings();
var prelims = filterPrelims(hearings);
console.log("There are " + hearings.length + " hearings.");
console.log("There are " + prelims.length + " prelims.");
| var getUrl = function(url, callback) {
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", callback);
oReq.open("GET", url);
oReq.send();
}
var extractHearingType = function(hearingRow) {
return hearingRow.querySelectorAll('td')[4].textContent.trim();
};
var extractCaseReportLink = function(hearingRow) {
return hearingRow.querySelectorAll('td')[2].querySelector('a').href.replace('criminalcalendar', 'criminalcasereport');
};
var isPrelim = function(hearingRow) {
return extractHearingType(hearingRow) == "PRELIMINARY HEARING";
};
var hearingNodes = function() {
return document.querySelectorAll('tr[id^="tr_row"]');
};
var nodeListToArray = function(nodeList) {
var a = [];
for (var i = 0, l = nodeList.length; i < l; i += 1) {
a[a.length] = nodeList[i];
};
return a;
};
var extractHearings = function() {
return nodeListToArray(hearingNodes());
};
var filterPrelims = function(hearings) {
return hearings.filter(isPrelim);
};
var hearings = extractHearings();
var prelims = filterPrelims(hearings);
var prelimLinks = prelims.forEach(extractCaseReportLink);
console.log("There are " + hearings.length + " hearings.");
console.log("There are " + prelims.length + " prelims.");
console.log(prelimLinks);
| Add functions to get case report links | Add functions to get case report links | JavaScript | mit | jluckyiv/ja_prep | ---
+++
@@ -1,5 +1,15 @@
+var getUrl = function(url, callback) {
+ var oReq = new XMLHttpRequest();
+ oReq.addEventListener("load", callback);
+ oReq.open("GET", url);
+ oReq.send();
+}
+
var extractHearingType = function(hearingRow) {
return hearingRow.querySelectorAll('td')[4].textContent.trim();
+};
+var extractCaseReportLink = function(hearingRow) {
+ return hearingRow.querySelectorAll('td')[2].querySelector('a').href.replace('criminalcalendar', 'criminalcasereport');
};
var isPrelim = function(hearingRow) {
return extractHearingType(hearingRow) == "PRELIMINARY HEARING";
@@ -22,5 +32,7 @@
};
var hearings = extractHearings();
var prelims = filterPrelims(hearings);
+var prelimLinks = prelims.forEach(extractCaseReportLink);
console.log("There are " + hearings.length + " hearings.");
console.log("There are " + prelims.length + " prelims.");
+console.log(prelimLinks); |
24b07ca09f8f85520b1f5303f96f1431f7077785 | index.js | index.js | require('font-awesome-webpack');
window.$ = require('jquery');
require('./css/html_styles.scss');
require('./css/set_view.scss');
require('./css/element_view.scss');
require('script!./event-manager');
require('script!./venn');
require('script!./utilities');
require('script!./attribute');
require('script!./viewer/word-cloud');
require('script!./viewer/scatterplot');
require('script!./viewer/histogram');
require('script!./viewer/variant-frequency');
require('script!./element-viewer');
require('script!./dataLoading');
require('script!./filter');
require('script!./selection');
require('script!./dataStructure');
require('script!./ui');
require('script!./setSelection');
require('script!./sort');
require('script!./highlight');
require('script!./scrollbar');
require('script!./items');
require('script!./setGrouping');
require('script!./logicPanel');
require('script!./brushableScale');
require('script!./statisticGraphs');
require('script!./upset');
module.exports = {
UpSet: window.UpSet,
Ui: window.Ui
};
| require('font-awesome-webpack');
window.$ = require('jquery');
require('./css/html_styles.scss');
require('./css/set_view.scss');
require('./css/element_view.scss');
require('script-loader!./event-manager');
require('script-loader!./venn');
require('script-loader!./utilities');
require('script-loader!./attribute');
require('script-loader!./viewer/word-cloud');
require('script-loader!./viewer/scatterplot');
require('script-loader!./viewer/histogram');
require('script-loader!./viewer/variant-frequency');
require('script-loader!./element-viewer');
require('script-loader!./dataLoading');
require('script-loader!./filter');
require('script-loader!./selection');
require('script-loader!./dataStructure');
require('script-loader!./ui');
require('script-loader!./setSelection');
require('script-loader!./sort');
require('script-loader!./highlight');
require('script-loader!./scrollbar');
require('script-loader!./items');
require('script-loader!./setGrouping');
require('script-loader!./logicPanel');
require('script-loader!./brushableScale');
require('script-loader!./statisticGraphs');
require('script-loader!./upset');
module.exports = {
UpSet: window.UpSet,
Ui: window.Ui
};
| Replace inline 'script!' with 'script-loader!' | Replace inline 'script!' with 'script-loader!'
This change is necessary to allow this module to properly work with newer
versions of Webpack.
| JavaScript | mit | VCG/upset,VCG/upset,VCG/upset,VCG/upset | ---
+++
@@ -5,30 +5,30 @@
require('./css/set_view.scss');
require('./css/element_view.scss');
-require('script!./event-manager');
-require('script!./venn');
-require('script!./utilities');
-require('script!./attribute');
-require('script!./viewer/word-cloud');
-require('script!./viewer/scatterplot');
-require('script!./viewer/histogram');
-require('script!./viewer/variant-frequency');
-require('script!./element-viewer');
-require('script!./dataLoading');
-require('script!./filter');
-require('script!./selection');
-require('script!./dataStructure');
-require('script!./ui');
-require('script!./setSelection');
-require('script!./sort');
-require('script!./highlight');
-require('script!./scrollbar');
-require('script!./items');
-require('script!./setGrouping');
-require('script!./logicPanel');
-require('script!./brushableScale');
-require('script!./statisticGraphs');
-require('script!./upset');
+require('script-loader!./event-manager');
+require('script-loader!./venn');
+require('script-loader!./utilities');
+require('script-loader!./attribute');
+require('script-loader!./viewer/word-cloud');
+require('script-loader!./viewer/scatterplot');
+require('script-loader!./viewer/histogram');
+require('script-loader!./viewer/variant-frequency');
+require('script-loader!./element-viewer');
+require('script-loader!./dataLoading');
+require('script-loader!./filter');
+require('script-loader!./selection');
+require('script-loader!./dataStructure');
+require('script-loader!./ui');
+require('script-loader!./setSelection');
+require('script-loader!./sort');
+require('script-loader!./highlight');
+require('script-loader!./scrollbar');
+require('script-loader!./items');
+require('script-loader!./setGrouping');
+require('script-loader!./logicPanel');
+require('script-loader!./brushableScale');
+require('script-loader!./statisticGraphs');
+require('script-loader!./upset');
module.exports = {
UpSet: window.UpSet, |
52f0112d546f750fd6dc01a9c0517015d7cd3a34 | index.js | index.js | var loaderUtils = require("loader-utils");
module.exports = function(source, map) {
this.callback(null, source, map);
};
module.exports.pitch = function(remainingRequest) {
this.cacheable();
return `
// classnames-loader: automatically bind css-modules to classnames
var classNames = require(${loaderUtils.stringifyRequest(this, '!' + require.resolve('classnames/bind'))});
var locals = require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)});
var css = classNames.bind(locals);
for (var style in locals) {
if (!locals.hasOwnProperty(style)) {
continue;
}
if (typeof Object.defineProperty === 'function') {
Object.defineProperty(css, style, {value: locals[style]});
}
else {
css[style] = locals[style];
}
}
module.exports = css;
`;
}
| var loaderUtils = require("loader-utils");
module.exports = function(source, map) {
this.callback(null, source, map);
};
module.exports.pitch = function(remainingRequest) {
this.cacheable();
return `
// classnames-loader: automatically bind css-modules to classnames
function interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var classNames = require(${loaderUtils.stringifyRequest(this, '!' + require.resolve('classnames/bind'))});
var locals = interopRequireDefault(require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)})).default;
var css = classNames.bind(locals);
for (var style in locals) {
if (!locals.hasOwnProperty(style)) {
continue;
}
if (typeof Object.defineProperty === 'function') {
Object.defineProperty(css, style, {value: locals[style]});
}
else {
css[style] = locals[style];
}
}
module.exports = css;
`;
};
| Support ES module exported class names | Support ES module exported class names
| JavaScript | mit | itsmepetrov/classnames-loader | ---
+++
@@ -8,8 +8,11 @@
this.cacheable();
return `
// classnames-loader: automatically bind css-modules to classnames
+ function interopRequireDefault(obj) {
+ return obj && obj.__esModule ? obj : {default: obj};
+ }
var classNames = require(${loaderUtils.stringifyRequest(this, '!' + require.resolve('classnames/bind'))});
- var locals = require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)});
+ var locals = interopRequireDefault(require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)})).default;
var css = classNames.bind(locals);
for (var style in locals) {
if (!locals.hasOwnProperty(style)) {
@@ -24,4 +27,4 @@
}
module.exports = css;
`;
-}
+}; |
91938eea868e9e21cb025bc4ea2f693465094838 | index.js | index.js | var readPackageTree = require("read-package-tree");
module.exports = function(dir, cb) {
readPackageTree(dir, function(err, root) {
if (err) {
cb(err);
return;
}
var isUpToDate = root.children.every(function(child) {
var currentVersion = child.package.version;
var wantedVersion = root.package.dependencies[child.package.name];
return !wantedVersion || currentVersion === wantedVersion;
});
cb(null, isUpToDate);
});
};
| var readPackageTree = require("read-package-tree");
module.exports = function(dir, cb) {
readPackageTree(dir, function(err, root) {
if (err) {
cb(err);
return;
}
var wantedDependencies = root.children.map(function(child) {
return {
name: child.package.name,
currentVersion: child.package.version,
wantedVersion: root.package.dependencies[child.package.name]
};
}).filter(function(dependency) {
return dependency.wantedVersion && dependency.currentVersion !== dependency.wantedVersion;
});
cb(null, wantedDependencies);
});
};
| Return an array of wanted dependencies | Return an array of wanted dependencies
| JavaScript | mit | lukehorvat/get-wanted-dependencies | ---
+++
@@ -7,12 +7,16 @@
return;
}
- var isUpToDate = root.children.every(function(child) {
- var currentVersion = child.package.version;
- var wantedVersion = root.package.dependencies[child.package.name];
- return !wantedVersion || currentVersion === wantedVersion;
+ var wantedDependencies = root.children.map(function(child) {
+ return {
+ name: child.package.name,
+ currentVersion: child.package.version,
+ wantedVersion: root.package.dependencies[child.package.name]
+ };
+ }).filter(function(dependency) {
+ return dependency.wantedVersion && dependency.currentVersion !== dependency.wantedVersion;
});
- cb(null, isUpToDate);
+ cb(null, wantedDependencies);
});
}; |
1d0dae5f963a62adf624cf166cba2478edb1be07 | start.js | start.js | /**
* Listens for the app launching then creates the window
*
*/
chrome.app.runtime.onLaunched.addListener(function() {
var screenWidth = screen.availWidth;
var screenHeight = screen.availHeight;
var width = 800;
var height = 600;
chrome.app.window.create('index.html', {
width: width,
height: height,
left: (screenWidth - width) / 2,
top: (screenHeight - height) / 2
});
});
| /**
* Listens for the app launching then creates the window
*
*/
chrome.app.runtime.onLaunched.addListener(function() {
var screenWidth = screen.availWidth;
var screenHeight = screen.availHeight;
var width = screenWidth;
var height = screenHeight;
chrome.app.window.create('index.html', {
width: width,
height: height,
left: (screenWidth - width) / 2,
top: (screenHeight - height) / 2
});
});
| Change default window size to full screen. | Change default window size to full screen.
| JavaScript | mit | Powpow-Shen/Monocle,powpowshen/Monocle,powpowshen/Monocle | ---
+++
@@ -5,8 +5,8 @@
chrome.app.runtime.onLaunched.addListener(function() {
var screenWidth = screen.availWidth;
var screenHeight = screen.availHeight;
- var width = 800;
- var height = 600;
+ var width = screenWidth;
+ var height = screenHeight;
chrome.app.window.create('index.html', {
width: width, |
c4bc757b094bdc0a313e7d3e59464965e7261ee4 | src/js/containers/main-content/header-filter.js | src/js/containers/main-content/header-filter.js | 'use strict'
import React from 'react'
import SvgIcon from '../../components/svg-icon'
const HeaderFilter = () => (
<nav className='filter'>
<div className='form-select'>
<SvgIcon id='date' label='Data' />
<label className='sr-only'>Escolha um mês</label>
<select>
<option>Escolha um mês</option>
<option>Janeiro</option>
<option>Fevereiro</option>
<option>Março</option>
</select>
</div>
<div className='form-select'>
<SvgIcon id='location' label='Local' />
<label className='sr-only'>Escolha um estado</label>
<select>
<option>Escolha um estado</option>
<option>São Paulo</option>
<option>Acre</option>
<option>Paraná</option>
</select>
</div>
<div className='search'>
<input className='form-control' type='search' placeholder='Busque por palavras chaves' />
<button className='search-btn' type='submit' role='button'>
<SvgIcon id='search' label='Search' />
</button>
</div>
</nav>
)
export default HeaderFilter
| 'use strict'
import React from 'react'
import FormSelect from '../../components/form-select'
import SvgIcon from '../../components/svg-icon'
const HeaderFilter = () => (
<nav className='filter'>
<FormSelect
key='select-date'
icon={{
id: 'date',
label: 'Data'
}}
label='Escolha um mês'
options={[{
text: 'Escolha um mês',
value: ''
}, {
text: 'Janeiro',
value: 'Janeiro'
}, {
text: 'Fevereiro',
value: 'Fevereiro'
}, {
text: 'Março',
value: 'Março'
}]}
/>
<FormSelect
key='select-location'
icon={{
id: 'location',
label: 'Local'
}}
label='Escolha um estado'
options={[{
text: 'São Paulo',
value: 'São Paulo'
}, {
text: 'Acre',
value: 'Acre'
}, {
text: 'Paraná',
value: 'Paraná'
}]}
/>
<div className='search'>
<input className='form-control' type='search' placeholder='Busque por palavras chaves' />
<button className='search-btn' type='submit' role='button'>
<SvgIcon id='search' label='Search' />
</button>
</div>
</nav>
)
export default HeaderFilter
| Add component form select on header filter | Add component form select on header filter
| JavaScript | mit | campinas-front-end-meetup/institucional,campinas-front-end-meetup/institucional,frontendbr/eventos,campinas-front-end/institucional,campinas-front-end/institucional | ---
+++
@@ -1,38 +1,58 @@
'use strict'
import React from 'react'
+import FormSelect from '../../components/form-select'
import SvgIcon from '../../components/svg-icon'
const HeaderFilter = () => (
<nav className='filter'>
- <div className='form-select'>
- <SvgIcon id='date' label='Data' />
- <label className='sr-only'>Escolha um mês</label>
- <select>
- <option>Escolha um mês</option>
- <option>Janeiro</option>
- <option>Fevereiro</option>
- <option>Março</option>
- </select>
- </div>
+ <FormSelect
+ key='select-date'
+ icon={{
+ id: 'date',
+ label: 'Data'
+ }}
+ label='Escolha um mês'
+ options={[{
+ text: 'Escolha um mês',
+ value: ''
+ }, {
+ text: 'Janeiro',
+ value: 'Janeiro'
+ }, {
+ text: 'Fevereiro',
+ value: 'Fevereiro'
+ }, {
+ text: 'Março',
+ value: 'Março'
+ }]}
+ />
- <div className='form-select'>
- <SvgIcon id='location' label='Local' />
- <label className='sr-only'>Escolha um estado</label>
- <select>
- <option>Escolha um estado</option>
- <option>São Paulo</option>
- <option>Acre</option>
- <option>Paraná</option>
- </select>
- </div>
+ <FormSelect
+ key='select-location'
+ icon={{
+ id: 'location',
+ label: 'Local'
+ }}
+ label='Escolha um estado'
+ options={[{
+ text: 'São Paulo',
+ value: 'São Paulo'
+ }, {
+ text: 'Acre',
+ value: 'Acre'
+ }, {
+ text: 'Paraná',
+ value: 'Paraná'
+ }]}
+ />
- <div className='search'>
- <input className='form-control' type='search' placeholder='Busque por palavras chaves' />
- <button className='search-btn' type='submit' role='button'>
- <SvgIcon id='search' label='Search' />
- </button>
- </div>
+ <div className='search'>
+ <input className='form-control' type='search' placeholder='Busque por palavras chaves' />
+ <button className='search-btn' type='submit' role='button'>
+ <SvgIcon id='search' label='Search' />
+ </button>
+ </div>
</nav>
)
|
3eca2dd5f2f4e03d7c2a728b0f9ab2cabfdb0d84 | index.js | index.js | const simplePreferences = require("sdk/simple-prefs");
const ui = require("./lib/ui");
const preferences = simplePreferences.prefs;
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
// Use a panel because there is no multiline string in simple-prefs
// show and fill on button click in preference
simplePreferences.on("editButton", function() {
ui.panel.show();
});
ui.panel.on("show", function() {
ui.panel.port.emit("show", preferences.items);
});
// save content and hide on save button click
ui.panel.port.on("save", function(text) {
ui.panel.hide();
preferences.items = text;
});
simplePreferences.on("items", function() {
ui.populateSubMenu();
});
ui.populateSubMenu();
};
| const simplePreferences = require("sdk/simple-prefs");
const ui = require("./lib/ui");
const preferences = simplePreferences.prefs;
exports.main = function(options) {
console.log("Starting up with reason ", options.loadReason);
// Use a panel because there is no multiline string in simple-prefs
// show and fill on button click in preference
simplePreferences.on("editButton", function() {
ui.panel.show();
});
ui.panel.on("show", function() {
ui.panel.port.emit("show", preferences.items);
});
// save content and hide on save button click
ui.panel.port.on("save", function(text) {
ui.panel.hide();
preferences.items = text;
});
simplePreferences.on("items", function() {
ui.populateSubMenu();
});
ui.populateSubMenu();
};
exports.onUnload = function(reason) {
console.log("Closing down with reason ", reason);
};
| Add empty onUnload to pass test | Add empty onUnload to pass test
| JavaScript | mit | sblask/firefox-simple-form-fill,sblask/firefox-simple-form-fill | ---
+++
@@ -28,3 +28,8 @@
ui.populateSubMenu();
};
+
+exports.onUnload = function(reason) {
+ console.log("Closing down with reason ", reason);
+
+}; |
8008f4591970052967678266935316541d49f6d4 | client/views/channel-info/channel-info.js | client/views/channel-info/channel-info.js | ChannelInfo = BlazeComponent.extendComponent({
onCreated: function () {
},
onRendered: function () {
},
creatorUsername : function() {
return currentChannel().createdBy ? Meteor.users.findOne(currentChannel().createdBy).username : '';
},
dateCreated: function () {
return moment(currentChannel().timestamp).format('MMMM Do YYYY');
}
}).register('channelInfo');
| ChannelInfo = BlazeComponent.extendComponent({
onCreated: function () {
},
onRendered: function () {
},
creatorUsername : function() {
return currentChannel().createdBy ? Meteor.users.findOne(currentChannel().createdBy).username : '';
},
dateCreated: function () {
return moment(currentChannel().timestamp).format('MMMM Do YYYY');
},
events: function () {
return [{
'click .channel-add-purpose': function (event) {
event.preventDefault();
// XXX TODO: Implement cross-component interactions
// in a nicer way
$('.channel-title').trigger('click');
$('.channel-purpose').trigger('click');
}
}];
}
}).register('channelInfo');
| Make channel info purpose link work | Make channel info purpose link work
| JavaScript | mit | mauricionr/SpaceTalk,foysalit/SpaceTalk,lhaig/SpaceTalk,TribeMedia/SpaceTalk,mGhassen/SpaceTalk,MarkBandilla/SpaceTalk,yanisIk/SpaceTalk,thesobek/SpaceTalk,dannypaton/SpaceTalk,bright-sparks/SpaceTalk,redanium/SpaceTalk,thesobek/SpaceTalk,anjneymidha/SpaceTalk,dannypaton/SpaceTalk,lhaig/SpaceTalk,tamzi/SpaceTalk,TribeMedia/SpaceTalk,anjneymidha/SpaceTalk,tamzi/SpaceTalk,yanisIk/SpaceTalk,mauricionr/SpaceTalk,foysalit/SpaceTalk,redanium/SpaceTalk,MarkBandilla/SpaceTalk,syrenio/SpaceTalk,SpaceTalk/SpaceTalk,syrenio/SpaceTalk,bright-sparks/SpaceTalk,SpaceTalk/SpaceTalk,mGhassen/SpaceTalk | ---
+++
@@ -10,5 +10,17 @@
},
dateCreated: function () {
return moment(currentChannel().timestamp).format('MMMM Do YYYY');
+ },
+ events: function () {
+ return [{
+ 'click .channel-add-purpose': function (event) {
+ event.preventDefault();
+
+ // XXX TODO: Implement cross-component interactions
+ // in a nicer way
+ $('.channel-title').trigger('click');
+ $('.channel-purpose').trigger('click');
+ }
+ }];
}
}).register('channelInfo'); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.