commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
9310026c8cbc4af5f4326a27cfc27121e5636323 | index.js | index.js | var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (!opt.splitter && opt.splitter !== "") opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
| var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (typeof opt.splitter === 'undefined') opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
| Adjust opt.splitter to compare against undefined for the default value. | Adjust opt.splitter to compare against undefined for the default value.
| JavaScript | mit | wearefractal/gulp-concat,queckezz/gulp-concat,KenanY/gulp-concat,BinaryMuse/gulp-concat,contra/gulp-concat,colynb/gulp-concat,stevelacy/gulp-concat,callumacrae/gulp-concat,abdurrachman-habibi/gulp-concat |
4021d99786f51646633cf9d15fead8c3a58bef7c | index.js | index.js | var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths) {
// determine webpack root
this.context = path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
| var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths, context) {
// determine webpack root
this.context = context || path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
| Add opportunity pass webpack root (context) | Add opportunity pass webpack root (context)
| JavaScript | mit | chrisblossom/clean-webpack-plugin,mhuggins/clean-webpack-plugin,johnagan/clean-webpack-plugin,chrisblossom/clean-webpack-plugin,johnagan/clean-webpack-plugin |
f4d7e0d0917f7af388c75b4b4816591c4f7410b5 | src/utils/config.js | src/utils/config.js | import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
| import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.merge(globalConfig, _.cloneDeep(cfg))
}
static overwrite(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
| Add loading/merging methods to Config utility | Add loading/merging methods to Config utility
| JavaScript | mit | thinktopography/reframe,thinktopography/reframe |
73707d6455b0f4758c61a5c573aec6ad987259de | index.js | index.js | 'use strict';
module.exports = {
name: 'ember-cli-uglify',
included(app) {
this._super.included.apply(this, arguments);
const defaults = require('lodash.defaultsdeep');
let defaultOptions = {
enabled: app.env === 'production',
uglify: {
compress: {
// this is adversely affects heuristics for IIFE eval
'negate_iife': false,
// limit sequences because of memory issues during parsing
sequences: 30,
},
output: {
// no difference in size and much easier to debug
semicolons: false,
},
}
};
if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) {
defaultOptions.uglify.sourceMap = false;
}
this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions);
},
_sourceMapsEnabled(options) {
if (options.enabled === false) {
return false;
}
let extensions = options.extensions || [];
if (extensions.indexOf('js') === -1) {
return false;
}
return true;
},
postprocessTree(type, tree) {
if (this._options.enabled === true && type === 'all') {
return require('broccoli-uglify-sourcemap')(tree, this._options);
} else {
return tree;
}
}
};
| 'use strict';
module.exports = {
name: 'ember-cli-uglify',
included(app) {
this._super.included.apply(this, arguments);
const defaults = require('lodash.defaultsdeep');
let defaultOptions = {
enabled: app.env === 'production',
uglify: {
compress: {
// this is adversely affects heuristics for IIFE eval
'negate_iife': false,
// limit sequences because of memory issues during parsing
sequences: 30,
},
mangle: {
safari10: true
},
output: {
// no difference in size and much easier to debug
semicolons: false,
},
}
};
if (app.options.sourcemaps && !this._sourceMapsEnabled(app.options.sourcemaps)) {
defaultOptions.uglify.sourceMap = false;
}
this._options = defaults(app.options['ember-cli-uglify'] || {}, defaultOptions);
},
_sourceMapsEnabled(options) {
if (options.enabled === false) {
return false;
}
let extensions = options.extensions || [];
if (extensions.indexOf('js') === -1) {
return false;
}
return true;
},
postprocessTree(type, tree) {
if (this._options.enabled === true && type === 'all') {
return require('broccoli-uglify-sourcemap')(tree, this._options);
} else {
return tree;
}
}
};
| Add a fix for Safari to the default config | Add a fix for Safari to the default config
Uglifying ES6 doesn't work currently with Safari due to a webkit bug.
Adding this mangle option fixes that.
| JavaScript | mit | ember-cli/ember-cli-uglify,ember-cli/ember-cli-uglify |
628a1e56241fd82104d69ac7e8e4b751ff85e34b | index.js | index.js | var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles = new TileSet('./data');
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
}); | var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
ImagicoElevationDownloader = require('node-hgt').ImagicoElevationDownloader,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles,
tileDownloader,
tileDirectory = process.env.TILE_DIRECTORY;
if(!tileDirectory) {
tileDirectory = "./data";
}
if(process.env.TILE_DOWNLOADER) {
if(process.env.TILE_DOWNLOADER == "imagico") {
tileDownloader = new ImagicoElevationDownloader();
}
}
tiles = new TileSet(tileDirectory, {downloader:tileDownloader});
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
}); | Read environment variables for data directory and tile downloader | Read environment variables for data directory and tile downloader
| JavaScript | isc | perliedman/elevation-service,JesseCrocker/elevation-service |
4bf4680c186dd7e21292e7efc2431547f51ac11b | index.js | index.js | function Alternate() {
this.values = arguments;
this.index = 0;
}
Alternate.prototype.next = function() {
var returnValue = this.values[this.index];
if (this.index < this.values.length) {
this.index++;
} else {
this.index = 0;
}
return returnValue;
};
Alternate.prototype.peek = function() {
return this.values[this.index];
};
module.exports = Alternate;
| function Alternate() {
this.values = arguments;
this.index = 0;
}
Alternate.prototype.next = function() {
var returnValue = this.values[this.index];
if (this.index < this.values.length - 1) {
this.index++;
} else {
this.index = 0;
}
return returnValue;
};
Alternate.prototype.peek = function() {
return this.values[this.index];
};
module.exports = Alternate;
| Fix off by one bug | Fix off by one bug
| JavaScript | mit | sgnh/alternate |
43204c269a394d1805d9ddc208ea6a524729c7cf | index.js | index.js | /*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
loop: 1,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var iteration = 1;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ?
1 :
(time - (startTime * iteration)) / options.duration;
options.onProgress(
options.easing(progress) *
(options.to - options.from) +
options.from
);
if (progress === 1) {
if (iteration < options.loop) {
iteration += 1;
} else {
isFinished = true;
}
}
if (isFinished) {
options.onComplete();
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
| /*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var fromToMultiplier = (options.to - options.from) + options.from;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ? 1 : (time - startTime) / options.duration;
options.onProgress(options.easing(progress) * fromToMultiplier);
if (progress === 1) {
isFinished = true;
}
if (isFinished) {
options.onComplete(time);
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
| Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf | Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf
| JavaScript | mit | jacobbuck/tweensy,jacobbuck/tweenie |
7c953aa414ea16fd831a11b3be4d74f5c52b5653 | src/database/utilities/constants.js | src/database/utilities/constants.js | /* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
};
| /* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
PATIENT_CODE: 'patient_code',
};
| Add patient code number sequence | Add patient code number sequence
| JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile |
a4acc1c3dbd3d77104f39c957051f2f38884224c | server/app.js | server/app.js | var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel/:username')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| Edit server route url to match client request | Edit server route url to match client request
| JavaScript | mit | andereld/progark,andereld/progark |
7af80538c9232f5bf0d929d4164076a44cb2b704 | render-mustache.js | render-mustache.js | /**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/template', mustache());
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
| /**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/x-mustache-template', mustache());
*
* A Note on MIME Types:
*
* It has become common convention to include templates within HTML by
* enclosing them within script tags:
*
* <script type=“text/template”>...</script>
*
* Recommended practice for Sail.js applications is to be more specific when
* indicating the MIME type, both as a way to communicate explicitly with
* other developers and as a means to use multiple template engines within an
* application.
*
* While no standard exists, the following list of MIME types are used to
* indicate Mustache templates in practice:
*
* * text/x-mustache-template
* [Announcing Handlebars.js](http://yehudakatz.com/2010/09/09/announcing-handlebars-js/)
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
| Add documentation regarding MIME types. | Add documentation regarding MIME types.
| JavaScript | mit | sailjs/render-mustache |
91e5e219929c894cb48391261cc38780c728b0d9 | src/cmd/main/music/handlers/YouTubeHandler.js | src/cmd/main/music/handlers/YouTubeHandler.js | /**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
const ITAG = '251'; // Preferred iTag quality to get. Default: 251.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
return got.stream(info.formats.find(f => f.itag === ITAG).url);
}
}
module.exports = YouTubeHandler; | /**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
// List of all itag qualities can be found here: https://en.wikipedia.org/w/index.php?title=YouTube&oldid=800910021#Quality_and_formats.
const ITAG = '140'; // Preferred itag quality to get. Default: 140.
const ITAG_FALLBACK = '22'; // In the event that the previous itag could not be found, try finding this one. Should probably be a lower value.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let format = info.formats.find(f => f.itag === ITAG) || info.formats.find(f => f.itag === ITAG_FALLBACK);
format = format ? format.url : info.url; // Fallback to default URL if the wanted itags could not be found;
return got.stream(format);
}
}
module.exports = YouTubeHandler; | Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues | Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues
| JavaScript | unknown | awau/owo-whats-this,sr229/owo-whats-this,ClarityMoe/Clara,awau/Clara,owo-dev-team/owo-whats-this |
3f96581aa2df3892d673a3ef175bf8e76f321075 | renderer/middleware/index.js | renderer/middleware/index.js | // @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
next(action);
};
| // @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
if (action.id) {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
}
next(action);
};
| Update store at Only import change | Update store at Only import change
| JavaScript | mit | akameco/PixivDeck,akameco/PixivDeck |
546e2733e51106975f7b167f3b690771ebd6dcfb | lib/gcli/test/testFail.js | lib/gcli/test/testFail.js | /*
* Copyright 2012, Mozilla Foundation and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var helpers = require('./helpers');
exports.testBasic = function(options) {
return helpers.audit(options, [
{
setup: 'tsfail reject',
exec: {
output: 'rejected promise',
type: 'error',
error: true
}
},
{
setup: 'tsfail rejecttyped',
exec: {
output: '54',
type: 'number',
error: true
}
},
{
setup: 'tsfail throwerror',
exec: {
output: 'thrown error',
type: 'error',
error: true
}
},
{
setup: 'tsfail throwstring',
exec: {
output: 'thrown string',
type: 'error',
error: true
}
},
{
setup: 'tsfail noerror',
exec: {
output: 'no error',
type: 'string',
error: false
}
}
]);
};
| /*
* Copyright 2012, Mozilla Foundation and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var helpers = require('./helpers');
exports.testBasic = function(options) {
return helpers.audit(options, [
{
setup: 'tsfail reject',
exec: {
output: 'rejected promise',
type: 'error',
error: true
}
},
{
setup: 'tsfail rejecttyped',
exec: {
output: '54',
type: 'number',
error: true
}
},
{
setup: 'tsfail throwerror',
exec: {
output: /thrown error$/,
type: 'error',
error: true
}
},
{
setup: 'tsfail throwstring',
exec: {
output: 'thrown string',
type: 'error',
error: true
}
},
{
setup: 'tsfail noerror',
exec: {
output: 'no error',
type: 'string',
error: false
}
}
]);
};
| Allow wider set of messages in exception tests | spawn-1007006: Allow wider set of messages in exception tests
If Task.spawn catches an exception message then it adds "Error: " onto
the front, so allow a slightly wider set of error messages when testing.
Signed-off-by: Joe Walker <7a17872fbb32c7d760c9a16ee3076daead11efcf@mozilla.com>
| JavaScript | apache-2.0 | mozilla/gcli,mozilla/gcli,joewalker/gcli,joewalker/gcli,mozilla/gcli |
6288e418a248e997f1e6830d8bfa4e09d33a3717 | src/modules/getPrice/index.js | src/modules/getPrice/index.js | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const [{data: [priceData]}, {data: {name: itemName}}] = await Promise.all([
axios.get(`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`),
axios.get(`${esiURL}universe/types/${itemid}/?datasource=tranquility&language=en-us`)
]);
const sellFivePercent = humanize(priceData.sell.fivePercent);
const buyFivePercent = humanize(priceData.buy.fivePercent);
message.channel.sendMessage(
`__Price of **${itemName}** in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | Modify getPrice to report name of item actually queried | Modify getPrice to report name of item actually queried
| JavaScript | mit | emensch/thonk9k |
56e76553bb5a4f6e44a4739fb4f9eb46dfbfa463 | src/plugins/FileVersioningPlugin.js | src/plugins/FileVersioningPlugin.js | let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', file => {
file = new File(file);
// Find and delete all matching versioned files in the directory.
glob(path.join(file.base(), '**'), (err, files) => {
files.filter(file => {
return /\.(\w{20}|\w{32})(\..+)/.test(file);
}).forEach(file => new File(file).delete());
});
// Then create a fresh versioned file.
this.reversion(file.path());
});
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
let name = new File(updatedFile).version(false).pathFromPublic();
try { File.find(Mix.manifest.get(updatedFile)).delete(); }
catch (e) {}
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
| let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', this.reversion);
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
updatedFile = new File(updatedFile);
try { File.find(Mix.manifest.get(updatedFile.pathFromPublic())).delete(); }
catch (e) {}
let name = updatedFile.version(false).pathFromPublic();
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
| Clean up file versioning handler | Clean up file versioning handler
| JavaScript | mit | JeffreyWay/laravel-mix |
ad1554d353a332c2eed047b86c3ddbe5f4e3a6c4 | src/components/CenteredMap.js | src/components/CenteredMap.js | import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={false}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
| import React from 'react'
import PropTypes from 'prop-types'
import { Map, TileLayer, GeoJSON } from 'react-leaflet'
class CenteredMap extends React.PureComponent {
static propTypes = {
vectors: PropTypes.object.isRequired,
className: PropTypes.string,
frozen: PropTypes.bool,
lat: PropTypes.number,
lon: PropTypes.number,
zoom: PropTypes.number
}
static defaultProps = {
frozen: false,
lat: 47,
lon: 1,
zoom: 5
}
componentDidMount() {
if (this.vectors) {
this.setState({
bounds: this.vectors.leafletElement.getBounds()
})
}
}
render() {
const { vectors, className, frozen, lat, lon, zoom } = this.props
const { bounds } = this.state
return (
<Map
className={className}
center={[lat, lon]}
bounds={bounds}
minZoom={zoom}
dragging={!frozen}
scrollWheelZoom={false}
doubleClickZoom={!frozen}
zoomControl={!frozen}
>
<TileLayer
attribution='© Contributeurs <a href="http://osm.org/copyright">OpenStreetMap</a>'
url='https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png'
/>
<GeoJSON
color='blue'
fillOpacity={0.1}
weight={2}
ref={vectors => { this.vectors = vectors }}
data={vectors}
/>
</Map>
)
}
}
export default CenteredMap
| Allow double click zoom when map is not frozen | Allow double click zoom when map is not frozen
| JavaScript | mit | sgmap/inspire,sgmap/inspire |
6e95c2af465fc296984e86b73192eca1c32c8f9d | lib/rules/load-average.js | lib/rules/load-average.js | var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
| var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
| Use event name for incident name | Use event name for incident name
| JavaScript | isc | numbat-metrics/numbat-analyzer,ceejbot/numbat-analyzer |
fff63aaf393903aa0830f1cf521b3edc775a152e | sdk/src/Constants.js | sdk/src/Constants.js | export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestPostMessage'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
} | export default class Constants {
static get USER_ACCOUNT_KEY() { return btoa('blipSdkUAccount'); }
static get IFRAMEURL_LOCAL() { return 'http://localhost:3000/'; }
static get IFRAMEURL_HMG() { return 'https://hmg-sdkcommon.blip.ai/'; }
static get IFRAMEURL_PRD() { return 'https://sdkcommon.blip.ai/'; }
static get COOKIE_DATA_CODE() { return 'BlipSdkCookieData'; }
static get SEND_MESSAGE_CODE() { return 'SendMessage'; }
static get SDK_DEFAULT_TITLE() { return 'Estamos online'; }
static get SDK_DEFAULT_ICON_PATH() { return 'https://takenetomni.blob.core.windows.net/media-db/blip-app-white.png'; }
static get SDK_DEFAULT_WIDGET_COLOR() { return '#546E7A'; }
static get SDK_DEFAULT_Z_INDEX() { return 16000001; }
static get SDK_DEFAULT_HIDE_MENU() { return false; }
static get REQUEST_POST_MESSAGE_CODE() { return 'RequestCookie'; }
static get COOKIES_EXPIRATION() { return 365; }
static get MENU_VISIBILITY_CODE() { return 'BlipSdkMenuVisibility' }
} | Change constant value for backward compatibility | Change constant value for backward compatibility
| JavaScript | apache-2.0 | takenet/blip-chat-web,takenet/blip-chat-web,takenet/blip-sdk-web,takenet/blip-sdk-web |
8a970c6b9bf037c10cdc55dc7fa27bcf20d393dc | test/config.spec.js | test/config.spec.js | 'use strict';
/*
config
->read from file, holds values and supplies as needed
*/
require('chai').should()
var config = require('../lib/config')()
describe('Config', () => {
describe('#getLayers', () => {
it('should return layers config array', () => {
//Given
//When
var layers = config.getLayers()
//Then
layers.should.be.an('array')
layers[0].name.should.be.a('string')
})
})
describe('#getMap', () => {
it('should return map config object', () => {
//Given
//When
var map = config.getMap()
//Then
map.should.be.an('object')
map.tileLayers.should.be.an('array')
})
})
})
| 'use strict';
/*
config
->read from file, holds values and supplies as needed
*/
require('chai').should()
var config = require('../lib/config')()
describe('Config', () => {
describe('#getLayers', () => {
it('should return layers config array', () => {
//Given
//When
var layers = config.getLayers()
//Then
layers.should.be.an('array')
layers[0].name.should.be.a('string')
})
})
describe('#getMap', () => {
it('should return map config object', () => {
//Given
//When
var map = config.getMap()
//Then
map.should.be.an('object')
map.tileLayers.should.be.an('object')
})
})
})
| Update test to reflect config file change | Update test to reflect config file change
| JavaScript | mit | mediasuitenz/mappy,mediasuitenz/mappy |
60fbc2e4405a2168223266f950488dfacb8b2f0a | Player.js | Player.js | /* global Entity */
(function() {
'use strict';
function Player(x, y, speed) {
this.base = Entity;
this.base(
x,
y,
Player.width,
Player.height,
'public/images/sprites/heroes.png',
56,
12,
speed || 150
);
}
Player.width = 32;
Player.height = 52;
Player.prototype = new Entity();
// Make Player available globally
window.Player = Player;
}());
| /* global Entity */
(function() {
'use strict';
function Player(x, y, speed) {
this.base = Entity;
this.base(
x,
y,
Player.width,
Player.height,
'public/images/sprites/heroes.png',
105,
142,
speed || 150
);
}
Player.width = 32;
Player.height = 48;
Player.prototype = new Entity();
// Make Player available globally
window.Player = Player;
}());
| Change player sprite to show hero facing the zombies | Change player sprite to show hero facing the zombies
| JavaScript | mit | handrus/zombies-game,brunops/zombies-game,brunops/zombies-game |
dc9a45d38a5857472b7d9a72f7c2363276cc4efc | tdd/server/palindrome/test/palindrome-test.js | tdd/server/palindrome/test/palindrome-test.js | var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
});
| /*
* Test ideas
*
* 'dad' is a palindrome
* 'dude' is not a palindrome
* 'mom mom' is a palindrome
* 'dad dae' is a palindrome'
*/
var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
it('should return true when passed "dad"', function() {
expect(isPalindrome('dad')).to.be.true;
});
});
| Add test: 'dad' is a palindrome | Add test: 'dad' is a palindrome
| JavaScript | apache-2.0 | mrwizard82d1/tdjsa |
aa9717b62f1a0c0e41f06e9f54393d8cd55769f9 | templates/demo/config/namesystem.js | templates/demo/config/namesystem.js | module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens",
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
| module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens"
},
development: {
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
| Move name config to development | [CHORES] Move name config to development
| JavaScript | mit | iurimatias/embark-framework,iurimatias/embark-framework |
2d14e852c9c833eeec7b63a76102ce4dc29bd2cb | angular/app-foundation.module.js | angular/app-foundation.module.js | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
'md.data.table',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})(); | /**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})(); | Update bower @ Uninstall angular-material-data-table | Update bower @ Uninstall angular-material-data-table
| JavaScript | mit | onderdelen/app-foundation,componeint/app-foundation,onderdelen/app-foundation,onderdelen/app-foundation,componeint/app-foundation,componeint/app-foundation,consigliere/app-foundation,consigliere/app-foundation,consigliere/app-foundation |
fa449ed86a6bfde93654bba283a8c7cc4788bc61 | test/journals-getDokumenter-test.js | test/journals-getDokumenter-test.js | 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
tap.test('Requires options.host to be specified', function (test) {
const options = {
host: false
}
const expectedErrorMessage = 'Missing required input: options.host'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
tap.test('Requires options.journalpostid to be specified', function (test) {
const options = {
host: true,
journalpostid: false
}
const expectedErrorMessage = 'Missing required input: options.journalpostid'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.done()
})
})
| 'use strict'
const tap = require('tap')
const getDokumenter = require('../lib/journals/getDokumenter')
tap.test('Requires options to be specified', function (test) {
const options = false
const expectedErrorMessage = 'Missing required input: options object'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
tap.test('Requires options.host to be specified', function (test) {
const options = {
host: false
}
const expectedErrorMessage = 'Missing required input: options.host'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
tap.test('Requires options.journalpostid to be specified', function (test) {
const options = {
host: true,
journalpostid: false
}
const expectedErrorMessage = 'Missing required input: options.journalpostid'
getDokumenter(options, function (error, data) {
tap.equal(error.message, expectedErrorMessage, expectedErrorMessage)
test.end()
})
})
| Replace test.done with test.end (patch) | Replace test.done with test.end (patch)
| JavaScript | mit | zrrrzzt/edemokrati |
0492af81a8140b89347ea721f46fcc71088466d8 | test/lib/api-util/api-util-test.js | test/lib/api-util/api-util-test.js | 'use strict';
const preq = require('preq');
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', function() {
this.timeout(20000); // eslint-disable-line no-invalid-this
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return preq.post({
uri: 'https://commons.wikimedia.org/w/api.php',
body: {
action: 'query',
format: 'json',
formatversion: 2,
generator: 'images',
prop: 'imageinfo|revisions',
iiextmetadatafilter: 'ImageDescription',
iiextmetadatamultilang: true,
iiprop: 'url|extmetadata|dimensions',
iiurlwidth: 1024,
rawcontinue: '',
titles: `Template:Potd/1980-07-06`
}
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
| 'use strict';
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', () => {
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return new Promise((resolve) => {
return resolve({});
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
| Remove unnecessary API call in unit test | Remove unnecessary API call in unit test
We do not need to hit the API in this test. It's unnecessary and makes
the test harder to comprehend.
Instead of testing this way, simulate a promise that resolves without
pages.
(npm run test:unit should work without an internet connection)
Change-Id: Iee834114890a64c96ccf255601503a25efd884bc
| JavaScript | apache-2.0 | wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps |
9eaa53c31ddb5170a9cd3d81e4fc4846a370b6ba | addon/change-gate.js | addon/change-gate.js | import Em from 'ember';
var get = Em.get;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
var computed = Em.computed(function handler(key) {
var meta = computed.meta();
meta.hasObserver = false;
meta.lastValue = null;
var isFirstRun = !meta.hasObserver;
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
meta.hasObserver = true;
meta.lastValue = value;
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = meta.lastValue;
if(newValue !== lastValue) {
meta.lastValue = value;
this.notifyPropertyChange(key);
}
});
return value;
} else {
return meta.lastValue;
}
});
return computed;
}
| import Em from 'ember';
var get = Em.get,
getMeta = Em.getMeta,
setMeta = Em.setMeta;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
return Em.computed(function(key) {
var hasObserverKey = '_changeGate:%@:hasObserver'.fmt(key);
var lastValueKey = '_changeGate:%@:lastValue'.fmt(key);
var isFirstRun = !getMeta(this, hasObserverKey);
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
setMeta(this, hasObserverKey, true);
setMeta(this, lastValueKey, value);
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = getMeta(this, lastValueKey);
if(newValue !== lastValue) {
setMeta(this, lastValueKey, newValue);
this.notifyPropertyChange(key);
}
});
return value;
} else {
return getMeta(this, lastValueKey);
}
});
}
| Revert "Refactored macro to use ComputedProperty meta instead of object's meta" | Revert "Refactored macro to use ComputedProperty meta instead of object's meta"
| JavaScript | mit | givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate,givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate |
daf08f7840abf24d076c604fb58ca0771c79a25c | snippets/device.js | snippets/device.js | const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
| const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'vendor', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
| Add "vendor" to list of printed properties | Add "vendor" to list of printed properties
| JavaScript | bsd-3-clause | eclipsesource/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js |
ced91cef769326b288b6741f3e1474ee9cb89a29 | core/providers/totalwind/extractor.js | core/providers/totalwind/extractor.js | 'use strict'
var extract = require('../../extract')
var lodash = require('lodash')
var CONST = {
SOURCE_NAME: 'totalwind',
IGNORE_LOG_PROPS: ['updatedAt', 'createdAt', 'link', 'title', 'provider']
}
function createExtractor (type, category) {
function extractor (data) {
data.type = type
data.provider = CONST.SOURCE_NAME
data.category = category
var raw = lodash.lowerCase(data.title)
var dataExtract = {
price: extract.price(raw),
year: extract.year(raw)
}
if (lodash.isEqual(category, 'sails'))
lodash.assign(dataExtract, extract.sail(raw))
lodash.merge(data, dataExtract)
var self = this
this.validate(data, function (validationError, instance) {
++self.stats.total
if (!validationError) {
self.log.info(lodash.omit(instance, CONST.IGNORE_LOG_PROPS))
++self.stats.valid
var category = instance.category
if (self.db[category]) {
++self.stats.add
self.db[category].addObject(instance)
}
} else {
self.log.debug(validationError)
}
})
}
return extractor
}
module.exports = createExtractor
| 'use strict'
var isBlacklisted = require('../../schema/is-blacklisted')
var extract = require('../../extract')
var lodash = require('lodash')
var CONST = {
SOURCE_NAME: 'totalwind',
IGNORE_LOG_PROPS: ['updatedAt', 'createdAt', 'link', 'title', 'provider']
}
function createExtractor (type, category) {
function extractor (data) {
if (isBlacklisted(data.title)) return
data.type = type
data.provider = CONST.SOURCE_NAME
data.category = category
var raw = lodash.lowerCase(data.title)
var dataExtract = {
price: extract.price(raw),
year: extract.year(raw)
}
if (lodash.isEqual(category, 'sails'))
lodash.assign(dataExtract, extract.sail(raw))
lodash.merge(data, dataExtract)
var self = this
this.validate(data, function (validationError, instance) {
++self.stats.total
if (!validationError) {
self.log.info(lodash.omit(instance, CONST.IGNORE_LOG_PROPS))
++self.stats.valid
var category = instance.category
if (self.db[category]) {
++self.stats.add
self.db[category].addObject(instance)
}
} else {
self.log.debug(validationError)
}
})
}
return extractor
}
module.exports = createExtractor
| Check first censure words before analyze | Check first censure words before analyze
| JavaScript | mit | windtoday/windtoday-core,windtoday/windtoday-core |
ea7bb1e48593306441da54337b82ba9b10452703 | bin/siteshooter.js | bin/siteshooter.js | #! /usr/bin/env node
'use strict';
var chalk = require('chalk'),
pkg = require('../package.json');
var nodeVersion = process.version.replace('v',''),
nodeVersionRequired = pkg.engines.node.replace('>=','');
// check node version compatibility
if(nodeVersion <= nodeVersionRequired){
console.log();
console.error(chalk.red.bold('✗ '), chalk.red.bold('Siteshooter requires node version ' + pkg.engines.node));
console.log();
process.exit(1);
}
var siteshooter = require('../index'),
args = [].slice.call(process.argv, 2);
var exitCode = 0,
isDebug = args.indexOf('--debug') !== -1;
siteshooter.cli(args).then(function() {
if (isDebug) {
console.log('CLI promise complete');
}
process.exit(exitCode);
}).catch(function(err) {
exitCode = 1;
if (!isDebug) {
console.error(err.stack);
}
process.exit(exitCode);
});
process.on('exit', function() {
if (isDebug) {
console.log('EXIT', arguments);
}
process.exit(exitCode);
});
| #! /usr/bin/env node
'use strict';
var chalk = require('chalk'),
pkg = require('../package.json');
var nodeVersion = process.version.replace('v',''),
nodeVersionRequired = pkg.engines.node.replace('>=','');
// check node version compatibility
if(nodeVersion <= nodeVersionRequired){
console.log();
console.error(chalk.red.bold('✗ '), chalk.red.bold('NODE ' + process.version + ' was detected. Siteshooter requires node version ' + pkg.engines.node));
console.log();
process.exit(1);
}
else{
// check for new version of Siteshooter
var updater = require('update-notifier');
updater({pkg: pkg}).notify({defer: true});
}
var siteshooter = require('../index'),
args = [].slice.call(process.argv, 2);
var exitCode = 0,
isDebug = args.indexOf('--debug') !== -1;
siteshooter.cli(args).then(function() {
if (isDebug) {
console.log('CLI promise complete');
}
process.exit(exitCode);
}).catch(function(err) {
exitCode = 1;
if (!isDebug) {
console.error(err.stack);
}
process.exit(exitCode);
});
process.on('exit', function() {
if (isDebug) {
console.log('EXIT', arguments);
}
process.exit(exitCode);
});
| Move update notifier to bin | Move update notifier to bin
| JavaScript | mpl-2.0 | devopsgroup-io/siteshooter |
8506adb0cd6e8dc13a2deefcd349a1826be6f567 | src/aspects/equality.js | src/aspects/equality.js | // @flow
import { Record } from 'immutable';
import { Type } from './tm';
import EvaluationResult from './evaluation';
const EqualityShape = Record({
of: null, // Tm
type: Type.singleton,
}, 'equality');
// Propositional Equality type
export class Equality extends EqualityShape {
static arity = [0];
map(): Equality {
throw new Error('unimplemented - Equality.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Equality.step');
}
}
const ReflShape = Record({
left: null, // Tm
right: null, // Tm
type: Type.singleton,
}, 'refl');
// TODO come up with appropriate name for this
export class Refl extends ReflShape {
static arity = [0, 0];
map(): Equality {
throw new Error('unimplemented - Refl.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Refl.step');
}
}
| // @flow
import { Record } from 'immutable';
import { Type } from '../theory/tm';
import { EvaluationResult } from '../theory/evaluation';
const EqualityShape = Record({
of: null, // Tm
type: Type.singleton,
}, 'equality');
// Propositional Equality type
export class Equality extends EqualityShape {
static arity = [0];
map(): Equality {
throw new Error('unimplemented - Equality.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Equality.step');
}
}
const ReflShape = Record({
left: null, // Tm
right: null, // Tm
type: Type.singleton,
}, 'refl');
// TODO come up with appropriate name for this
export class Refl extends ReflShape {
static arity = [0, 0];
map(): Equality {
throw new Error('unimplemented - Refl.map');
}
step(): EvaluationResult {
throw new Error('unimplemented - Refl.step');
}
}
| Fix import errors flow found. | Fix import errors flow found.
| JavaScript | mit | joelburget/pigment |
9ad30d7fb666403f0a74e5905ef928be13547a7b | gulpfile.js | gulpfile.js | 'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
| 'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**', '!test/assets/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
| Disable lint for test assets | Disable lint for test assets
| JavaScript | mit | FountainJS/generator-fountain-systemjs,FountainJS/generator-fountain-systemjs |
c62191bfcb066f9f544f3df019db32da48dbbeee | test/examples/Counter-test.js | test/examples/Counter-test.js | /** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1, 0)
const handleMinus = createEventHandler(-1, 0)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
| /** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1)
const handleMinus = createEventHandler(-1)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0).startWith(0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
| Update Counter test to no relying on initial values for event handlers | Update Counter test to no relying on initial values for event handlers
| JavaScript | mit | StateFarmIns/yolk,garbles/yolk,KenPowers/yolk,yolkjs/yolk,jadbox/yolk,brandonpayton/yolk,kamilogorek/yolk,BrewhouseTeam/yolk,knpwrs/yolk |
1ed8856f1a4861213c73b857582a18e6c836a7ef | gulpfile.js | gulpfile.js | var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('default', ['jsdoc']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
| var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('deploy', function() {
return gulp.src(docsDestDir + '/**/*')
.pipe(ghPages());
});
gulp.task('default', ['jsdoc']);
gulp.task('build', ['jsdoc', 'deploy']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
| Add gulp task to deploy jsDocs | Add gulp task to deploy jsDocs
| JavaScript | mit | moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough |
af37455fed835172c2e533a60f2e65f3833058a9 | gulpfile.js | gulpfile.js | var gulp = require("gulp");
var sass = require("gulp-sass");
var postcss = require("gulp-postcss");
var autoprefixer = require("autoprefixer");
var cssnano = require("cssnano");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var browserSync = require("browser-sync");
gulp.task("serve", ["css", "js"], function () {
browserSync.init({
server: "./"
});
gulp.watch("css/main.scss", ["css"]);
gulp.watch("index.html").on("change", browserSync.reload);
gulp.watch("js/main.js", ["js"]);
gulp.watch("js/main.min.js").on("change", browserSync.reload);
});
gulp.task("css", function () {
gulp.src("css/main.scss")
.pipe(sass().on("error", sass.logError))
.pipe(postcss([
autoprefixer(),
cssnano()
]))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("css"))
.pipe(browserSync.stream());
});
gulp.task("js", function () {
gulp.src("js/main.js")
.pipe(uglify())
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("js"));
});
gulp.task("default", ["serve"]); | const gulp = require('gulp');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const browserSync = require('browser-sync');
gulp.task('serve', ['css', 'js'], () => {
browserSync.init({
server: './'
});
gulp.watch('css/main.scss', ['css']);
gulp.watch('index.html').on('change', browserSync.reload);
gulp.watch('js/main.js', ['js']);
gulp.watch('js/main.min.js').on('change', browserSync.reload);
});
gulp.task('css', () => {
gulp
.src('css/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
});
gulp.task('js', () => {
gulp
.src('js/main.js')
.pipe(uglify())
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('js'));
});
gulp.task('default', ['serve']);
| Update Gulp file to use es6 syntax. | Update Gulp file to use es6 syntax. | JavaScript | mit | mohouyizme/minimado,mohouyizme/minimado |
ac04ecd69e559d018f7d9e24d7f6de617aac3a26 | src/apis/Dimensions/index.js | src/apis/Dimensions/index.js | /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {
screen: {
fontScale: 1,
get height() { return win.screen.height },
scale: win.devicePixelRatio || 1,
get width() { return win.screen.width }
},
window: {
fontScale: 1,
get height() { return win.innerHeight },
scale: win.devicePixelRatio || 1,
get width() { return win.innerWidth }
}
}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
}
module.exports = Dimensions
| /**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import debounce from 'lodash.debounce'
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
static set(): void {
dimensions.window = {
fontScale: 1,
height: win.innerHeight,
scale: win.devicePixelRatio || 1,
width: win.innerWidth
}
dimensions.screen = {
fontScale: 1,
height: win.screen.height,
scale: win.devicePixelRatio || 1,
width: win.screen.width
}
}
}
Dimensions.set();
ExecutionEnvironment.canUseDOM && window.addEventListener('resize', debounce(Dimensions.set, 50))
module.exports = Dimensions
| Update Dimensions when window resizes | Update Dimensions when window resizes
| JavaScript | mit | necolas/react-native-web,necolas/react-native-web,necolas/react-native-web |
e5fb18d4a59e707f075d76310af2ec919ca5716c | src/modules/getPrice/index.js | src/modules/getPrice/index.js | import module from '../../module'
import command from '../../components/command'
import loader from '../../components/loader'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
loader(() => {
console.log('test')
}),
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const {data: itemData} = await axios.get(
`https://esi.tech.ccp.is/latest/search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | import module from '../../module'
import command from '../../components/command'
import loader from '../../components/loader'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
loader(() => {
console.log('test')
}),
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
) | Move ESI url prefix to variable | Move ESI url prefix to variable
| JavaScript | mit | emensch/thonk9k |
6801d288ec728671330a6881306753abd30e0a8f | app/student.front.js | app/student.front.js | const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data),
limit: 10
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
| const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data),
limit: 10
}
})
$answer.each((i, answer) => {
$.get(`/load?answerId=${answer.id}`, data => {
data && $(answer).html(data.html)
makeRichText(answer, richTextOptions(answer.id), onValueChange)
})
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
function onValueChange() {
}
| Update answer content before initializing rich text | Update answer content before initializing rich text
| JavaScript | mit | digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor |
d02ef235fb382ff749a41561518c18c7ebd81f2f | src/JokeMeUpBoy.js | src/JokeMeUpBoy.js | /**
* Prints a random programmer joke.
* @author Vitor Cortez <vitoracortez+github@gmail.com>
*/
var jokeMeUpBoy = function() {
const jokes = getListOfJokes();
let rand = Math.floor(Math.random() * jokes.length);
console.log(jokes[rand]);
};
/**
* Holds a list of classic programmer jokes.
* Feel free to add a new joke each day.
* @private
*/
function getListOfJokes() {
var arr = [];
arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.');
return arr;
}
anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
| /**
* Prints a random programmer joke.
* @author Vitor Cortez <vitoracortez+github@gmail.com>
*/
var jokeMeUpBoy = function() {
const jokes = getListOfJokes();
let rand = Math.floor(Math.random() * jokes.length);
console.log(jokes[rand]);
};
/**
* Holds a list of classic programmer jokes.
* Feel free to add a new joke each day.
* @private
*/
function getListOfJokes() {
var arr = [];
arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.');
arr.push('Q: Why do programmers always mix up Halloween and Christmas?\nA: Because Oct 31 == Dec 25!');
return arr;
}
anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
| Add a new dank joke | Add a new dank joke
Dem jokes | JavaScript | mit | Rabrennie/anything.js,Sha-Grisha/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js |
86cef9310543200502e822cbfbc39066e3f91967 | public/app/user-account/user-login/user-login-controller.js | public/app/user-account/user-login/user-login-controller.js | define(function() {
var LoginController = function($location, AuthenticationService) {
// reset login status
AuthenticationService.clearCredentials();
this.login = function() {
this.dataLoading = true;
var self = this
AuthenticationService.login(this.username, this.password)
.success(function(userProfile, status) {
AuthenticationService.setCredentials(self.username, self.password);
$location.path('/');
})
.error(function(error, status) {
self.error = error.message;
self.dataLoading = false;
});
};
}
LoginController.$inject = ['$location', 'UserAuthenticationService']
return LoginController
})
| define(function() {
var LoginController = function($location, $mdDialog, AuthenticationService) {
// reset login status
AuthenticationService.clearCredentials()
this.login = function() {
this.dataLoading = true
var self = this
AuthenticationService.login(this.username, this.password)
.success(function(userProfile, status) {
AuthenticationService.setCredentials(self.username, self.password)
$location.path('/')
})
.error(function(error, status) {
self.dataLoading = false
var alert = $mdDialog.alert({
title: 'We couldn\'t sign you in!',
content: error.message,
ok: 'Try again'
})
$mdDialog.show(alert)
})
}
}
LoginController.$inject = ['$location', '$mdDialog', 'UserAuthenticationService']
return LoginController
})
| Update login controller to display dialog on error | Update login controller to display dialog on error
| JavaScript | mit | tenevdev/idiot,tenevdev/idiot |
297c942ffefae923501d5988c36ef6930b5888b7 | examples/http-random-user/src/main.js | examples/http-random-user/src/main.js | import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
key: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.key === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
| import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
category: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.category === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
| Rename http-random-user key to category | Rename http-random-user key to category
| JavaScript | mit | cyclejs/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,cyclejs/cycle-core,staltz/cycle,ntilwalli/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,usm4n/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cycle-core,ntilwalli/cyclejs,staltz/cycle,usm4n/cyclejs,cyclejs/cyclejs,maskinoshita/cyclejs |
73e99f993882ddd754fefd112f2c95ce62e5dad2 | app/components/OverFlowMenu.js | app/components/OverFlowMenu.js | import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setState({open: !this.state.open});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.toggle();
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
| import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setOpen(!this.isOpen());
}
isOpen() {
return this.state.open;
}
setOpen(openOrClosed) {
this.setState({open: openOrClosed});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.setOpen(false);
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
| Fix overflow menu reopening immediately after selecting an item | Fix overflow menu reopening immediately after selecting an item
Was caused by mouseout toggling, instead of closing
| JavaScript | mpl-2.0 | pascalw/gettable,pascalw/gettable |
5e850fc85216fed6848878eaf66841c8dc25fc1b | src/selectors/cashRegister.js | src/selectors/cashRegister.js | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc + total, 0)
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc + total, 0)
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => currency(receiptsTotal - paymentsTotal).format(false)
);
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => receiptsTotal.subtract(paymentsTotal).format()
);
| Add currency to cash register selectors | Add currency to cash register selectors | JavaScript | mit | sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile |
39c4271933e1392d20483aa3e1c6e7287fb3d820 | src/api/githubAPI.js | src/api/githubAPI.js | let Octokat = require('octokat');
let octo = new Octokat({});
class GithubApi {
constructor(){
this.octo = new Octokat({});
}
static newOctokatNoToken(){
this.octo = new Octokat({});
}
static newOctokatWithToken(token){
this.octo = new Octokat({
token: token
});
}
static testOctokat(){
return new Promise((resolve) => {
resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch());
});
}
}
export default GithubApi;
| let Octokat = require('octokat');
let octo = new Octokat({});
class GithubApi {
static testOctokat(){
return new Promise((resolve) => {
resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch());
});
}
}
export default GithubApi;
| Revert "Modify GithubApi to be able to set an OAuth token when instantiating" | Revert "Modify GithubApi to be able to set an OAuth token when instantiating"
This reverts commit 2197aa8a6246348070b9c26693ec08fc44f02031.
| JavaScript | mit | compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI |
60f02a26c5857e28e268cbfdd242644089c6626c | react.js | react.js | module.exports = {
extends: ["./index.js", "plugin:react/recommended"],
env: {
browser: true
},
plugins: [
"react"
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {
"jsx": true
}
}
};
| module.exports = {
extends: ["./index.js", "plugin:react/recommended"],
env: {
browser: true
},
plugins: [
"react"
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {
"jsx": true
}
},
rules: {
"react/display-name": 0,
"react/no-danger": 0
}
};
| Add common React rules to preset | Add common React rules to preset
| JavaScript | mit | netconomy/eslint-config-netconomy |
30d5c4942db0ccdb2f5ee4de0d4405d456ff3ed9 | webpack.conf.js | webpack.conf.js | import webpack from "webpack";
import path from "path";
export default {
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
}
]
},
plugins: [
new webpack.ProvidePlugin({
"fetch": "imports-loader?this=>global!exports?global.fetch!whatwg-fetch"
})
],
context: path.join(__dirname, "src"),
entry: {
app: ["./js/app"]
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js"
},
externals: [/^vendor\/.+\.js$/]
};
| import webpack from "webpack";
import path from "path";
export default {
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
}
]
},
plugins: [
new webpack.ProvidePlugin({
"fetch": "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch"
})
],
context: path.join(__dirname, "src"),
entry: {
app: ["./js/app"]
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "[name].js"
},
externals: [/^vendor\/.+\.js$/]
};
| Update exports loader to Webpack 3 syntax | Update exports loader to Webpack 3 syntax
Closes #67. | JavaScript | mit | doudigit/doudigit.github.io,BeitouSafeHome/btsh,netlify-templates/one-click-hugo-cms,netlify-templates/one-click-hugo-cms,emiaj/blog,chromicant/blog,doudigit/doudigit.github.io,jcrincon/jcrincon.github.io,chromicant/blog,BeitouSafeHome/btsh,emiaj/blog,jcrincon/jcrincon.github.io,emiaj/blog |
55e44ff76a4baae8214cd89c498868b661d99049 | spawnAsync.js | spawnAsync.js | 'use strict';
let spawn = require('cross-spawn');
module.exports = function spawnAsync() {
let args = Array.prototype.slice.call(arguments, 0);
let child;
let promise = new Promise((fulfill, reject) => {
child = spawn.apply(spawn, args);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', data => {
stdout += data;
});
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr += data;
});
}
child.on('close', (code, signal) => {
child.removeAllListeners();
let result = {
pid: child.pid,
output: [stdout, stderr],
stdout,
stderr,
status: code,
signal,
};
if (code) {
let error = new Error(`Process exited with non-zero code: ${code}`);
Object.assign(error, result);
reject(error);
} else {
fulfill(result);
}
});
child.on('error', error => {
child.removeAllListeners();
error.pid = child.pid;
error.output = [stdout, stderr];
error.stdout = stdout;
error.stderr = stderr;
error.status = null;
reject(error);
});
});
promise.child = child;
return promise;
};
| 'use strict';
let spawn = require('cross-spawn');
module.exports = function spawnAsync(...args) {
let child;
let promise = new Promise((fulfill, reject) => {
child = spawn.apply(spawn, args);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', data => {
stdout += data;
});
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr += data;
});
}
child.on('close', (code, signal) => {
child.removeAllListeners();
let result = {
pid: child.pid,
output: [stdout, stderr],
stdout,
stderr,
status: code,
signal,
};
if (code) {
let error = new Error(`Process exited with non-zero code: ${code}`);
Object.assign(error, result);
reject(error);
} else {
fulfill(result);
}
});
child.on('error', error => {
child.removeAllListeners();
error.pid = child.pid;
error.output = [stdout, stderr];
error.stdout = stdout;
error.stderr = stderr;
error.status = null;
reject(error);
});
});
promise.child = child;
return promise;
};
| Use rest param instead of slice | Use rest param instead of slice
| JavaScript | mit | exponentjs/spawn-async,650Industries/spawn-async |
9017acd8ec8e0aaf9cf95d0b64385fb18fff0dcc | lib/config.js | lib/config.js | // Load configurations file
var config = require('../configs/config.json');
// Validate settings
if (!config.mpd || !config.mpd.host || !config.mpd.port) {
throw new Error("You must specify MPD host and port");
}
if (!config.radioStations || (typeof config.radioStations !== 'object')) {
throw new Error('"radioStations" field must be an object');
}
var isRadioStationsEmpty = true;
for(var index in config.radioStations) {
if (config.radioStations.hasOwnProperty(index)) {
isRadioStationsEmpty = false;
config.defaultRadioStation = config.defaultRadioStation || index;
}
}
if (isRadioStationsEmpty) {
throw new Error("You must specify at least one radio station");
}
module.exports = config;
| // Load configurations file
var config = require('../configs/config.json');
// Validate settings
if (!config.mpd || !config.mpd.host || !config.mpd.port) {
throw new Error("You must specify MPD host and port");
}
if (!config.radioStations || (typeof config.radioStations !== 'object')) {
throw new Error('"radioStations" field must be an object');
}
var isRadioStationsEmpty = true;
for(var index in config.radioStations) {
if (config.radioStations.hasOwnProperty(index)) {
isRadioStationsEmpty = false;
config.defaultRadioStation = config.defaultRadioStation || index;
}
}
if (isRadioStationsEmpty) {
throw new Error("You must specify at least one radio station");
}
// Make sure the application port is set
config.server.port = config.server.port || 8000;
module.exports = config;
| Make use server port is set | Make use server port is set
| JavaScript | apache-2.0 | JustBlackBird/bluethroat,JustBlackBird/bluethroat,JustBlackBird/bluethroat |
ee5a87db22b7e527d7d0102072bba5de91ac38fb | lib/errors.js | lib/errors.js | /**
AuthGW Custom Errors
@author tylerFowler
**/
/**
@name InvalidRoleError
@desc Thrown when a role is given that is not in the list of roles
@param { String } invalidRole
**/
function InvalidRoleError(invalidRole) {
this.name = 'InvalidRoleError';
this.message = `${invalidRole} is not a valid role`;
this.stack = (new Error()).stack;
}
InvalidRoleError.prototype = Object.create(Error.prototype);
InvalidRoleError.prototype.constructor = InvalidRoleError;
exports.InvalidRoleError = InvalidRoleError;
| /**
AuthGW Custom Errors
@author tylerFowler
**/
/**
@class InvalidRoleError @extends Error
@desc Thrown when a role is given that is not in the list of roles
@param { String } invalidRole
**/
class InvalidRoleError extends Error {
constructor(invalidRole) {
this.name = 'InvalidRoleError';
this.message = `${invalidRole} is not a valid role`;
}
}
exports.InvalidRoleError = InvalidRoleError;
| Use class syntax for creating error | Use class syntax for creating error
| JavaScript | mit | tylerFowler/authgw |
48ef57b90e8567574199dddb5b6cee78b6b039b0 | src/config.js | src/config.js | export const TZ = 'Europe/Prague'
export const SIRIUS_PROXY_PATH = process.env.SIRIUS_PROXY_PATH
| export const TZ = 'Europe/Prague'
export const SIRIUS_PROXY_PATH = global.SIRIUS_PROXY_PATH || process.env.SIRIUS_PROXY_PATH
| Allow SIRIUS_PROXY_PATH override by global var | Allow SIRIUS_PROXY_PATH override by global var
| JavaScript | mit | cvut/fittable-widget,cvut/fittable,cvut/fittable-widget,cvut/fittable-widget,cvut/fittable,cvut/fittable |
57789e5d40c448ab1138dad987f7d8f9595966ee | .storybook/config.js | .storybook/config.js | import { configure } from '@storybook/vue';
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| import { configure, addParameters } from '@storybook/vue';
// Option defaults:
addParameters({
options: {
name: 'Vue Visual',
panelPosition: 'right',
}
})
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| Put package name in the storybook | Put package name in the storybook
| JavaScript | mit | BKWLD/vue-visual |
2de18a5628f1acf45a5884c93bd985d4f6f367a3 | lib/server.js | lib/server.js | var acquires = {};
var Responder = require('cote').Responder;
var autoReleaseTimeout = 30000;
var counts = {
acquires: 0,
releases: 0
};
function acquire(req, cb) {
console.log('acquire', req.id);
counts.acquires++;
cb.autoRelease = setTimeout(function() {
console.log('auto release', req.id);
release(req);
}, autoReleaseTimeout);
if (acquires[req.id])
return acquires[req.id].push(cb);
acquires[req.id] = [];
cb();
}
function release(req) {
console.log('release', req.id);
counts.releases++;
if (!(req.id in acquires)) return;
if (!acquires[req.id].length)
return delete acquires[req.id];
var cb = acquires[req.id].shift();
cb && cb();
clearTimeout(cb.autoRelease);
}
function init() {
var server = new Responder({
name: 'semaver server',
key: 'semaver',
respondsTo: ['acquire', 'release']
});
server.on('acquire', acquire);
server.on('release', release);
setInterval(function() {
console.log('counts', counts);
if (Object.keys(acquires).length)
console.log(acquires);
}, 1000);
}
module.exports = {
init: init
};
| var acquires = {};
var Responder = require('cote').Responder;
var autoReleaseTimeout = 30000;
var counts = {
acquires: 0,
releases: 0
};
function acquire(req, cb) {
console.log('acquire', req.id);
counts.acquires++;
if (acquires[req.id]) {
cb.autoRelease = setTimeout(function() {
console.log('auto release', req.id);
release(req);
}, autoReleaseTimeout);
return acquires[req.id].push(cb);
}
acquires[req.id] = [];
cb();
}
function release(req) {
console.log('release', req.id);
counts.releases++;
if (!(req.id in acquires)) return;
if (!acquires[req.id].length)
return delete acquires[req.id];
var cb = acquires[req.id].shift();
cb && cb();
clearTimeout(cb.autoRelease);
}
function init() {
var server = new Responder({
name: 'semaver server',
key: 'semaver',
respondsTo: ['acquire', 'release']
});
server.on('acquire', acquire);
server.on('release', release);
setInterval(function() {
console.log('counts', counts);
if (Object.keys(acquires).length)
console.log(acquires);
}, 1000);
}
module.exports = {
init: init
};
| Move auto release timeout to if check in acquire. | Move auto release timeout to if check in acquire. | JavaScript | apache-2.0 | tart/semaver |
f5774e3fb24ca403de481e446c3bf68fa78b2c47 | spec/fixtures/api/quit-app/main.js | spec/fixtures/api/quit-app/main.js | var app = require('electron').app
app.on('ready', function () {
app.exit(123)
})
process.on('exit', function (code) {
console.log('Exit event with code: ' + code)
})
| var app = require('electron').app
app.on('ready', function () {
// This setImmediate call gets the spec passing on Linux
setImmediate(function () {
app.exit(123)
})
})
process.on('exit', function (code) {
console.log('Exit event with code: ' + code)
})
| Exit from a setImmediate callback | Exit from a setImmediate callback
| JavaScript | mit | seanchas116/electron,felixrieseberg/electron,pombredanne/electron,bpasero/electron,wan-qy/electron,leftstick/electron,the-ress/electron,jaanus/electron,deed02392/electron,thomsonreuters/electron,brave/muon,tonyganch/electron,tinydew4/electron,thomsonreuters/electron,gerhardberger/electron,roadev/electron,simongregory/electron,the-ress/electron,rreimann/electron,shiftkey/electron,thomsonreuters/electron,kcrt/electron,preco21/electron,aichingm/electron,ankitaggarwal011/electron,Floato/electron,Gerhut/electron,voidbridge/electron,leftstick/electron,seanchas116/electron,thingsinjars/electron,aliib/electron,jhen0409/electron,MaxWhere/electron,roadev/electron,bpasero/electron,lzpfmh/electron,joaomoreno/atom-shell,lzpfmh/electron,kokdemo/electron,rajatsingla28/electron,Floato/electron,dongjoon-hyun/electron,renaesop/electron,brenca/electron,etiktin/electron,posix4e/electron,astoilkov/electron,brenca/electron,Floato/electron,ankitaggarwal011/electron,thompsonemerson/electron,lzpfmh/electron,miniak/electron,dongjoon-hyun/electron,gabriel/electron,posix4e/electron,minggo/electron,deed02392/electron,leftstick/electron,thompsonemerson/electron,shiftkey/electron,astoilkov/electron,voidbridge/electron,miniak/electron,felixrieseberg/electron,rreimann/electron,lzpfmh/electron,simongregory/electron,pombredanne/electron,stevekinney/electron,roadev/electron,stevekinney/electron,gerhardberger/electron,jaanus/electron,minggo/electron,Floato/electron,the-ress/electron,tinydew4/electron,bbondy/electron,wan-qy/electron,gabriel/electron,the-ress/electron,tinydew4/electron,aliib/electron,biblerule/UMCTelnetHub,leethomas/electron,bbondy/electron,biblerule/UMCTelnetHub,brave/muon,miniak/electron,renaesop/electron,noikiy/electron,stevekinney/electron,lzpfmh/electron,ankitaggarwal011/electron,thingsinjars/electron,thompsonemerson/electron,noikiy/electron,minggo/electron,kokdemo/electron,joaomoreno/atom-shell,etiktin/electron,thomsonreuters/electron,tonyganch/electron,stevekinney/electron,kcrt/electron,leethomas/electron,bbondy/electron,voidbridge/electron,stevekinney/electron,kcrt/electron,rajatsingla28/electron,Floato/electron,felixrieseberg/electron,Gerhut/electron,felixrieseberg/electron,voidbridge/electron,evgenyzinoviev/electron,brave/electron,electron/electron,dongjoon-hyun/electron,simongregory/electron,voidbridge/electron,gabriel/electron,rajatsingla28/electron,gabriel/electron,electron/electron,thomsonreuters/electron,kokdemo/electron,tonyganch/electron,gerhardberger/electron,aichingm/electron,twolfson/electron,electron/electron,simongregory/electron,leftstick/electron,simongregory/electron,aichingm/electron,tonyganch/electron,aliib/electron,brave/electron,leethomas/electron,seanchas116/electron,tylergibson/electron,aichingm/electron,rajatsingla28/electron,roadev/electron,tylergibson/electron,twolfson/electron,bbondy/electron,shiftkey/electron,tinydew4/electron,astoilkov/electron,dongjoon-hyun/electron,evgenyzinoviev/electron,electron/electron,aliib/electron,brave/muon,rajatsingla28/electron,thingsinjars/electron,twolfson/electron,voidbridge/electron,joaomoreno/atom-shell,kcrt/electron,evgenyzinoviev/electron,renaesop/electron,tinydew4/electron,thompsonemerson/electron,leftstick/electron,leftstick/electron,MaxWhere/electron,brave/electron,bpasero/electron,renaesop/electron,brave/electron,seanchas116/electron,shiftkey/electron,brave/muon,wan-qy/electron,minggo/electron,thingsinjars/electron,noikiy/electron,etiktin/electron,brave/muon,tonyganch/electron,kcrt/electron,rreimann/electron,deed02392/electron,astoilkov/electron,Gerhut/electron,jaanus/electron,aichingm/electron,bpasero/electron,biblerule/UMCTelnetHub,minggo/electron,pombredanne/electron,rreimann/electron,deed02392/electron,kokdemo/electron,the-ress/electron,biblerule/UMCTelnetHub,rreimann/electron,brenca/electron,wan-qy/electron,thompsonemerson/electron,thingsinjars/electron,leethomas/electron,renaesop/electron,minggo/electron,jhen0409/electron,posix4e/electron,leethomas/electron,aichingm/electron,preco21/electron,Evercoder/electron,brave/electron,preco21/electron,seanchas116/electron,shiftkey/electron,tylergibson/electron,Evercoder/electron,miniak/electron,Evercoder/electron,gerhardberger/electron,dongjoon-hyun/electron,Gerhut/electron,posix4e/electron,evgenyzinoviev/electron,tylergibson/electron,Evercoder/electron,MaxWhere/electron,brenca/electron,jhen0409/electron,electron/electron,preco21/electron,bpasero/electron,noikiy/electron,jhen0409/electron,felixrieseberg/electron,tylergibson/electron,astoilkov/electron,kokdemo/electron,seanchas116/electron,astoilkov/electron,wan-qy/electron,dongjoon-hyun/electron,jaanus/electron,preco21/electron,gerhardberger/electron,brenca/electron,simongregory/electron,leethomas/electron,roadev/electron,noikiy/electron,posix4e/electron,kcrt/electron,electron/electron,gerhardberger/electron,deed02392/electron,preco21/electron,Evercoder/electron,twolfson/electron,joaomoreno/atom-shell,felixrieseberg/electron,gabriel/electron,jaanus/electron,tonyganch/electron,evgenyzinoviev/electron,thompsonemerson/electron,brave/electron,twolfson/electron,gerhardberger/electron,ankitaggarwal011/electron,twolfson/electron,bpasero/electron,pombredanne/electron,renaesop/electron,jaanus/electron,thingsinjars/electron,etiktin/electron,shiftkey/electron,bbondy/electron,MaxWhere/electron,bpasero/electron,ankitaggarwal011/electron,MaxWhere/electron,Gerhut/electron,joaomoreno/atom-shell,pombredanne/electron,the-ress/electron,tylergibson/electron,jhen0409/electron,jhen0409/electron,brave/muon,gabriel/electron,rajatsingla28/electron,tinydew4/electron,posix4e/electron,lzpfmh/electron,joaomoreno/atom-shell,biblerule/UMCTelnetHub,electron/electron,ankitaggarwal011/electron,aliib/electron,biblerule/UMCTelnetHub,miniak/electron,wan-qy/electron,miniak/electron,bbondy/electron,Evercoder/electron,etiktin/electron,noikiy/electron,roadev/electron,kokdemo/electron,brenca/electron,pombredanne/electron,aliib/electron,MaxWhere/electron,rreimann/electron,the-ress/electron,thomsonreuters/electron,Gerhut/electron,Floato/electron,deed02392/electron,etiktin/electron,evgenyzinoviev/electron,stevekinney/electron |
ad16587294c3186a89e84105fb2e390b36f26ca0 | lib/switch.js | lib/switch.js | const gpio = require('raspi-gpio')
module.exports = class Switch {
constructor (pinId) {
this.nInput = new gpio.DigitalInput(pinId, gpio.PULL_UP)
}
on (changeListener) {
this.nInput.on('change', (value) => {
changeListener(value)
})
}
}
| const gpio = require('raspi-gpio')
module.exports = class Switch {
constructor (pinId) {
this.nInput = new gpio.DigitalInput({
pin: pinId,
pullResistor: gpio.PULL_UP})
}
on (changeListener) {
this.nInput.on('change', (value) => {
changeListener(value)
})
}
}
| Fix pin pull resistor config | Fix pin pull resistor config
| JavaScript | mit | DanStough/josl |
b9e214312ec055e7e6d64fcc6a75b108c6176657 | js/index.js | js/index.js | // Pullquotes
document.addEventListener("DOMContentLoaded", function(event) {
function pullQuote(el){
var parentParagraph = el.parentNode;
parentParagraph.style.position = 'relative';
var clone = el.cloneNode(true);
clone.setAttribute('class','semantic-pull-quote--pulled');
// Hey y’all, watch this!
parentParagraph.parentNode.parentNode.insertBefore(clone, parentParagraph.parentNode);
if(!clone.getAttribute('data-content')){
clone.setAttribute('data-content', clone.innerHTML );
clone.innerHTML = null;
}
};
var pullQuotes = document.getElementsByClassName('semantic-pull-quote');
for(var i = 0; i < pullQuotes.length; i++) {
pullQuote(pullQuotes[i]);
}
});
| // Semantic Pullquotes
document.addEventListener("DOMContentLoaded", function(event) {
function pullQuote(el){
var parentParagraph = el.parentNode;
parentParagraph.style.position = 'relative';
var clone = el.cloneNode(true);
clone.setAttribute('class','semantic-pull-quote--pulled');
// Hey y’all, watch this!
parentParagraph.parentNode.parentNode.insertBefore(clone, parentParagraph.parentNode);
if(!clone.getAttribute('data-content')){
clone.setAttribute('data-content', clone.innerHTML );
clone.innerHTML = null;
}
};
var pullQuotes = document.getElementsByClassName('semantic-pull-quote');
for(var i = 0; i < pullQuotes.length; i++) {
pullQuote(pullQuotes[i]);
}
});
| Rename Pullquotes --> Semantic Pullquotes | Rename Pullquotes --> Semantic Pullquotes
| JavaScript | mit | curiositry/sassisfy,curiositry/sassisfy |
234138b3a81e6db0439851c131448eb3f030f146 | app/send-native.js | app/send-native.js | 'use strict';
const application = 'io.github.deathcap.nodeachrome';
function decodeResponse(response, cb) {
console.log('decodeResponse',response);
if (typeof cb !== 'function') { console.error('??? decodeResponse non-string callback',cb); cb = () => {}; }
if (!response) return cb(chrome.runtime.lastError);
if (response.error) return cb(new Error(response.error.message));
return cb(null, response.result);
}
// Send message using Google Chrome Native Messaging API to a native code host
function sendNative(method, params, cb) {
console.log('sendNative',method,params);
const msg = {method: method, params: params};
chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb));
}
module.exports = sendNative;
| 'use strict';
const application = 'io.github.deathcap.nodeachrome';
let callbacks = new Map();
let nextID = 1;
let port = null;
function decodeResponse(response, cb) {
console.log('decodeResponse',response);
if (typeof cb !== 'function') { console.error('??? decodeResponse non-string callback',cb); cb = () => {}; }
if (!response) return cb(chrome.runtime.lastError);
if (response.error) return cb(new Error(response.error.message));
return cb(null, response.result);
}
function recvIncoming(msg) {
const cb = callbacks.get(msg.id);
if (!cb) {
throw new Error(`received native host message with unexpected id: ${msg.id} in ${JSON.stringify(msg)}`);
}
cb(msg);
callbacks.delete(msg.id);
}
function disconnected(e) {
console.log('unexpected native host disconnect:',e);
throw new Error('unexpected native host disconnect:'+e);
// TODO: reconnect? if it crashes
}
function connectPort() {
port = chrome.runtime.connectNative(application);
port.onMessage.addListener(recvIncoming);
port.onDisconnect.addListener(disconnected);
return port;
}
// Send message using Google Chrome Native Messaging API to a native code host
function sendNative(method, params, cb) {
console.log('sendNative',method,params);
const id = nextID;
nextID += 1;
const msg = {method: method, params: params, id: id};
if (!port) {
port = connectPort();
}
callbacks.set(id, (response) => decodeResponse(response, cb));
port.postMessage(msg);
// the one-off sendNativeMessage call is convenient in that it accepts a response callback,
// but it launches the host app every time, so it doesn't preserve open filehandles (for e.g. fs.open/fs.write)
//chrome.runtime.sendNativeMessage(application, msg, (response) => decodeResponse(response, cb));
}
module.exports = sendNative;
| Change native messaging to keep the host running persistently, maintaining an open port | Change native messaging to keep the host running persistently, maintaining an open port
| JavaScript | mit | deathcap/nodeachrome,deathcap/nodeachrome,deathcap/nodeachrome |
a6a42353b20a9282bdb83cf45c0111954b9d6888 | ember-cli-build.js | ember-cli-build.js | /* eslint-env node */
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
| /* eslint-env node */
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
'ember-cli-babel': {
includePolyfill: true
},
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
| Include ember-cli-babel polyfil to fix tests | Include ember-cli-babel polyfil to fix tests
| JavaScript | mit | amiel/ember-data-url-templates,amiel/ember-data-url-templates |
1db74f03479538911f1c9336df233aea3c7cc622 | karma.conf.js | karma.conf.js | var webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'test/**/*.ts'
],
exclude: [
],
preprocessors: {
'src/**/!(defaults)/*.js': ['coverage'],
'test/**/*.ts': ['webpack']
},
webpack: {
module: webpackConfig.module,
resolve: webpackConfig.resolve
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeES6'],
singleRun: true,
concurrency: Infinity,
coverageReporter: {
includeAllSources: true,
reporters: [
// generates ./coverage/lcov.info
{ type: 'lcovonly', subdir: '.' },
// generates ./coverage/coverage-final.json
{ type: 'json', subdir: '.' },
// generates HTML reports
{ type: 'html', dir: 'coverage/' }
]
},
customLaunchers: {
ChromeES6: {
base: 'Chrome',
flags: ['--javascript-harmony', '--no-sandbox']
}
}
})
} | var webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'test/**/*.ts'
],
mime: {
'text/x-typescript': ['ts', 'tsx']
},
exclude: [
],
preprocessors: {
'src/**/!(defaults)/*.js': ['coverage'],
'test/**/*.ts': ['webpack']
},
webpack: {
module: webpackConfig.module,
resolve: webpackConfig.resolve
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeES6'],
singleRun: true,
concurrency: Infinity,
coverageReporter: {
includeAllSources: true,
reporters: [
// generates ./coverage/lcov.info
{ type: 'lcovonly', subdir: '.' },
// generates ./coverage/coverage-final.json
{ type: 'json', subdir: '.' },
// generates HTML reports
{ type: 'html', dir: 'coverage/' }
]
},
customLaunchers: {
ChromeES6: {
base: 'Chrome',
flags: ['--javascript-harmony', '--no-sandbox']
}
}
})
} | Add mime type option in karma file! | Add mime type option in karma file!
| JavaScript | apache-2.0 | proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic |
a551c502c03f0e324aa0765d36799f3c8305b2f2 | app/utils/index.js | app/utils/index.js | const moment = require('moment');
export const dateFormat = (utcDate) => {
return moment(utcDate, 'YYYY-MM-DD hh:mm:ss z').format('LLL');
};
| const moment = require('moment');
export const dateFormat = (utcDate) => {
return moment.utc(new Date(utcDate)).format('LLL');
};
| Use Date function to help parse timezone. | Use Date function to help parse timezone.
| JavaScript | mit | FuBoTeam/fubo-flea-market,FuBoTeam/fubo-flea-market |
ec5401d64467628fa318a96363dcd4ae85ff1d98 | get_languages.js | get_languages.js | var request = require('request');
var yaml = require('js-yaml');
module.exports = function (callback) {
var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
request(languagesURL, function (error, response, body) {
var languages = yaml.safeLoad(body);
Object.keys(languages).forEach(function (languageName) {
languages[languageName] = languages[languageName].color;
});
if (!error && response.statusCode === 200) {
callback(languages);
} else {
callback(undefined);
}
});
};
| var request = require('request');
var yaml = require('js-yaml');
module.exports = function (callback) {
var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
request(languagesURL, function (error, response, body) {
var languages = yaml.safeLoad(body);
Object.keys(languages).forEach(function (languageName) {
if (languages[languageName]) {
languages[languageName] = languages[languageName].color;
} else {
delete languages[languageName];
}
});
if (!error && response.statusCode === 200) {
callback(languages);
} else {
callback(undefined);
}
});
};
| Remove languages that don't have colors | Remove languages that don't have colors
| JavaScript | mit | nicolasmccurdy/language-colors,nicolasmccurdy/language-colors |
e24f9da2e1b107767453a8693be90cfb97ebe76c | lib/index.js | lib/index.js | /**
* isUndefined
* Checks if a value is undefined or not.
*
* @name isUndefined
* @function
* @param {Anything} input The input value.
* @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise.
*/
module.exports = function isUndefined(input) {
return typeof input === 'undefined';
};
| "use strict";
/**
* isUndefined
* Checks if a value is undefined or not.
*
* @name isUndefined
* @function
* @param {Anything} input The input value.
* @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise.
*/
let u = void 0;
module.exports = input => input === u;
| Use void 0 to get the undefined value. | Use void 0 to get the undefined value.
| JavaScript | mit | IonicaBizau/is-undefined |
5aff66da9b38b94fe0e6b453ecb2678e0f743d8a | example/i18n/fr.js | example/i18n/fr.js | export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues ?',
comments: 'Commentaires',
created_at: 'Créer le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créer le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
};
export default messages;
| export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues',
comments: 'Commentaires',
created_at: 'Créé le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créé le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
resources: {
comments: 'Commentaire |||| Commentaires'
}
};
export default messages;
| Fix typos in French translation of the example | Fix typos in French translation of the example
| JavaScript | mit | matteolc/admin-on-rest,matteolc/admin-on-rest,marmelab/admin-on-rest,marmelab/admin-on-rest |
cbfb5044b5d16a826f98104f52c8588fffbfb6c0 | src/deploy.spec.js | src/deploy.spec.js | import {describe, it} from 'mocha';
import {
assertThat, equalTo,
} from 'hamjest';
const toSrcDestPairs = (files, {sourcePath, destinationPath}) =>
files.map(file => ({
sourceFileName: file,
destinationFilename: file.replace(sourcePath, destinationPath)
}))
;
describe('Build src-dest pairs from file names', () => {
const sourcePath = '/src/path';
const destinationPath = '/dest/path';
const deps = {sourcePath, destinationPath};
const buildPairs = (files) =>
toSrcDestPairs(files, deps)
;
it('WHEN no file names given return empty pairs', () => {
const noFiles = [];
assertThat(buildPairs(noFiles), equalTo([]));
});
it('WHEN one file given, replace src path with dest path', () => {
const oneSrcFile = [`${sourcePath}/file.js`];
const onePair = [{
sourceFileName: `${sourcePath}/file.js`,
destinationFilename: `${destinationPath}/file.js`
}];
assertThat(buildPairs(oneSrcFile), equalTo(onePair));
});
});
| import {describe, it} from 'mocha';
import {
assertThat, equalTo,
} from 'hamjest';
const toSrcDestPairs = (files, {sourcePath, destinationPath}) =>
files.map(file => ({
sourceFileName: file,
destinationFilename: file.replace(sourcePath, destinationPath)
}))
;
describe('Build src-dest pairs from file names', () => {
const sourcePath = '/src/path';
const destinationPath = '/dest/path';
const deps = {sourcePath, destinationPath};
const buildPairs = (files) =>
toSrcDestPairs(files, deps)
;
it('WHEN no file names given return empty pairs', () => {
const noFiles = [];
assertThat(buildPairs(noFiles), equalTo([]));
});
it('WHEN one file given, replace src path with dest path', () => {
const oneSrcFile = [`${sourcePath}/file.js`];
const onePair = [{
sourceFileName: `${sourcePath}/file.js`,
destinationFilename: `${destinationPath}/file.js`
}];
assertThat(buildPairs(oneSrcFile), equalTo(onePair));
});
it('WHEN many files given, replace src path with dest path', () => {
const manyFile = [
`${sourcePath}/file.js`,
`${sourcePath}/any/depth/file.js`,
];
const manyPairs = [
{sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js`},
{sourceFileName: `${sourcePath}/any/depth/file.js`, destinationFilename: `${destinationPath}/any/depth/file.js`},
];
assertThat(buildPairs(manyFile), equalTo(manyPairs));
});
});
| Write a (documenting) test that describes the "lots-case". | Write a (documenting) test that describes the "lots-case".
| JavaScript | mit | tddbin/katas,tddbin/katas,tddbin/katas |
e082e386adc50466d4c30a24dea8ce6a93b265b4 | routes/admin/authenticated/sidebar/templates-list/page.connected.js | routes/admin/authenticated/sidebar/templates-list/page.connected.js | import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import * as MobilizationActions from '~mobilizations/action-creators'
import * as MobilizationSelectors from '~mobilizations/selectors'
import * as TemplateActions from '~mobilizations/templates/action-creators'
import * as TemplateSelectors from '~mobilizations/templates/selectors'
import Page from './page'
const redial = {
fetch: ({ dispatch, getState, params }) => {
const state = getState()
const promises = []
!TemplateSelectors.isLoaded(state) && promises.push(
dispatch(TemplateActions.asyncFetch())
)
promises.push(dispatch(MobilizationActions.toggleMenu(undefined)))
return Promise.all(promises)
}
}
const mapStateToProps = state => ({
loading: TemplateSelectors.isLoading(state),
menuActiveIndex: MobilizationSelectors.getMenuActiveIndex(state),
mobilizationTemplates: TemplateSelectors.getCustomTemplates(state)
})
const mapActionCreatorsToProps = {
asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate,
toggleMenu: MobilizationActions.toggleMenu
}
export default provideHooks(redial)(
connect(mapStateToProps, mapActionCreatorsToProps)(Page)
)
| import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import MobSelectors from '~client/mobrender/redux/selectors'
import { toggleMobilizationMenu } from '~client/mobrender/redux/action-creators'
import * as TemplateActions from '~mobilizations/templates/action-creators'
import * as TemplateSelectors from '~mobilizations/templates/selectors'
import Page from './page'
const redial = {
fetch: ({ dispatch, getState, params }) => {
const state = getState()
const promises = []
!TemplateSelectors.isLoaded(state) && promises.push(
dispatch(TemplateActions.asyncFetch())
)
promises.push(dispatch(toggleMobilizationMenu(undefined)))
return Promise.all(promises)
}
}
const mapStateToProps = state => ({
loading: TemplateSelectors.isLoading(state),
menuActiveIndex: MobSelectors(state).getMobilizationMenuActive(),
mobilizationTemplates: TemplateSelectors.getCustomTemplates(state)
})
const mapActionCreatorsToProps = {
asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate,
toggleMenu: toggleMobilizationMenu
}
export default provideHooks(redial)(
connect(mapStateToProps, mapActionCreatorsToProps)(Page)
)
| Fix menu in template list | Fix menu in template list
| JavaScript | agpl-3.0 | nossas/bonde-client,nossas/bonde-client,nossas/bonde-client |
26325efdf4836d0eb44a4f987830c38562222cda | public/javascripts/app.js | public/javascripts/app.js | var app = angular.module("blogApp", []);
var posts = [];
app.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'BlogCtrl'
})
.when('/post/:postId', {
templateUrl: 'views/post.html',
controller: 'PostCtrl'
})
.otherwise({
redirectTo: '/'
});
});
var socket = io.connect(window.location.origin);
socket.on('message', function(data)
{
switch(data.type)
{
default: break;
}
}); | var app = angular.module("blogApp", []);
var posts = [];
app.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'BlogCtrl'
})
.when('/post/:postId', {
templateUrl: 'views/post.html',
controller: 'PostCtrl'
})
.otherwise({
redirectTo: '/'
});
});
var host = location.origin.replace(/^http/, 'ws');
var socket = io.connect(host);
socket.on('message', function(data)
{
switch(data.type)
{
default: break;
}
}); | Change for socket connection on Heroku | Change for socket connection on Heroku
| JavaScript | mit | Somojojojo/blog |
6621c6e7cc5fb3d62d8a5fabb08cf870b72ed5fe | lib/dropbox/index.js | lib/dropbox/index.js | 'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
| 'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
profile.access_token = accessToken;
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
| Add accessToken to profile before done | Add accessToken to profile before done
| JavaScript | mit | svacha/jsbin,filamentgroup/jsbin,eggheadio/jsbin,late-warrior/jsbin,thsunmy/jsbin,pandoraui/jsbin,ilyes14/jsbin,digideskio/jsbin,saikota/jsbin,AverageMarcus/jsbin,fgrillo21/NPA-Exam,late-warrior/jsbin,peterblazejewicz/jsbin,juliankrispel/jsbin,francoisp/jsbin,ctide/jsbin,juliankrispel/jsbin,KenPowers/jsbin,mdo/jsbin,mingzeke/jsbin,dedalik/jsbin,jsbin/jsbin,IvanSanchez/jsbin,Freeformers/jsbin,jwdallas/jsbin,ilyes14/jsbin,vipulnsward/jsbin,arcseldon/jsbin,HeroicEric/jsbin,mingzeke/jsbin,digideskio/jsbin,jasonsanjose/jsbin-app,jamez14/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,saikota/jsbin,dennishu001/jsbin,jsbin/jsbin,ctide/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,yize/jsbin,Hamcha/jsbin,johnmichel/jsbin,y3sh/jsbin-fork,pandoraui/jsbin,nitaku/jervis,fgrillo21/NPA-Exam,kentcdodds/jsbin,johnmichel/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,dennishu001/jsbin,filamentgroup/jsbin,vipulnsward/jsbin,kirjs/jsbin,eggheadio/jsbin,Hamcha/jsbin,KenPowers/jsbin,simonThiele/jsbin,francoisp/jsbin,mlucool/jsbin,dedalik/jsbin,roman01la/jsbin,yohanboniface/jsbin,blesh/jsbin,jwdallas/jsbin,jamez14/jsbin,kentcdodds/jsbin,jasonsanjose/jsbin-app,simonThiele/jsbin,thsunmy/jsbin,dhval/jsbin,IveWong/jsbin,mcanthony/jsbin,IveWong/jsbin,martinvd/jsbin,minwe/jsbin,yize/jsbin,fend-classroom/jsbin,dhval/jsbin,Freeformers/jsbin,roman01la/jsbin,AverageMarcus/jsbin,knpwrs/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,mcanthony/jsbin,kirjs/jsbin,minwe/jsbin,KenPowers/jsbin,svacha/jsbin,martinvd/jsbin,mlucool/jsbin,knpwrs/jsbin,fend-classroom/jsbin,remotty/jsbin |
bb9858b1edbc7f8fe7a2abd70110adb50055ff8c | lib/main.js | lib/main.js | import "es6-symbol";
import "weakmap";
import svgLoader from "./loader.js";
import Icon from "./components/Icon.js";
import Sprite from "./components/Sprite.js";
import Theme from "./components/Theme.js";
var callback = function callback() { };
const icons = Icon;
const initLoader = svgLoader;
// loads an external SVG file as sprite.
function load(loader, onFulfilled, onRejected) {
if (!onRejected) { onRejected = callback; }
if (typeof loader === "string") {
loader = svgLoader(loader);
} else if (!loader || !loader.request) {
onRejected(new TypeError("Invalid Request"));
}
loader.onSuccess = function(svg) {
make(svg, onFulfilled, onRejected);
};
loader.onFailure = function(e) {
onRejected(new TypeError(e));
};
loader.send();
}
function make(svg, onFulfilled, onRejected) {
var theme;
var autorun = false;
if (!onFulfilled) {
onFulfilled = callback;
autorun = true;
}
if (!onRejected) { onRejected = callback; }
try {
var sprite = new Sprite(svg);
theme = new Theme(sprite);
onFulfilled(theme);
if (autorun) {
theme.render();
}
} catch (e) {
onRejected(e);
}
}
export { icons, initLoader, load, make };
| import "es6-symbol";
import "weakmap";
import svgLoader from "./loader.js";
import Icon from "./components/Icon.js";
import Sprite from "./components/Sprite.js";
import Theme from "./components/Theme.js";
var callback = function callback() { };
const icons = Icon;
const initLoader = svgLoader;
// loads an external SVG file as sprite.
function load(loader, onFulfilled, onRejected) {
if (!onRejected) { onRejected = callback; }
if (typeof loader === "string") {
loader = svgLoader(loader);
} else if (!loader || !loader.request) {
onRejected(new TypeError("Invalid Request"));
}
loader.onSuccess = function onSuccess(svg) {
make(svg, onFulfilled, onRejected);
};
loader.onFailure = function onFailure(e) {
onRejected(new TypeError(e));
};
loader.send();
}
function make(svg, onFulfilled, onRejected) {
var theme;
var autorun = false;
if (!onFulfilled) {
onFulfilled = callback;
autorun = true;
}
if (!onRejected) { onRejected = callback; }
try {
var sprite = new Sprite(svg);
theme = new Theme(sprite);
onFulfilled(theme);
if (autorun) {
theme.render();
}
} catch (e) {
onRejected(e);
}
}
export { icons, initLoader, load, make };
| Update name of callback functions | Update name of callback functions
| JavaScript | mit | vuzonp/uxon |
19e3dc49302a635f51bcd552fb70b434c0968520 | tests/cross-context-instance.js | tests/cross-context-instance.js | let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.globalReference();
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context1.isReference.applySync(null, [ new ivm.Reference({}) ])) {
console.log('fail1');
}
if (!context1.isReference.applySync(null, [ context1.makeReference.applySync(null, [ 1 ]) ])) {
console.log('fail2');
}
});
if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) {
console.log('fail3');
}
console.log('pass');
| let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
function makeContext() {
let context = isolate.createContextSync();
let global = context.globalReference();
global.setSync('ivm', ivm);
isolate.compileScriptSync(`
function makeReference(ref) {
return new ivm.Reference(ref);
}
function isReference(ref) {
return ref instanceof ivm.Reference;
}
`).runSync(context);
return {
makeReference: global.getSync('makeReference'),
isReference: global.getSync('isReference'),
};
}
let context1 = makeContext();
let context2 = makeContext();
[ context1, context2 ].forEach(context => {
if (!context.isReference.applySync(null, [ new ivm.Reference({}) ])) {
console.log('fail1');
}
if (!context.isReference.applySync(null, [ context.makeReference.applySync(null, [ 1 ]) ])) {
console.log('fail2');
}
});
if (context1.isReference.applySync(null, [ context2.makeReference.applySync(null, [ 1 ]).derefInto() ])) {
console.log('fail3');
}
console.log('pass');
| Fix test wasn't actually testing | Fix test wasn't actually testing
| JavaScript | isc | laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm,laverdet/isolated-vm |
0c44942fa439737c8adf26a2e196bbd700e18e66 | R7.University.Employee/js/module.js | R7.University.Employee/js/module.js | $(function () {
// paint tables with dnnGrid classes
var table = ".employeeDetails #employeeDisciplines table";
$(table).addClass ("dnnGrid").css ("border-collapse", "collapse");
// use parent () to get rows with matched cell types
$(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem");
$(table + " tr:nth-child(odd) td").parent ().addClass ("dnnGridAltItem");
// paint headers
$(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left");
}); | $(function () {
// paint tables with dnnGrid classes
var table = ".employeeDetails #employeeDisciplines table";
$(table).addClass ("dnnGrid").css ("border-collapse", "collapse");
// use parent () to get rows with matched cell types
$(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem")
.next ().addClass ("dnnGridAltItem");
// paint headers
$(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left");
}); | Optimize & fix table painting script | Optimize & fix table painting script | JavaScript | agpl-3.0 | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University |
ef259591d22d303c351b419f130b13061e28771a | app/native/src/types/Navigation.js | app/native/src/types/Navigation.js | // @flow
export type Navigation = {
navigate: (screen: string, parameters?: Object) => void,
state: {
params: Object,
},
};
| // @flow
type NavigationStateParameters = Object;
/**
* @see https://reactnavigation.org/docs/navigators/navigation-prop
*/
export type Navigation = {
navigate: (routeName: string, parameters?: NavigationStateParameters) => void,
state: {
params: NavigationStateParameters,
},
setParams: (newParameters: NavigationStateParameters) => void,
goBack: () => void,
};
| Improve Flow type of the navigation | Improve Flow type of the navigation
| JavaScript | mit | mrtnzlml/native,mrtnzlml/native |
1b6904a33c0f83eddf6c759ebe4243d54eb1f54f | app/services/resizeable-columns.js | app/services/resizeable-columns.js | import Ember from "ember";
const { $, inject, run } = Ember;
export default Ember.Service.extend({
fastboot: inject.service(),
init() {
this._super(...arguments);
if (!this.get('fastboot.isFastBoot')) {
this.setupMouseEventsFromIframe();
}
},
setupMouseEventsFromIframe() {
window.addEventListener('message', (m) => {
run(() => {
if(typeof m.data==='object' && 'mousemove' in m.data) {
let event = $.Event("mousemove", {
pageX: m.data.mousemove.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.data.mousemove.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
}
if(typeof m.data==='object' && 'mouseup' in m.data) {
let event = $.Event("mouseup", {
pageX: m.data.mouseup.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.data.mouseup.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
}
});
});
}
});
| import Ember from "ember";
const { $, inject, run } = Ember;
export default Ember.Service.extend({
fastboot: inject.service(),
init() {
this._super(...arguments);
if (!this.get('fastboot.isFastBoot')) {
this.setupMouseEventsFromIframe();
}
},
handleMouseEvents(m, mouseEvent) {
const event = $.Event(mouseEvent, {
pageX: m.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
},
setupMouseEventsFromIframe() {
window.addEventListener('message', (m) => {
run(() => {
if(typeof m.data==='object' && 'mousemove' in m.data) {
this.handleMouseEvents(m.data.mousemove, 'mousemove');
}
if(typeof m.data==='object' && 'mouseup' in m.data) {
this.handleMouseEvents(m.data.mouseup, 'mousemove');
}
});
});
}
});
| Refactor mouse events in resizeable columns | Refactor mouse events in resizeable columns
| JavaScript | mit | ember-cli/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle,Gaurav0/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle |
78874dcdad510e76c2ee6d47c6b0ac72073b3e7c | lib/loaders/index.js | lib/loaders/index.js | import loadersWithAuthentication from "./loaders_with_authentication"
import loadersWithoutAuthentication from "./loaders_without_authentication"
export default (accessToken, userID) => {
const loaders = loadersWithoutAuthentication()
if (accessToken) {
return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID))
}
return loaders
}
| import loadersWithAuthentication from "./loaders_with_authentication"
import loadersWithoutAuthentication from "./loaders_without_authentication"
/**
* Creates a new set of data loaders for all routes. These should be created for each GraphQL query and passed to the
* `graphql` query execution function.
*
* Only if credentials are provided will the set include authenticated loaders, so before using an authenticated loader
* it would be wise to check if the loader is not in fact `undefined`.
*/
export default (accessToken, userID) => {
const loaders = loadersWithoutAuthentication()
if (accessToken) {
return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID))
}
return loaders
}
| Add documentation for a bunch of functions. | [loaders] Add documentation for a bunch of functions.
| JavaScript | mit | craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics,craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1 |
da8027163e556a84e60d0c41bd61ea4b8a42ef05 | src/renderer/scr.dom.js | src/renderer/scr.dom.js | var DOM = (function(){
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
var entityRegex = /[&<>"'\/]/g;
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: function(id, parent){
return (parent || document).getElementById(id);
},
/*
* Returns an array of all child elements containing the specified class. Parent defaults to the entire document.
*/
cls: function(cls, parent){
return Array.prototype.slice.call((parent || document).getElementsByClassName(cls));
},
/*
* Returns an array of all child elements that have the specified tag. Parent defaults to the entire document.
*/
tag: function(tag, parent){
return Array.prototype.slice.call((parent || document).getElementsByTagName(tag));
},
/*
* Creates an element, adds it to the DOM, and returns it.
*/
createElement: function(tag, parent){
var ele = document.createElement(tag);
parent.appendChild(ele);
return ele;
},
/*
* Removes an element from the DOM.
*/
removeElement: function(ele){
ele.parentNode.removeChild(ele);
},
/*
* Converts characters to their HTML entity form.
*/
escapeHTML: function(html){
return html.replace(entityRegex, s => entityMap[s]);
}
};
})();
| var DOM = (function(){
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
var entityRegex = /[&<>"'\/]/g;
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: function(id, parent){
return (parent || document).getElementById(id);
},
/*
* Returns an array of all child elements containing the specified class. Parent defaults to the entire document.
*/
cls: function(cls, parent){
return Array.prototype.slice.call((parent || document).getElementsByClassName(cls));
},
/*
* Returns an array of all child elements that have the specified tag. Parent defaults to the entire document.
*/
tag: function(tag, parent){
return Array.prototype.slice.call((parent || document).getElementsByTagName(tag));
},
/*
* Creates an element, adds it to the DOM, and returns it.
*/
createElement: function(tag, parent){
var ele = document.createElement(tag);
parent.appendChild(ele);
return ele;
},
/*
* Removes an element from the DOM.
*/
removeElement: function(ele){
ele.parentNode.removeChild(ele);
},
/*
* Converts characters to their HTML entity form.
*/
escapeHTML: function(html){
return String(html).replace(entityRegex, s => entityMap[s]);
}
};
})();
| Fix HTML escaping in renderer crashing on non-string values | Fix HTML escaping in renderer crashing on non-string values
| JavaScript | mit | chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker |
9520ab1f9e7020879c8e3c2e8f6faad31fd572ef | Kwc/Shop/Box/Cart/Component.defer.js | Kwc/Shop/Box/Cart/Component.defer.js | var onReady = require('kwf/on-ready');
var $ = require('jQuery');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
onReady.onRender('.kwcClass',function(el) {
var url = getKwcRenderUrl();
$.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) {
$(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) {
$.ajax({
url: url,
data: { componentId: el.data('component-id') },
success: function(response) {
el.html(response);
onReady.callOnContentReady(el, {newRender: true});
}
});
}, el));
}, el));
}, { priority: 0 }); //call after Kwc.Form.Component
| var onReady = require('kwf/on-ready');
var $ = require('jQuery');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
onReady.onRender('.kwcClass',function(el) {
var url = getKwcRenderUrl();
$.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) {
$(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) {
$.ajax({
url: url,
data: { componentId: el.data('component-id') },
success: function(response) {
$('.kwcClass').html(response);
onReady.callOnContentReady(el, {newRender: true});
}
});
}, el));
}, el));
}, { priority: 0 }); //call after Kwc.Form.Component
| Fix wrong exchange of cartbox-domelement | Fix wrong exchange of cartbox-domelement
| JavaScript | bsd-2-clause | koala-framework/koala-framework,koala-framework/koala-framework |
b4dfceadd3a541cb13d5a69a4ef799dce1dc2037 | web/src/js/components/Dashboard/DashboardContainer.js | web/src/js/components/Dashboard/DashboardContainer.js | import graphql from 'babel-plugin-relay/macro'
import { createFragmentContainer } from 'react-relay'
import Dashboard from 'js/components/Dashboard/DashboardComponent'
export default createFragmentContainer(Dashboard, {
app: graphql`
fragment DashboardContainer_app on App {
campaign {
isLive
}
...UserMenuContainer_app
}
`,
user: graphql`
fragment DashboardContainer_user on User {
id
experimentActions {
referralNotification
searchIntro
}
joined
searches
tabs
...WidgetsContainer_user
...UserBackgroundImageContainer_user
...UserMenuContainer_user
...LogTabContainer_user
...LogRevenueContainer_user
...LogConsentDataContainer_user
...LogAccountCreationContainer_user
...NewUserTourContainer_user
...AssignExperimentGroupsContainer_user
}
`,
})
| import graphql from 'babel-plugin-relay/macro'
import { createFragmentContainer } from 'react-relay'
import Dashboard from 'js/components/Dashboard/DashboardComponent'
export default createFragmentContainer(Dashboard, {
app: graphql`
fragment DashboardContainer_app on App {
campaign {
isLive
numNewUsers # TODO: remove later. For testing Redis.
}
...UserMenuContainer_app
}
`,
user: graphql`
fragment DashboardContainer_user on User {
id
experimentActions {
referralNotification
searchIntro
}
joined
searches
tabs
...WidgetsContainer_user
...UserBackgroundImageContainer_user
...UserMenuContainer_user
...LogTabContainer_user
...LogRevenueContainer_user
...LogConsentDataContainer_user
...LogAccountCreationContainer_user
...NewUserTourContainer_user
...AssignExperimentGroupsContainer_user
}
`,
})
| Add data fetching for testing out Redis | Add data fetching for testing out Redis
| JavaScript | mpl-2.0 | gladly-team/tab,gladly-team/tab,gladly-team/tab |
25376ac4975c5d5021b40438f8954a6faa24e21d | lib/config.js | lib/config.js | var Fs = require('fs');
var config = module.exports = {};
// Configuring TLS
config.tls = {
key: Fs.readFileSync('./lib/certs/key.key'),
cert: Fs.readFileSync('./lib/certs/cert.crt'),
// Only necessary if using the client certificate authentication.
requestCert: true,
// Only necessary only if client is using the self-signed certificate.
ca: []
};
config.crumb = {
cookieOptions: { isSecure: true },
autoGenerate: true
};
config.monitor = {
opsInterval: 1000,
reporters: [{
reporter: require('good-console'),
events: { log: '*', response: '*' }
}, {
reporter: require('good-file'),
events: { ops: '*' },
config: './test/fixtures/monitor_log'
}, {
reporter: 'good-http',
events: { ops: '*', log: '*', response: '*' },
config: {
endpoint: 'http://localhost:3000',
wreck: {
headers: { 'x-api-key': 12345 }
}
}
}]
};
| var Fs = require('fs');
var config = module.exports = {};
// Configuring TLS
config.tls = {
key: Fs.readFileSync('./lib/certs/key.key'),
cert: Fs.readFileSync('./lib/certs/cert.crt'),
// Only necessary if using the client certificate authentication.
requestCert: true,
// Only necessary only if client is using the self-signed certificate.
ca: []
};
config.crumb = {
cookieOptions: { isSecure: true },
autoGenerate: true
};
config.monitor = {
opsInterval: 1000,
reporters: [{
reporter: require('good-console'),
events: { log: '*', response: '*' }
}, {
reporter: require('good-file'),
events: { ops: '*' },
config: './test/fixtures/monitor_log'
}]
};
// @Example of logging to a remote server.
// config.monitor = {
// opsInterval: 1000,
// reporters: [{
// reporter: require('good-console'),
// events: { log: '*', response: '*' }
// }, {
// reporter: require('good-file'),
// events: { ops: '*' },
// config: './test/fixtures/monitor_log'
// }, {
// reporter: 'good-http',
// events: { ops: '*', log: '*', response: '*' },
// config: {
// endpoint: 'http://localhost:3000',
// wreck: {
// headers: { 'x-api-key': 12345 }
// }
// }
// }]
// };
| Refactor good stop sending logs to remote server | Refactor good stop sending logs to remote server
Comments in lib/config.js still show how to send
logs to remote server. But, it is not used.
| JavaScript | bsd-3-clause | jd73/university,jd73/university |
fa1c80fabddcf07bc6a81f581b36a3a26578fc02 | src/js/app/main.js | src/js/app/main.js | /**
* Load all the Views.
*/
require([
'models/user',
'controllers/home',
'outer'
], function (User, Home, Router) {
var users = [new User('Barney'),
new User('Cartman'),
new User('Sheldon')];
localStorage.users = JSON.stringify(users);
Home.start();
Router.startRouting();
});
| /**
* Load all the Views.
*/
require([
'models/user',
'controllers/home',
'router'
], function (User, Home, Router) {
var users = [new User('Barney'),
new User('Cartman'),
new User('Sheldon')];
localStorage.users = JSON.stringify(users);
Home.start();
Router.startRouting();
});
| Rename router file part iii. | Rename router file part iii.
| JavaScript | mit | quantumtom/rainbow-dash,quantumtom/rainbow-dash,quantumtom/ash,quantumtom/ash |
2b261f89e9820a4697e0a812defaec05385fad51 | test/spec/controllers/main.js | test/spec/controllers/main.js | 'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('quakeStatsApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
| 'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('quakeStatsApp'));
var MainCtrl,
scope,
mockStats = {
gamesStats: []
};
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Constants: {},
stats: mockStats
});
}));
it('should attach a list of games to the scope', function () {
expect(scope.games).toBeDefined();
});
});
| Make the first dummy test pass | Tests: Make the first dummy test pass
| JavaScript | mit | mbarzeev/quake-stats,mbarzeev/quake-stats |
d111e99ba98e357e1f13eb8b8e83da5e188b9d0a | lib/readTemplate.js | lib/readTemplate.js | 'use strict';
const fs = require('fs');
const Promise = require('bluebird');
const readFile = Promise.promisify(fs.readFile, { context: fs });
const cache = require('./cache');
module.exports = readTemplate;
function readTemplate(path, callback) {
const cacheKey = `template.${path}`;
if (process.env.NODE_ENV === 'production') {
return cache.get(cacheKey)
.catch((err) => {
return readFile(path)
.then((buf) => buf.toString())
.then((value) => cache.put(cacheKey, value, { ttl: 0 }));
})
.asCallback(callback);
} else {
return readFile(path)
.then((buf) => buf.toString())
.asCallback(callback);
}
};
| 'use strict';
const fs = require('fs');
const Promise = require('bluebird');
const readFile = Promise.promisify(fs.readFile, { context: fs });
const cache = require('./cache');
module.exports = readTemplate;
function readTemplate(path, callback) {
const cacheKey = `template.${path}`;
return cache.get(cacheKey)
.catch((err) => {
return readFile(path)
.then((buf) => buf.toString())
.then((value) => cache.put(cacheKey, value, { ttl: 0 }));
})
.asCallback(callback);
};
| Revert "only cache templates in production" | Revert "only cache templates in production"
This reverts commit 4e2bf7d48d60bba8b4d4497786e4db0ab8f81bef.
| JavaScript | apache-2.0 | carsdotcom/windshieldjs,carsdotcom/windshieldjs |
62624f36608eb495e18050fdff395b39bd69fd22 | app/assets/javascripts/spree/checkout/payment/adyen_encrypted_credit_card.js | app/assets/javascripts/spree/checkout/payment/adyen_encrypted_credit_card.js | Spree.createEncryptedAdyenForm = function(paymentMethodId) {
document.addEventListener("DOMContentLoaded", function() {
var checkout_form = document.getElementById("checkout_form_payment")
// See adyen.encrypt.simple.html for details on the options to use
var options = {
name: "payment_source[" + paymentMethodId + "][encrypted_credit_card_data]",
enableValidations : true,
// If there's other payment methods, they need to be able to submit
submitButtonAlwaysEnabled: true,
disabledValidClass: true
};
// Create the form.
// Note that the method is on the Adyen object, not the adyen.encrypt object.
return adyen.createEncryptedForm(checkout_form, options);
});
}
| Spree.createEncryptedAdyenForm = function(paymentMethodId) {
document.addEventListener("DOMContentLoaded", function() {
var checkout_form = document.getElementById("checkout_form_payment")
// See adyen.encrypt.simple.html for details on the options to use
var options = {
name: "payment_source[" + paymentMethodId + "][encrypted_credit_card_data]",
enableValidations : true,
// If there's other payment methods, they need to be able to submit
submitButtonAlwaysEnabled: false,
disabledValidClass: true
};
// Create the form.
// Note that the method is on the Adyen object, not the adyen.encrypt object.
return adyen.createEncryptedForm(checkout_form, options);
});
}
| Enable validations on CC form | Enable validations on CC form
| JavaScript | mit | freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen,StemboltHQ/solidus-adyen,freerunningtech/solidus-adyen |
25ecb5e4f4bfeac33198913ec49bdb8b2412f462 | MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js | MovieFinder/src/main/webapp/public/src/controllers/nav-controller.js | //
// nav-controller.js
// Contains the controller for the nav-bar.
//
(function () {
'use strict';
angular.module('movieFinder.controllers')
.controller('NavCtrl', function ($scope, $modal, user) {
var _this = this;
var signInModal;
this.error = {
signIn: ''
};
this.showSignInModal = function () {
signInModal = $modal({
scope: $scope,
template: 'partials/modals/sign-in.html',
container: 'body'
});
};
this.login = function (username, password) {
user.login(username, password).success(function(){
signInModal.$promise.then(signInModal.hide);
}).error(function(){
_this.error.signIn = 'Some error message';
});
};
this.logout = function() {
user.logout();
};
});
})(); | //
// nav-controller.js
// Contains the controller for the nav-bar.
//
(function () {
'use strict';
angular.module('movieFinder.controllers')
.controller('NavCtrl', function ($scope, $modal, user) {
var _this = this;
var signInModal;
this.error = {
signIn: ''
};
this.showSignInModal = function () {
this.error.signIn = '';
signInModal = $modal({
scope: $scope,
template: 'partials/modals/sign-in.html',
container: 'body'
});
};
this.login = function (username, password) {
user.login(username, password).success(function(){
signInModal.$promise.then(signInModal.hide);
}).error(function(){
_this.error.signIn = 'Some error message';
});
};
this.logout = function() {
user.logout();
};
});
})(); | Reset error message when dialog re-opened. | Reset error message when dialog re-opened.
| JavaScript | mit | we4sz/DAT076,we4sz/DAT076 |
633dd358d078e50503406f15f8b46b8ba9fce951 | src/modules/sound.js | src/modules/sound.js | let lastPachiIndex = -1
let lastCaptureIndex = -1
let captureSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/capture${x}.mp3`))
let pachiSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/${x}.mp3`))
let newGameSound = new Audio('./data/newgame.mp3')
let passSound = new Audio('./data/pass.mp3')
exports.playPachi = function(delay = 0) {
let index = lastPachiIndex
while (index === lastPachiIndex) {
index = Math.floor(Math.random() * pachiSounds.length)
}
lastPachiIndex = index
setTimeout(() => pachiSounds[index].play(), delay)
}
exports.playCapture = function(delay = 0) {
let index = lastCaptureIndex
while (index === lastCaptureIndex) {
index = Math.floor(Math.random() * captureSounds.length)
}
lastCaptureIndex = index
setTimeout(() => captureSounds[index].play(), delay)
}
exports.playPass = function(delay = 0) {
setTimeout(() => passSound.play(), delay)
}
exports.playNewGame = function(delay = 0) {
setTimeout(() => newGameSound.play(), delay)
}
| const helper = require('./helper')
let lastPachiIndex = -1
let lastCaptureIndex = -1
let captureSounds = [...Array(5)].map((_, i) => new Audio(`./data/capture${i}.mp3`))
let pachiSounds = [...Array(5)].map((_, i) => new Audio(`./data/${i}.mp3`))
let newGameSound = new Audio('./data/newgame.mp3')
let passSound = new Audio('./data/pass.mp3')
exports.playPachi = function(delay = 0) {
let index = lastPachiIndex
while (index === lastPachiIndex) {
index = Math.floor(Math.random() * pachiSounds.length)
}
lastPachiIndex = index
setTimeout(() => pachiSounds[index].play().catch(helper.noop), delay)
}
exports.playCapture = function(delay = 0) {
let index = lastCaptureIndex
while (index === lastCaptureIndex) {
index = Math.floor(Math.random() * captureSounds.length)
}
lastCaptureIndex = index
setTimeout(() => captureSounds[index].play().catch(helper.noop), delay)
}
exports.playPass = function(delay = 0) {
setTimeout(() => passSound.play().catch(helper.noop), delay)
}
exports.playNewGame = function(delay = 0) {
setTimeout(() => newGameSound.play().catch(helper.noop), delay)
}
| Fix weird error messages about play() and pause() | Fix weird error messages about play() and pause()
| JavaScript | mit | yishn/Sabaki,yishn/Goban,yishn/Goban,yishn/Sabaki |
c1a1f8f3ddf1485016c3d70c2ceca66be42608f3 | src/server.js | src/server.js | var express = require('express');
var app = express();
app.use('/game', express.static(__dirname + '/public'));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Node app is up and running to serve static HTML content.');
}); | var express = require('express');
var app = express();
app.use('/app', express.static(__dirname + '/public'));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Node app is up and running to serve static HTML content.');
}); | Fix that URL--we just have to update Kibana. | Fix that URL--we just have to update Kibana. | JavaScript | apache-2.0 | gameontext/gameon-webapp,gameontext/gameon-webapp,gameontext/gameon-webapp |
87407f3dbd25b823d05f2f5b03475a7ecc391438 | lib/geoloc.js | lib/geoloc.js | var geoip = require('geoip');
function Point(latitude, longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
module.exports = {
/*
* Returns geoloc Point from the requester's ip adress
* @throws Exception
*/
getPointfromIp: function(ip, geoliteConfig) {
var latitude, longitude;
var city = new geoip.City(geoliteConfig.geolitepath);
var geo = city.lookupSync(ip);
if (!geo) {
return null;
}
longitude = geo.longitude;
latitude = geo.latitude;
return new Point(latitude, longitude);
},
getCityFromIp : function (ip, geoliteConfig) {
var city = new geoip.City(geoliteConfig.geolitepath);
return city.lookupSync(ip);
}
};
| var geoip = require('geoip');
function Point(latitude, longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
module.exports = {
/*
* Returns geoloc Point from the requester's ip adress
* @throws Exception
*/
getPointfromIp: function(ip, geolitePath) {
var latitude, longitude;
var city = new geoip.City(geolitePath);
var geo = city.lookupSync(ip);
if (!geo) {
return null;
}
longitude = geo.longitude;
latitude = geo.latitude;
return new Point(latitude, longitude);
},
getCityFromIp : function (ip, geolitePath) {
var city = new geoip.City(geolitePath);
return city.lookupSync(ip);
}
};
| Change getPointFromIp & getCityFromIp methods signature | Change getPointFromIp & getCityFromIp methods signature | JavaScript | mit | Jumplead/GeonamesServer,Jumplead/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,xjewer/GeonamesServer,Jumplead/GeonamesServer,Jumplead/GeonamesServer |
152c0faec45c4b754b3496a37de0884df11eb5bb | isProduction.js | isProduction.js | if (process && process.env && process.env.NODE_ENV === 'production') {
console.warn([
'You are running Mimic in production mode,',
'in most cases you only want to run Mimic in development environments.\r\n',
'For more information on how to load Mimic in development environments only please see:',
'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments'
].join(' '));
}
| if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'production') {
console.warn([
'You are running Mimic in production mode,',
'in most cases you only want to run Mimic in development environments.\r\n',
'For more information on how to load Mimic in development environments only please see:',
'https://github.com/500tech/mimic#loading-mimic-only-in-development-environments'
].join(' '));
}
| Fix a bug where checking process.env.NODE_ENV was not safe enough | fix(bootstrapping): Fix a bug where checking process.env.NODE_ENV was not safe enough
the check for process variable existence threw an error in some build systems which do not take care
of the process global variable such as angular cli.
| JavaScript | mit | 500tech/bdsm,500tech/mimic,500tech/mimic,500tech/bdsm |
7a2e50e7634ead72e8301fb99da246f20e92c961 | libs/connections.js | libs/connections.js | //Get required modules
var Connection = require( 'ssh2' );
var domain = require( 'domain' );
//Add my libs
var handlers = require( './handlers.js' );
//Auxiliary function to initialize/re-initialize ssh connection
function initializeConnection() {
//Initialize the ssh connection
connection = new Connection(),
handler = domain.create();
//Handling "error" event inside domain handler.
handler.add(connection);
//Add global connection handlers
handlers.setGlobalConnectionHandlers();
//Start connection
connection.connect(OptionsForSFTP);
}
function resetConnection() {
//Mark inactive connection
active_connection = false;
//Start connection
connection.connect(OptionsForSFTP);
}
//Expose handlers public API
module.exports = {
initializeConnection: initializeConnection,
resetConnection: resetConnection
};
| //Get required modules
var Connection = require( 'ssh2' );
var domain = require( 'domain' );
//Auxiliary function to initialize/re-initialize ssh connection
function initializeConnection() {
//Add my libs
var handlers = require( './handlers.js' );
//Initialize the ssh connection
connection = new Connection(),
handler = domain.create();
//Handling "error" event inside domain handler.
handler.add(connection);
//Add global connection handlers
handlers.setGlobalConnectionHandlers();
//Start connection
connection.connect(OptionsForSFTP);
}
function resetConnection() {
//Mark inactive connection
active_connection = false;
//Start connection
connection.connect(OptionsForSFTP);
}
//Expose handlers public API
module.exports = {
resetConnection: resetConnection,
initializeConnection: initializeConnection
};
| Fix module require chicken-egg problem | Fix module require chicken-egg problem
| JavaScript | mit | ctimoteo/syncmaster |
9bbcea12f0db82cf583d9fcc42998b2b79ef4372 | lib/parser.js | lib/parser.js | 'use babel';
export default class Parser {
source: null
editor: null
parse(source, editor) {
this.source = source;
this.editor = editor;
return this.scan();
}
scan() {
let result = [], count = 0;
// Find 'describes', set indexs, find 'it'
this.findInstanceOf('describe(\'', result, 0, this.source.length);
this.getEndIndex(result);
result.map((obj) => obj.children = []);
result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex));
return result;
}
findInstanceOf(word, result, startIndex, endIndex) {
let index = startIndex, wordLength = word.length, name, position;
while (index != -1 && index < endIndex) {
index++;
index = this.source.indexOf(word, index);
if (index == -1 || index > endIndex) break;
name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1));
position = this.editor.buffer.positionForCharacterIndex(index);
result.push({index, name, position});
}
}
getEndIndex(arr){
arr.map((obj, index, arr) => {
if (arr[index + 1]) {
obj.endIndex = arr[index + 1]['index'];
}
else {
obj.endIndex = this.source.length;
}
});
}
}
| 'use babel';
export default class Parser {
source: null
editor: null
parse(source, editor) {
this.source = source;
this.editor = editor;
return this.scan();
}
scan() {
let result = [], count = 0;
// Find 'describes', set indexs, find 'it'
this.findInstanceOf('describe(\'', result, 0, this.source.length);
this.getEndIndex(result);
result.map((obj) => obj.children = []);
result.map((obj) => this.findInstanceOf('it(\'', obj.children, obj.index, obj.endIndex));
return result;
}
findInstanceOf(word, result, startIndex, endIndex) {
let index = startIndex, wordLength = word.length, name, position;
while (index != -1 && index < endIndex) {
index++;
index = this.source.indexOf(word, index);
if (index == -1 || index > endIndex) break;
name = this.source.substring(index + wordLength, this.source.indexOf('\'', index + wordLength + 1));
position = this.editor.buffer.positionForCharacterIndex(index);
result.push({index, name, position, expanded: true,});
}
}
getEndIndex(arr){
arr.map((obj, index, arr) => {
if (arr[index + 1]) {
obj.endIndex = arr[index + 1]['index'];
}
else {
obj.endIndex = this.source.length;
}
});
}
}
| Expand the tree view by defualt | Expand the tree view by defualt
| JavaScript | mit | chiragchoudhary66/test-list-maker |
9413f0cb3b4bd6545d29e79e9b656469b209a417 | jquery.linkem.js | jquery.linkem.js | // jquery.linkem.js
// Copyright Michael Hanson
// https://github.com/mybuddymichael/jquery-linkem
(function( $ ) {
$.fn.linkem = function() {
var linked = this;
this.on( "keydown keyup mousedown mouseup", function() {
linked.text( $(this).val() );
});
};
return this;
})( jQuery );
| // jquery.linkem.js
// Copyright Michael Hanson
// https://github.com/mybuddymichael/jquery-linkem
(function( $ ) {
$.fn.linkem = function() {
var linked = this;
this.on( "input change", function() {
linked.text( $(this).val() );
});
};
return this;
})( jQuery );
| Change events to "input" and "change" | Change events to "input" and "change"
| JavaScript | mit | mybuddymichael/jquery-linkem |
47b311db68aa5343f66e3f5a5fd77602bd3e2e9e | server/models/products.js | server/models/products.js | // npm dependencies
const mongoose = require('mongoose');
// defines Product model
// contains 3 fields (title, description, and price)
let Product = mongoose.model('Product', {
title: {
type: String,
required: true,
minlength: 5,
trim: true
},
description: {
type: String,
required: true,
minlength: 10,
trim: true
},
price: {
type: Number,
default: null
}
});
module.exports = {
Product
}
| // npm dependencies
const mongoose = require('mongoose');
// defines Product model
// contains 3 fields (title, description, and price)
let Product = mongoose.model('Product', {
title: {
type: String,
required: true,
minlength: 5,
trim: true
},
description: {
type: String,
minlength: 10,
trim: true
},
price: {
type: Number,
default: null
}
});
module.exports = {
Product
}
| Remove 'required' validation from 'description' field | Remove 'required' validation from 'description' field
| JavaScript | mit | dshaps10/full-stack-demo-site,dshaps10/full-stack-demo-site |
8e54f1bd3f215ada478b6fb41644bcb777b29ab2 | js/app/viewer.js | js/app/viewer.js | /*jslint browser: true, white: true, plusplus: true */
/*global angular, console, alert*/
(function () {
'use strict';
var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']);
app.controller("StatusController", function($scope, $http) {
$scope.serverName = app.serverName;
var request = app.api + "search/tickets?unresolved=1";
$http.get( request )
.success(function(data, status, header, config) {
$scope.apiLoaded = true;
$scope.ticketsCount = data.length;
if ($scope.ticketsCount > 0) {
$scope.tickets = data;
}
})
.error(function(data, status, header, config) {
$scope.apiLoaded = false;
console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?closedBy=0");
});
});
}());
| /*jslint browser: true, white: true, plusplus: true */
/*global angular, console, alert*/
(function () {
'use strict';
var app = angular.module('status', ['ui.bootstrap', 'chieffancypants.loadingBar', 'tableSort']);
app.controller("StatusController", function($scope, $http) {
$scope.serverName = app.serverName;
var request = app.api + "search/tickets?unresolved=1";
$http.get( request )
.success(function(data, status, header, config) {
$scope.apiLoaded = true;
$scope.ticketsCount = data.length;
if ($scope.ticketsCount > 0) {
$scope.tickets = data;
}
})
.error(function(data, status, header, config) {
$scope.apiLoaded = false;
console.log("Error while retrieving tickets, API request failed: " + app.api + "search/tickets?unresolved=1");
});
});
}());
| Update console log error text | Update console log error text
| JavaScript | agpl-3.0 | ShinDarth/TC-Ticket-Web-Viewer,ShinDarth/TC-Ticket-Web-Viewer |
e8b81efc0799f24d099ac7073da35a4ece27d615 | desktop/webpack.main.config.js | desktop/webpack.main.config.js | const plugins = require('./webpack.plugins')
const webpack = require('webpack')
module.exports = {
/**
* This is the main entry point for your application, it's the first file
* that runs in the main process.
*/
entry: './src/index.ts',
plugins: [
...plugins,
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV ?? 'development'
),
'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN),
'process.type': '"browser"',
}),
],
module: {
rules: [
// Add support for native node modules
// TODO: Investigate. Seems to cause issues, and things seem to work without this loader
// {
// test: /\.node$/,
// use: 'node-loader',
// },
{
test: /\.(m?js|node)$/,
parser: { amd: false },
use: {
loader: '@marshallofsound/webpack-asset-relocator-loader',
options: {
outputAssetBase: 'native_modules',
debugLog: true,
},
},
},
{
test: /\.tsx?$/,
exclude: /(node_modules|\.webpack)/,
use: {
loader: 'ts-loader',
options: {
configFile: 'tsconfig.main.json',
transpileOnly: true,
},
},
},
],
},
resolve: {
extensions: ['.js', '.mjs', '.ts', '.json'],
},
}
| const plugins = require('./webpack.plugins')
const webpack = require('webpack')
module.exports = {
/**
* This is the main entry point for your application, it's the first file
* that runs in the main process.
*/
entry: './src/index.ts',
plugins: [
...plugins,
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV ?? 'development'
),
'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN),
'process.type': '"browser"',
}),
],
module: {
rules: [
// Add support for native node modules
{
test: /native_modules\/.+\.node$/,
use: 'node-loader',
},
{
test: /\.(m?js|node)$/,
parser: { amd: false },
use: {
loader: '@marshallofsound/webpack-asset-relocator-loader',
options: {
outputAssetBase: 'native_modules',
debugLog: true,
},
},
},
{
test: /\.tsx?$/,
exclude: /(node_modules|\.webpack)/,
use: {
loader: 'ts-loader',
options: {
configFile: 'tsconfig.main.json',
transpileOnly: true,
},
},
},
],
},
resolve: {
extensions: ['.js', '.mjs', '.ts', '.json'],
},
}
| Fix resolution of native Node modules | chore(Desktop): Fix resolution of native Node modules
See https://github.com/electron-userland/electron-forge/pull/2449
| JavaScript | apache-2.0 | stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila,stencila/stencila |
a966513e6677626454f550bd81cd50efce79c86f | src/unix_stream.js | src/unix_stream.js | var util = require('util');
var Socket = require('net').Socket;
/* Make sure we choose the correct build directory */
var directory = process.config.default_configuration === 'Debug' ? 'Debug' : 'Release';
var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node');
var SOCK_STREAM = bindings.SOCK_STREAM;
var AF_UNIX = bindings.AF_UNIX;
var bind = bindings.bind;
var socket = bindings.socket;
function errnoException(errorno, syscall) {
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
exports.createSocket = function(local_path) {
var fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1)
throw errnoException(errno, 'socket');
var s = new Socket(fd);
if (local_path) {
if (bind(fd, local_path) == -1) {
process.nextTick(function() {
s.emit('error', errnoException(errno, 'bind'));
});
}
s.local_path = local_path;
}
return s;
};
| var util = require('util');
var Socket = require('net').Socket;
/* Make sure we choose the correct build directory */
var directory = process.config.target_defaults.default_configuration === 'Debug' ? 'Debug' : 'Release';
var bindings = require(__dirname + '/../build/' + directory + '/unix_stream.node');
var SOCK_STREAM = bindings.SOCK_STREAM;
var AF_UNIX = bindings.AF_UNIX;
var bind = bindings.bind;
var socket = bindings.socket;
function errnoException(errorno, syscall) {
var e = new Error(syscall + ' ' + errorno);
e.errno = e.code = errorno;
e.syscall = syscall;
return e;
}
exports.createSocket = function(local_path) {
var fd;
if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) === -1)
throw errnoException(errno, 'socket');
var s = new Socket(fd);
if (local_path) {
if (bind(fd, local_path) == -1) {
process.nextTick(function() {
s.emit('error', errnoException(errno, 'bind'));
});
}
s.local_path = local_path;
}
return s;
};
| Use the correct process.config variable | Use the correct process.config variable
| JavaScript | isc | santigimeno/node-unix-stream,santigimeno/node-unix-stream,santigimeno/node-unix-stream |
74386ac41257a7ea865aefd09631ff87815c23a5 | src/components/App/index.js | src/components/App/index.js | import React, { Component } from 'react';
/* global styles for app */
import './styles/app.scss';
/* application components */
import { Header } from '../../components/Header';
import { Footer } from '../../components/Footer';
export class App extends Component {
static propTypes = {
children: React.PropTypes.any,
};
render() {
return (
<section>
<Header />
<main className="container">
{this.props.children}
</main>
<Footer />
</section>
);
}
}
| import React, { Component } from 'react';
/* global styles for app */
import './styles/app.scss';
/* application components */
import { Header } from '../../components/Header';
import { Footer } from '../../components/Footer';
export class App extends Component {
static propTypes = {
children: React.PropTypes.any,
};
render() {
return (
<section>
<Header />
<main>
<div className="container">
{this.props.children}
</div>
</main>
<Footer />
</section>
);
}
}
| Change markup so that main el is outside of container, can take a full width bg color | Change markup so that main el is outside of container, can take a full width bg color
| JavaScript | mit | dramich/Chatson,badT/twitchBot,badT/Chatson,badT/twitchBot,dramich/Chatson,dramich/twitchBot,TerryCapan/twitchBot,TerryCapan/twitchBot,dramich/twitchBot,badT/Chatson |
ada006bbcee7e855f9ee44acbd777928a0c58d1b | addon/initializers/mutation-observer.js | addon/initializers/mutation-observer.js | /**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
const config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | /**
* Simple initializer that implements the mutationObserverMixin
* in all the Components. It uses a flag defined in the app
* environment for it.
*/
import Ember from 'ember';
import mutationObserver from '../mixins/mutation-observer';
export function initialize(app) {
let config;
try {
// Ember 2.15+
config = app.resolveRegistration('config:environment');
} catch (e) {
// Older Ember approach
config = app.lookupFactory ?
app.lookupFactory('config:environment') :
app.__container__.lookupFactory('config:environment');
}
if (!config || !config.mutationObserverInjection) {return;}
Ember.Component.reopen(mutationObserver);
}
export default {
name: 'mutation-observer',
initialize: initialize
}; | Fix initializer for Ember 2.15+ | Fix initializer for Ember 2.15+
| JavaScript | mit | zzarcon/ember-cli-Mutation-Observer,zzarcon/ember-cli-Mutation-Observer |
1f13a1254fbf5303a58bf75b14b160e11d7dd30e | src/components/Lotteries.js | src/components/Lotteries.js | /**
* Created by mgab on 14/05/2017.
*/
import React,{ Component } from 'react'
import Title from './common/styled-components/Title'
import Lottery from './Lottery'
export default class Lotteries extends Component {
render() {
const lotteries = []
this.props.lotteriesData.forEach((entry) => {
lotteries.push(<Lottery name={entry.id}
jackpot={entry.jackpots[0].jackpot}
drawingDate={entry.drawingDate}
key={entry.id} />)
})
return (
<div>
<Title>Lotteries</Title>
<div>
{lotteries}
</div>
</div>
)
}
} | /**
* Created by mgab on 14/05/2017.
*/
import React,{ Component } from 'react'
import Title from './common/styled-components/Title'
import Lottery from './Lottery'
export default class Lotteries extends Component {
render() {
const lotteries = []
if (this.props.lotteriesData) {
this.props.lotteriesData.forEach((entry) => {
lotteries.push(<Lottery name={entry.id}
jackpot={entry.jackpots[0].jackpot}
drawingDate={entry.drawingDate}
key={entry.id} />)
})
}
return (
<div>
<Title>Lotteries</Title>
<div>
{lotteries}
</div>
</div>
)
}
} | Check for lotteries data before trying to process them. | Check for lotteries data before trying to process them.
| JavaScript | mit | mihailgaberov/lottoland-react-demo,mihailgaberov/lottoland-react-demo |
28c89588650841686f1c0c515360686a5ac0afd8 | src/middleware/authenticate.js | src/middleware/authenticate.js | import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var verifyHeader = ( !! config.header)
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
if (verifyHeader) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
| import handleAdapter from '../handleAdapter'
export default (config) => {
if ( ! config.enabled) return (req, res, next) => { next() }
var header = (config.header || 'Authorization').toLowerCase()
var tokenLength = 32
var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`)
return (req, res, next) => {
var err
req.auth = {}
if (header) {
var value = req.auth.header = req.headers[header]
if ( ! value) {
err = new Error(`Missing ${config.header} header.`)
err.statusCode = 401
return next(err)
}
if (config.byToken !== false) {
var token = value.replace(tokenRegExp, '$1')
if (token.length !== tokenLength) {
err = new Error('Invalid token.')
err.statusCode = 401
return next(err)
}
req.auth.token = token
}
}
handleAdapter(req, config, next, (err, user) => {
if (err) {
err = new Error(err)
err.statusCode = 401
return next(err)
}
req.user = user
next()
})
}
}
| Fix header not being validated if 'auth.header' option is not given. | Fix header not being validated if 'auth.header' option is not given.
In authenticate middleware.
| JavaScript | mit | kukua/concava |
fc9bdc4a183ea90c596603bdc5cdc62e2902c1ce | lib/Subheader.js | lib/Subheader.js | import { getColor } from './helpers';
import { StyleSheet, View, Text } from 'react-native';
import { TYPO, THEME_NAME } from './config';
import React, { Component, PropTypes } from 'react';
const styles = StyleSheet.create({
container: {
padding: 16
},
text: TYPO.paperFontBody1
});
export default class Subheader extends Component {
static propTypes = {
text: PropTypes.string.isRequired,
color: PropTypes.string,
inset: PropTypes.bool,
theme: PropTypes.oneOf(THEME_NAME),
lines: PropTypes.number
};
static defaultProps = {
color: 'rgba(0,0,0,.54)',
inset: false,
theme: 'light',
lines: 1
};
render() {
const { text, color, inset, lines } = this.props;
return (
<View
style={[styles.container, {
paddingLeft: inset ? 72 : 16
}]}
>
<Text
numberOfLines={lines}
style={[styles.text, {
color: getColor(color),
fontWeight: '500'
}]}
>
{text}
</Text>
</View>
);
}
}
| import { getColor } from './helpers';
import { StyleSheet, View, Text } from 'react-native';
import { TYPO, THEME_NAME } from './config';
import React, { Component, PropTypes } from 'react';
const styles = StyleSheet.create({
container: {
padding: 16
},
text: TYPO.paperFontBody1
});
export default class Subheader extends Component {
static propTypes = {
text: PropTypes.string.isRequired,
color: PropTypes.string,
inset: PropTypes.bool,
theme: PropTypes.oneOf(THEME_NAME),
lines: PropTypes.number,
style: PropTypes.object,
};
static defaultProps = {
color: 'rgba(0,0,0,.54)',
inset: false,
theme: 'light',
lines: 1
};
render() {
const { text, color, inset, lines, style } = this.props;
return (
<View
style={[styles.container, {
paddingLeft: inset ? 72 : 16
}, style]}
>
<Text
numberOfLines={lines}
style={[styles.text, {
color: getColor(color),
fontWeight: '500'
}]}
>
{text}
</Text>
</View>
);
}
}
| Add ability to set state of subheader | Add ability to set state of subheader
| JavaScript | mit | xotahal/react-native-material-ui,mobileDevNativeCross/react-native-material-ui,xvonabur/react-native-material-ui,blovato/sca-mobile-components,ajaxangular/react-native-material-ui,kenma9123/react-native-material-ui |
edbcdb75813fdd8149c147f0c7dc5138e06307e6 | test/unit/history/setLimit.test.js | test/unit/history/setLimit.test.js | import History from '../../../src/history'
describe('History::setLimit', function() {
const action = n => n
it('sets the correct size given Infinity', function() {
const history = new History()
history.setLimit(Infinity)
expect(history.limit).toEqual(Infinity)
})
it('sets the correct size given an integer', function() {
const history = new History()
history.setLimit(10)
expect(history.limit).toEqual(10)
})
it('sets the limit to 0 given a negative integer', function() {
const history = new History()
history.setLimit(-10)
expect(history.limit).toEqual(0)
})
})
| import History from '../../../src/history'
describe('History::setLimit', function() {
it('sets the correct size given Infinity', function() {
const history = new History()
history.setLimit(Infinity)
expect(history.limit).toEqual(Infinity)
})
it('sets the correct size given an integer', function() {
const history = new History()
history.setLimit(10)
expect(history.limit).toEqual(10)
})
it('sets the limit to 0 given a negative integer', function() {
const history = new History()
history.setLimit(-10)
expect(history.limit).toEqual(0)
})
})
| Remove unused variable that caused linter warning | Remove unused variable that caused linter warning
| JavaScript | mit | vigetlabs/microcosm,vigetlabs/microcosm,vigetlabs/microcosm |
2990ed3071a0969145e0a76beae6ad057e6e14f9 | subsystem/click.js | subsystem/click.js | phoxy._ClickHook =
{
_: {},
};
phoxy._ClickHook._.click =
{
InitClickHook: function()
{
document.querySelector('body').addEventListener('click', function(event)
{
var target = event.target;
while (true)
{
if (target === null)
return;
if (target.nodeName === 'A')
break; // only click on A is triggered
target = target.parentElement;
}
var url = target.getAttribute('href');
if (url === undefined || target.hasAttribute('not-phoxy'))
return;
if (phoxy._.click.OnClick(url, false))
return;
event.preventDefault()
}, true);
window.onpopstate = phoxy._.click.OnPopState;
}
,
OnClick: function (url, not_push)
{
if (url.indexOf('#') !== -1)
return true;
if (url[0] === '/')
url = url.substring(1);
phoxy.MenuCall(url);
return false;
}
,
OnPopState: function(e)
{
var path = e.target.location.pathname;
var hash = e.target.location.hash;
phoxy._.click.OnClick(path, true);
}
}; | phoxy._ClickHook =
{
_: {},
};
phoxy._ClickHook._.click =
{
InitClickHook: function()
{
document.querySelector('body').addEventListener('click', function(event)
{
var target = event.target;
while (true)
{
if (target === null)
return;
if (target.nodeName === 'A')
break; // only click on A is triggered
target = target.parentElement;
}
var url = target.getAttribute('href');
if (url === undefined || target.hasAttribute('not-phoxy'))
return;
if (phoxy._.click.OnClick(url, false))
return;
event.preventDefault()
}, true);
window.onpopstate = phoxy._.click.OnPopState;
}
,
OnClick: function (url, not_push)
{
if (url.indexOf('#') !== -1)
return true;
if (url[0] === '/')
url = url.substring(1);
if (not_push)
phoxy.ApiRequest(url);
else
phoxy.MenuCall(url);
return false;
}
,
OnPopState: function(e)
{
var path = e.target.location.pathname;
var hash = e.target.location.hash;
phoxy._.click.OnClick(path, true);
}
}; | Fix empty history issue, when we never could go back | Fix empty history issue, when we never could go back
| JavaScript | apache-2.0 | phoxy/phoxy,phoxy/phoxy |
675134d0bb49567fade2501538dc088b21cdab64 | StructureMaintainer.js | StructureMaintainer.js | module.exports = function() {
console.log("Maintaining Structures... " + Game.getUsedCpu());
var newCandidates = [],
links = [],
spawns = [];
Object.keys(Game.structures).forEach(function(structureId) {
structure = Game.structures[structureId];
if(structure.hits < (structure.hitsMax / 2)) {
newCandidates.push(structure);
}
if(structure.structureType === STRUCTURE_LINK) {
links.push(structure.id);
}
});
Memory.repairList.forEach(function (id) {
var structure = Game.getObjectById(id);
if(!structure || structure.hits >= structure.hitsMax*0.75) {
Memory.repairList.splice(Memory.repairList.indexOf(id), 1);
}
});
Memory.linkList = links;
Memory.spawnList = Game.spawns;
newCandidates.forEach(function (structure) {
if(Memory.repairList.indexOf(structure.id) === -1) {
Memory.repairList.push(structure.id);
}
});
console.log("Finished " + Game.getUsedCpu());
};
| module.exports = function() {
console.log("Maintaining Structures... " + Game.getUsedCpu());
var structures = Object.keys(Game.rooms).forEach(function (roomName) {
Game.rooms[roomName].find(FIND_STRUCTURES, {
filter: function (structure) {
return (structure.my === true || structure.structureType === "STRUCTURE_ROAD");
}
});
});
var newCandidates = [],
links = [],
spawns = [];
structures.forEach(function(structure) {
if(structure.hits < (structure.hitsMax / 2)) {
newCandidates.push(structure);
}
if(structure.structureType === STRUCTURE_LINK) {
links.push(structure.id);
}
});
Memory.repairList.forEach(function (id) {
var structure = Game.getObjectById(id);
if(!structure || structure.hits >= structure.hitsMax*0.75) {
Memory.repairList.splice(Memory.repairList.indexOf(id), 1);
}
});
Memory.linkList = links;
Memory.spawnList = Game.spawns;
newCandidates.forEach(function (structure) {
if(Memory.repairList.indexOf(structure.id) === -1) {
Memory.repairList.push(structure.id);
}
});
console.log("Finished " + Game.getUsedCpu());
};
| Make it so that the Structure Maintainer includes roads as well. | Make it so that the Structure Maintainer includes roads as well.
| JavaScript | mit | pmaidens/screeps,pmaidens/screeps |
e29974b1adcb91af1a65ac474fcb36d7a0e24098 | test/17_image/definitions.js | test/17_image/definitions.js | define(function () {
return [
{
"default": {
name: "TestForm",
label: "TestForm",
_elements: [
{
"default": {
name: "Name",
type: "text",
label: "Name"
}
},
{
"default": {
name: "Photo",
type: "file",
label: "Photo",
accept: "image/*"
}
},
{
"default": {
name: "Photo1",
type: "file",
label: "Photo1",
accept: "image/*"
}
},
{
"default": {
name: "Photo2",
type: "file",
label: "Photo2",
accept: "image/*"
}
},
{
'default': {
name: 'location',
label: 'Location',
type: 'location'
}
},
{
'default': {
name: 'draw',
label: 'Sign',
type: 'draw',
size: 'signature'
}
},
{
"default": {
name: "Rank",
type: "number",
label: "Rank"
}
},
{
"default": {
name: "Details",
type: "text",
label: "Details"
}
}
]
}
}
];
});
| define(function () {
return [
{
"default": {
name: "TestForm",
label: "TestForm",
_elements: [
{
"default": {
name: "Name",
type: "text",
label: "Name"
}
},
{
"default": {
name: "Photo",
type: "file",
label: "Photo",
accept: "image/*",
capture: true
}
},
{
"default": {
name: "Photo1",
type: "file",
label: "Photo1",
accept: "image/*",
capture: false
}
},
{
"default": {
name: "Photo2",
type: "file",
label: "Photo2",
accept: "image/*",
capture: true
}
},
{
'default': {
name: 'location',
label: 'Location',
type: 'location'
}
},
{
'default': {
name: 'draw',
label: 'Sign',
type: 'draw',
size: 'signature'
}
},
{
"default": {
name: "Rank",
type: "number",
label: "Rank"
}
},
{
"default": {
name: "Details",
type: "text",
label: "Details"
}
}
]
}
}
];
});
| Update form definition in tests to demonstrate functionality | Update form definition in tests to demonstrate functionality
| JavaScript | bsd-3-clause | blinkmobile/forms,blinkmobile/forms |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.