commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
94f8f130f60802a04d81c15b2b4c2766ca48e588 | src/vibrant.service.js | src/vibrant.service.js | angular
.module('ngVibrant')
.provider('$vibrant', $vibrantProvider);
function $vibrantProvider() {
this.$get = function() {
function $vibrant(element) {
var instance = new Vibrant(element);
return instance.swatches();
}
};
}
| angular
.module('ngVibrant')
.provider('$vibrant', $vibrantProvider);
function $vibrantProvider() {
this.$get = function() {
function $vibrant(element) {
var instance = new Vibrant(element);
var swatches = instance.swatches();
var rgb = {};
Object.getOwnPropertyNames(swatches).forEach(function(swatch) {
if (angular.isDefined(swatches[swatch])) {
rgb[swatch] = swatches[swatch].rgb;
}
});
return rgb;
}
};
}
| Return only rgb swatches (gonna add a toggle for this later) | Return only rgb swatches (gonna add a toggle for this later)
| JavaScript | apache-2.0 | maxjoehnk/ngVibrant |
9c0c159b1184d5322f1baf0fa530efaf45cd5e3c | app/assets/javascripts/angular/main/login-controller.js | app/assets/javascripts/angular/main/login-controller.js | (function(){
'use strict';
angular
.module('secondLead')
.controller('LoginCtrl', [
'Restangular',
'$state',
'store',
'UserModel',
function (Restangular, $state, store, UserModel) {
var login = this;
login.user = {};
login.onSubmit = function() {
UserModel.login(login.user)
.then(function (response) {
var user = response.data.user;
$state.go('user.lists', {userID: user.id});
login.reset();
}, function(error){
login.error = "Invalid username/password";
}
);
}
login.reset = function () {
login.user = {};
};
}])
})(); | (function(){
'use strict';
angular
.module('secondLead')
.controller('LoginCtrl', [
'Restangular',
'$state',
'store',
'UserModel',
function (Restangular, $state, store, UserModel) {
var login = this;
login.user = {};
login.onSubmit = function() {
UserModel.login(login.user)
.then(function (response) {
var user = response.data.user;
UserModel.setLoggedIn(true);
$state.go('user.lists', {userID: user.id});
login.reset();
}, function(error){
login.error = "Invalid username/password";
}
);
}
login.reset = function () {
login.user = {};
};
}])
})(); | Add update to usermodel upon login with login controller | Add update to usermodel upon login with login controller
| JavaScript | mit | ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead |
72267372d27463883af3dd2bff775e8199948770 | VIE/test/rdfa.js | VIE/test/rdfa.js | var jQuery = require('jquery');
var VIE = require('../vie.js');
// Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed
VIE.RDFa.predicateSelector = '[property]';
exports['test inheriting subject'] = function(test) {
var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein<span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>');
var entities = VIE.RDFa.readEntities(html);
test.equal(entities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON");
var entities = VIE.RDFaEntities.getInstances(html);
test.equal(entities.length, 2, "This RDFa defines two entities but they don't get to Backbone");
test.done();
};
| var jQuery = require('jquery');
var VIE = require('../vie.js');
// Until https://github.com/tmpvar/jsdom/issues/issue/81 is fixed
VIE.RDFa.predicateSelector = '[property]';
exports['test inheriting subject'] = function(test) {
var html = jQuery('<div about="http://dbpedia.org/resource/Albert_Einstein"><span property="foaf:name">Albert Einstein</span><span property="dbp:dateOfBirth" datatype="xsd:date">1879-03-14</span><div rel="dbp:birthPlace" resource="http://dbpedia.org/resource/Germany" /><span about="http://dbpedia.org/resource/Germany" property="dbp:conventionalLongName">Federal Republic of Germany</span></div>');
var jsonldEntities = VIE.RDFa.readEntities(html);
test.equal(jsonldEntities.length, 2, "This RDFa defines two entities but they don't get parsed to JSON");
test.equal(jsonldEntities[1]['foaf:name'], 'Albert Einstein');
test.equal(jsonldEntities[0]['dbp:conventionalLongName'], 'Federal Republic of Germany');
var backboneEntities = VIE.RDFaEntities.getInstances(html);
test.equal(backboneEntities.length, 2, "This RDFa defines two entities but they don't get to Backbone");
test.equal(backboneEntities[1].get('foaf:name'), 'Albert Einstein');
test.equal(backboneEntities[0].get('dbp:conventionalLongName'), 'Federal Republic of Germany');
test.done();
};
| Test getting properties as well | Test getting properties as well
| JavaScript | mit | bergie/VIE,bergie/VIE |
e2e2ea04901ca320c33792245fdb80c33f04ec6b | app/js/controllers.js | app/js/controllers.js | var phonecatControllers = angular.module('leaguecontrollers', []);
phonecatControllers.factory("dataProvider", ['$q', function($q) {
console.log("Running dataProvider factory");
return {
getData: function() {
var result = bowling.initialize({"root": "testdata"}, $q);
return result;
}
}
}]).controller('LeagueController', ['$scope', '$route', 'dataProvider',
function ($scope, $route, dataProvider) {
console.log("Loaded league data");
dataProvider.getData().then(function(league) {
$scope.league = league;
});
}
]
);
| var phonecatControllers = angular.module('leaguecontrollers', []);
phonecatControllers.factory("dataProvider", ['$q', function($q) {
console.log("Running dataProvider factory");
var dataLoaded = false;
return {
getData: function() {
if (!dataLoaded) {
var result = bowling.initialize({"root": "testdata"}, $q);
return result.then(function (league) {
console.log("Data loaded marking flag");
dataLoaded = true;
return league;
});
} else {
return $q(function (resolve, reject) {
resolve(bowling.currentLeague);
});
}
}
}
}]).controller('LeagueController', ['$scope', '$route', 'dataProvider',
function ($scope, $route, dataProvider) {
console.log("Loaded league data");
dataProvider.getData().then(function(league) {
$scope.league = league;
});
}
]
);
| Add getData overrides for multiple views. | Add getData overrides for multiple views.
| JavaScript | mit | MeerkatLabs/bowling-visualization |
ef478f65b91a9948c33b446468b9c98861ad2686 | src/TextSuggest.js | src/TextSuggest.js | /**
* Created by XaviTorello on 30/05/18
*/
import React from 'react';
import ComposedComponent from './ComposedComponent';
import AutoComplete from 'material-ui/AutoComplete';
class TextSuggest extends React.Component {
render() {
// console.log('TextSuggest', this.props.form);
// assign the source list to autocomplete
const datasource = this.props.form.schema.enumNames || this.props.form.schema.enum || ['Loading...'];
// assign the filter, by default case insensitive
const filter = ((filter) => {
switch (filter) {
case 'fuzzy':
return AutoComplete.fuzzyFilter;
break;
default:
return AutoComplete.caseInsensitiveFilter;
break;
}
})(this.props.form.filter)
return (
<div className={this.props.form.htmlClass}>
<AutoComplete
type={this.props.form.type}
floatingLabelText={this.props.form.title}
hintText={this.props.form.placeholder}
errorText={this.props.error}
onChange={this.props.onChangeValidate}
defaultValue={this.props.value}
disabled={this.props.form.readonly}
style={this.props.form.style || {width: '100%'}}
dataSource={datasource}
filter={filter}
maxSearchResults={this.props.form.maxSearchResults || 5}
/>
</div>
);
}
}
export default ComposedComponent(TextSuggest);
| /**
* Created by XaviTorello on 30/05/18
*/
import React from 'react';
import ComposedComponent from './ComposedComponent';
import AutoComplete from 'material-ui/AutoComplete';
const dataSourceConfig = {
text: 'name',
value: 'value',
};
class TextSuggest extends React.Component {
render() {
// console.log('TextSuggest', this.props.form);
// assign the source list to autocomplete
const datasource = this.props.form.schema.enumNames || this.props.form.schema.enum || ['Loading...'];
// assign the filter, by default case insensitive
const filter = ((filter) => {
switch (filter) {
case 'fuzzy':
return AutoComplete.fuzzyFilter;
break;
default:
return AutoComplete.caseInsensitiveFilter;
break;
}
})(this.props.form.filter)
return (
<div className={this.props.form.htmlClass}>
<AutoComplete
type={this.props.form.type}
floatingLabelText={this.props.form.title}
hintText={this.props.form.placeholder}
errorText={this.props.error}
onChange={this.props.onChangeValidate}
defaultValue={this.props.value}
disabled={this.props.form.readonly}
style={this.props.form.style || {width: '100%'}}
dataSource={datasource}
filter={filter}
maxSearchResults={this.props.form.maxSearchResults || 5}
/>
</div>
);
}
}
export default ComposedComponent(TextSuggest);
| Add dataSourceConfig to link passed datasource keys | Add dataSourceConfig to link passed datasource keys
| JavaScript | mit | networknt/react-schema-form,networknt/react-schema-form |
abd11edf30aa0a77548b04263b26edd1efe8cc89 | app/containers/TimeProvider/index.js | app/containers/TimeProvider/index.js | import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { gql, graphql } from 'react-apollo';
import { getCurrentTimeSuccess } from '../App/actions';
const GetCurrentTime = gql`
query GetCurrentTime {
time
}
`;
@graphql(GetCurrentTime, { options: { pollInterval: 5 * 60 * 1000 } })
@connect(null, (dispatch) => ({ dispatch }))
export default class TimeProvider extends React.PureComponent {
constructor(props) {
super(props);
this.parseProps(props);
}
componentWillReceiveProps(nextProps) {
this.parseProps(nextProps);
}
parseProps(props) {
if (!props.data.loading) {
this.props.dispatch(getCurrentTimeSuccess(moment(props.data.time)));
}
}
render() {
return this.props.children ? this.props.children : null;
}
}
TimeProvider.propTypes = {
children: PropTypes.node,
dispatch: PropTypes.func,
};
| import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { gql, graphql } from 'react-apollo';
import { getCurrentTimeSuccess } from '../App/actions';
const GetCurrentTime = gql`
query GetCurrentTime {
time
}
`;
@graphql(GetCurrentTime, { options: { pollInterval: 5 * 60 * 1000 } })
@connect(null, (dispatch) => ({ dispatch }))
export default class TimeProvider extends React.PureComponent {
constructor(props) {
super(props);
this.parseProps(props);
}
componentWillReceiveProps(nextProps) {
this.parseProps(nextProps);
}
parseProps(props) {
if (!props.data.loading && !props.data.error) {
this.props.dispatch(getCurrentTimeSuccess(moment(props.data.time)));
}
}
render() {
return this.props.children ? this.props.children : null;
}
}
TimeProvider.propTypes = {
children: PropTypes.node,
dispatch: PropTypes.func,
};
| Check for GraphQL error in TimeProvider | Check for GraphQL error in TimeProvider
| JavaScript | bsd-3-clause | zmora-agh/zmora-ui,zmora-agh/zmora-ui |
80da46e990bc2f9562d56874903ecfde718027e7 | test/riak.js | test/riak.js | "use strict";
/* global describe, it */
describe('Riak client', function() {
var riakClient = require('../lib/riak')();
it('#getServerInfo', function() {
return riakClient.getServerInfo()
.then(function(info) {
info.should.have.property('node')
info.should.have.property('server_version')
})
})
})
| "use strict";
/* global describe, it, before */
describe('Riak client', function() {
var riakClient = require('../lib/riak')();
var bucket = 'test-riak-' + Date.now();
before(function() {
return riakClient.setBucket({
bucket: bucket,
props: {
allow_mult: true,
last_write_wins: false,
}
})
})
it('#getServerInfo', function() {
return riakClient.getServerInfo()
.then(function(info) {
info.should.have.property('node')
info.should.have.property('server_version')
})
})
it('delete without vclock should not create sibling (allow_mult=true)', function() {
var vclock;
return riakClient.put({
bucket: bucket,
key: 'testKey',
content: {
value: '1234'
},
return_head: true
})
.then(function(reply) {
vclock = reply.vclock
return riakClient.del({
bucket: bucket,
key: 'testKey'
})
})
.then(function() {
return riakClient.get({
bucket: bucket,
key: 'testKey',
deletedvclock: true
})
})
.then(function(reply) {
reply.should.not.have.property('content')
reply.vclock.should.not.be.eql(vclock)
})
})
it('delete with stale vclock should create sibling (allow_mult=true)', function() {
var vclock;
return riakClient.put({
bucket: bucket,
key: 'testKey2',
content: {
value: '1234'
},
return_head: true
})
.then(function(reply) {
vclock = reply.vclock
return riakClient.put({
bucket: bucket,
key: 'testKey2',
vclock: vclock,
content: {
value: '123456'
}
})
})
.then(function() {
return riakClient.del({
bucket: bucket,
key: 'testKey2',
vclock: vclock
})
})
.then(function() {
return riakClient.get({
bucket: bucket,
key: 'testKey2',
deletedvclock: true
})
})
.then(function(reply) {
reply.should.have.property('content').that.is.an('array').and.have.length(2)
})
})
})
| Test Riak delete object with allow_mult=true | Test Riak delete object with allow_mult=true
| JavaScript | mit | oleksiyk/riakfs |
851cf0c6edb73b18dac37ffebb5b09c0e5237310 | server/app.js | server/app.js | import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import http from 'http';
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set('json spaces', 4);
const port = parseInt(process.env.PORT, 10) || 5000;
app.set('port', port);
require('./routes')(app);
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the beginning of aawesomeness',
}));
const server = http.createServer(app);
server.listen(port);
module.exports = app;
| import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
const app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.set('json spaces', 4);
const port = process.env.PORT || 5000;
app.set('port', port);
require('./routes')(app);
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the beginning of aawesomeness',
}));
app.listen(port);
module.exports = app;
| Refactor filre for hosting heroku | Refactor filre for hosting heroku
| JavaScript | mit | Billmike/More-Recipes,Billmike/More-Recipes |
1bcb78fa324e44fd9dcfebdb0a5f5e409f9a746a | lib/core/src/server/common/babel-loader.js | lib/core/src/server/common/babel-loader.js | import { includePaths, excludePaths } from '../config/utils';
export default options => ({
test: /\.(mjs|jsx?)$/,
use: [
{
loader: 'babel-loader',
options,
},
],
include: includePaths,
exclude: excludePaths,
});
export const nodeModulesBabelLoader = {
test: /\.js$/,
include: /\/node_modules\/safe-eval\//,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
require.resolve('@babel/preset-env'),
{
useBuiltIns: 'usage',
modules: 'commonjs',
},
],
],
},
},
],
};
| import { includePaths, excludePaths } from '../config/utils';
export default options => ({
test: /\.(mjs|jsx?)$/,
use: [
{
loader: 'babel-loader',
options,
},
],
include: includePaths,
exclude: excludePaths,
});
export const nodeModulesBabelLoader = {
test: /\.js$/,
include: /\/node_modules\/safe-eval\//,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
[
'env',
{
modules: 'commonjs',
},
],
],
},
},
],
};
| Make nodeModulesBabelLoader compatible with Babel 6 | Make nodeModulesBabelLoader compatible with Babel 6
| JavaScript | mit | storybooks/storybook,kadirahq/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook |
ffd6a08630675550427919737f6ddb6020ff1e63 | main.js | main.js | /*
* Evernote-webhooks: A project to use webhooks to automate things in Evernote
*/
var express = require('express');
var config = require('./config.json');
var app = express();
var consumerKey = process.env.consumerKey;
var consumerSecret = process.env.consumerSecret;
var wwwDir = "/www";
app.use('/', express.static(__dirname + wwwDir));
app.get('/:endpoint', function(req, res, next) { console.log(req.params.endpoint); next(); });
app.get('/', function(req, res) { res.render(wwwDir + '/index.html');});
// Start the server on port 3000 or the server port.
var port = process.env.PORT || 3000;
console.log('PORT: ' + port);
var server = app.listen(port);
| /*
* Evernote-webhooks: A project to use webhooks to automate things in Evernote
*/
var express = require('express');
var app = express();
var consumerKey = process.env.consumerKey;
var consumerSecret = process.env.consumerSecret;
var wwwDir = "/www";
app.use('/', express.static(__dirname + wwwDir));
app.get('/:endpoint', function(req, res, next) { console.log(req.params.endpoint); next(); });
app.get('/', function(req, res) { res.render(wwwDir + '/index.html');});
// Start the server on port 3000 or the server port.
var port = process.env.PORT || 3000;
console.log('PORT: ' + port);
var server = app.listen(port);
| Remove import of config.json for Heroku to work | Remove import of config.json for Heroku to work
| JavaScript | mit | tomzhang32/evernote-webhooks,tomzhang32/evernote-webhooks |
4f6915eb0ee67ea77a69ac7d4653279abb6e6bbd | data-init.js | data-init.js | 'use strict';
angular.module('ngAppInit', []).
provider('$init', function(
){
this.$get = function() {
return {};
};
}).
directive('ngAppInit', function(
$window,
$init
){
return {
compile: function() {
return {
pre: function(scope, element, attrs) {
angular.extend($init, $window.JSON.parse(attrs.ngAppInit));
}
};
}
};
});
| 'use strict';
angular.module('data-init', []).
provider('$init', function() {
this.$get = function(
$window
){
return $window.JSON.parse(document.querySelector('[ng-app]').dataset.init);
};
});
| Rewrite the logic without using directive | Rewrite the logic without using directive
| JavaScript | mit | gsklee/angular-init |
f51217f928277adb8888e52cbcd8d7f373d72df4 | src/db/queries.js | src/db/queries.js | const pgp = require('pg-promise')()
const dbName = 'vinyl'
const connectionString = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`
const db = pgp(connectionString)
const getAlbums = () => {
return db.query('SELECT * FROM albums')
}
const getAlbumById = (albumId) => {
return db.one(`
SELECT * FROM albums
WHERE id = $1
`, [albumId])
}
const getUserByEmail = (email) => {
return db.one(`
SELECT * FROM users WHERE email = $1
`, [email])
.catch((error) => {
console.error('\nError in queries.getUserByEmail\n')
throw error
})
}
const createUser = (name, email, password) => {
return db.none(`
INSERT INTO
users (name, email, password)
VALUES
($1, $2, $3)
`, [name, email, password])
}
module.exports = {
getAlbums,
getAlbumById,
createUser,
getUserByEmail
}
| const pgp = require('pg-promise')()
const dbName = 'vinyl'
const connectionString = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`
const db = pgp(connectionString)
const getAlbums = () => {
return db.query('SELECT * FROM albums')
}
const getAlbumById = (albumId) => {
return db.one(`
SELECT * FROM albums
WHERE id = $1
`, [albumId])
}
const getUserByEmail = (email) => {
return db.one(`
SELECT * FROM users WHERE LOWER(email) = LOWER($1)
`, [email])
.catch((error) => {
console.error('\nError in queries.getUserByEmail\n')
throw error
})
}
const createUser = (name, email, password) => {
return db.none(`
INSERT INTO
users (name, email, password)
VALUES
($1, $2, $3)
`, [name, email, password])
}
module.exports = {
getAlbums,
getAlbumById,
createUser,
getUserByEmail
}
| Update query to make e-mail in sign-in not case sensitive | Update query to make e-mail in sign-in not case sensitive
| JavaScript | mit | Maighdlyn/phase-4-challenge,Maighdlyn/phase-4-challenge,Maighdlyn/phase-4-challenge |
d9a2f54d42395ca21edc1de6383049af0d512c42 | homeworks/dmitry.minchenko_wer1Kua/homework_2/script.js | homeworks/dmitry.minchenko_wer1Kua/homework_2/script.js | (function() {
let height = 1,
block = '#',
space = ' ';
if (height<2) {
return console.log('Error! Height must be >= 2');
}
for (let i = 0; i < height; i++) {
console.log(space.repeat(height-i) + block.repeat(i+1) + space.repeat(2) + block.repeat(1+i));
}
})();
| (function() {
let height = 13,
block = '#',
space = ' ';
if (height<2 && height>12) {
return console.log('Error! Height must be >= 2 and <= 12');
}
for (let i = 0; i < height; i++) {
console.log(space.repeat(height-i) + block.repeat(i+1) + space.repeat(2) + block.repeat(1+i));
}
})();
| Add maximum check for pyramid height | Add maximum check for pyramid height
| JavaScript | mit | MastersAcademy/js-course-2017,MastersAcademy/js-course-2017,MastersAcademy/js-course-2017 |
04866dcdf67fe8a264a0bf6308613339527ed69c | app/api/rooms.js | app/api/rooms.js | module.exports = function(app) {
/**
* @apiGroup buildings
* @apiName Show list of buildings
* @apiVersion 3.0.0
* @api {get} buildings Show list of available buildings
* @apiSuccess {[]} buildings List of buildings
* @apiError InternalServerError
*/
app.get('/api/v3/buildings', function(request, response) {
app.settings.db.Building.find({},
{ _id: 0, __v: 0, rooms: 0 },
function(error, buildings) {
if (error)
return response.status(500).send();
response.json(buildings);
});
});
/**
* @apiGroup building
* @apiName Get building information
* @apiVersion 3.0.0
* @api {get} buildings Show list of available buildings
* @apiParam {string} name Building name
* @apiSuccess {} building data
* @apiError BuildingNotFound
*/
app.get('/api/v3/buildings/:name', function(request, response) {
var name = request.params.name;
app.settings.db.Building.find(
{ "name" : new RegExp(name, 'i') },
{ _id: 0, __v: 0 },
function(error, building) {
if (error || building.length == 0)
return response.status(404).send("BuildingNotFound");
response.json(building[0]);
});
});
}; | module.exports = function(app) {
/**
* @apiGroup buildings
* @apiName Show list of buildings
* @apiVersion 3.0.0
* @api {get} buildings Show list of available buildings
* @apiSuccess {[]} buildings List of buildings
* @apiError InternalServerError
*/
app.get('/api/v3/buildings', function(request, response) {
app.settings.db.Building.find({},
{ _id: 0, __v: 0, rooms: 0 },
function(error, buildings) {
if (error)
return response.status(500).send();
response.json(buildings);
});
});
/**
* @apiGroup building
* @apiName Get building information
* @apiVersion 3.0.0
* @api {get} buildings Show list of available buildings
* @apiParam {string} name Building name
* @apiSuccess {string} name building name
* @apiError BuildingNotFound
*/
app.get('/api/v3/buildings/:name', function(request, response) {
var name = request.params.name;
app.settings.db.Building.find(
{ "name" : new RegExp(name, 'i') },
{ _id: 0, __v: 0 },
function(error, building) {
if (error || building.length == 0)
return response.status(404).send("BuildingNotFound");
response.json(building[0]);
});
});
}; | Fix apidoc to allow `npm install` to complete | Fix apidoc to allow `npm install` to complete
| JavaScript | mit | igalshapira/ziggi3,igalshapira/ziggi3 |
1e2f32d2da67b3731deee762f888682884f90099 | spec/specs.js | spec/specs.js | describe('pingPong', function() {
it("is false for a number that is not divisible by 3 or 5", function() {
expect(pingPong(7)).to.equal(false);
});
it("will run pingPongType if isPingPong is true", function() {
expect(pingPong(6)).to.equal("ping");
});
});
describe('pingPongType', function() {
it("returns ping for a number that is divisible by 3", function() {
expect(pingPongType(6)).to.equal("ping");
});
it("returns pong for a number that is divisible by 5", function() {
expect(pingPongType(10)).to.equal("pong");
});
it("returns pingpong for a number that is divisible by 3 and 5", function() {
expect(pingPongType(30)).to.equal("pingpong")
});
});
describe('isPingPong', function() {
it("returns true for a number divisible by 3, 5, or 15", function() {
expect(isPingPong(6)).to.equal(true);
});
it("returns false for a number not divisible by 3, 5, or 15", function() {
expect(isPingPong(7)).to.equal(false);
});
});
| describe('pingPongType', function() {
it("returns ping for a number that is divisible by 3", function() {
expect(pingPongType(6)).to.equal("ping");
});
it("returns pong for a number that is divisible by 5", function() {
expect(pingPongType(10)).to.equal("pong");
});
it("returns pingpong for a number that is divisible by 3 and 5", function() {
expect(pingPongType(30)).to.equal("pingpong")
});
});
describe('isPingPong', function() {
it("returns pingPongType for a number divisible by 3, 5, or 15", function() {
expect(isPingPong(6)).to.equal("ping");
});
it("returns false for a number not divisible by 3, 5, or 15", function() {
expect(isPingPong(7)).to.equal(false);
});
});
| Remove description for pingPong, leave tests for pingPongType and isPingPong | Remove description for pingPong, leave tests for pingPongType and isPingPong
| JavaScript | mit | kcmdouglas/pingpong,kcmdouglas/pingpong |
91d8bb02e4216ac90cfe6d2ec98c52785720cc3b | node.js | node.js | /*eslint-env node*/
// Import assert function
global.assert = require("assert");
// Code coverage helper
require("blanket")({
pattern: "src/sinon.js"
});
// 'Simulate' browser environment by creating a window object
global.window = {};
// 'Load' the current sinon file
require("./src/sinon.js");
// Map the sinon object to global in order to make it global
global.sinon = window.sinon;
| /*eslint-env node*/
// Import assert function
global.assert = require("assert");
delete global._$jscoverage; // Purge any previous blanket use
// Code coverage helper
require("blanket")({
pattern: "src/sinon.js"
});
// 'Simulate' browser environment by creating a window object
global.window = {};
// 'Load' the current sinon file
require("./src/sinon.js");
// Map the sinon object to global in order to make it global
global.sinon = window.sinon;
| Clean any previous usage of blanket (because re-run in the same process) | Clean any previous usage of blanket (because re-run in the same process)
| JavaScript | mit | ArnaudBuchholz/training-functions-stub,ArnaudBuchholz/training-functions-stub |
e1b5de724f301ae61ef656dbeab783bc2cdf2d54 | api/controllers/GCMController.js | api/controllers/GCMController.js | /**
* GCMKey provider
*
* @description :: Server-side logic for managing users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
key: function key(req, res) {
sails.log("Google Project Number: " + sails.config.push.gcm.projectNumber);
res.json(sails.config.push.gcm.projectNumber);
}
};
| /**
* GCMKey provider
*
* @description :: Server-side logic for managing users
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
key: function key(req, res) {
sails.log("Google Project Number: " + sails.config.gcm.projectNumber);
res.json(sails.config.gcm.projectNumber);
}
};
| Use correct sails.config for GCM key | Use correct sails.config for GCM key
| JavaScript | mit | SneakSpeak/sp-server |
7f71436ba8d4c879a945d4ba7d88a71f2dbe0a43 | apps/crbug/bg.js | apps/crbug/bg.js | var qb;
function launch() {
if ( ! qb ) qb = QBug.create();
qb.launchBrowser();
// qb.launchBrowser('chromium');
}
if ( chrome.app.runtime ) {
ajsonp = (function() {
var factory = OAuthXhrFactory.create({
authAgent: ChromeAuthAgent.create({}),
responseType: "json"
});
return function(url, params, opt_method) {
return function(ret) {
var xhr = factory.make();
return xhr.asend(ret, opt_method ? opt_method : "GET", url + (params ? '?' + params.join('&') : ''));
};
};
})();
chrome.app.runtime.onLaunched.addListener(function(opt_launchData) {
// launchData is provided by the url_handler
if ( opt_launchData ) console.log(opt_launchData.url);
console.log('launched');
launch();
});
}
| var qb;
function launch() {
if ( ! qb ) qb = QBug.create();
qb.launchBrowser();
// qb.launchBrowser('chromium');
}
if ( chrome.app.runtime ) {
ajsonp = (function() {
var factory = OAuthXhrFactory.create({
authAgent: ChromeAuthAgent.create({}),
responseType: "json"
});
return function(url, params, opt_method, opt_payload) {
return function(ret) {
var xhr = factory.make();
xhr.responseType = "json";
return xhr.asend(ret,
opt_method ? opt_method : "GET",
url + (params ? '?' + params.join('&') : ''),
opt_payload);
};
};
})();
chrome.app.runtime.onLaunched.addListener(function(opt_launchData) {
// launchData is provided by the url_handler
if ( opt_launchData ) console.log(opt_launchData.url);
console.log('launched');
launch();
});
}
| Add optional payload to ajsonp | Add optional payload to ajsonp
| JavaScript | apache-2.0 | osric-the-knight/foam,shepheb/foam,jacksonic/foam,shepheb/foam,foam-framework/foam,osric-the-knight/foam,jacksonic/foam,osric-the-knight/foam,foam-framework/foam,mdittmer/foam,mdittmer/foam,mdittmer/foam,shepheb/foam,jlhughes/foam,jlhughes/foam,jlhughes/foam,foam-framework/foam,jacksonic/foam,foam-framework/foam,mdittmer/foam,foam-framework/foam,osric-the-knight/foam,jacksonic/foam,jlhughes/foam |
06dba54a9bd08e27756dceebd214841986de9d1a | grunt.js | grunt.js | module.exports = function (grunt) {
grunt.initConfig({
meta: {
banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0]
},
min: {
dist: {
src: ['<banner>', 'src/loStorage.js'],
dest: 'src/loStorage.min.js'
}
},
jasmine: {
all: ['spec/index.html']
},
watch: {
test: {
files: ['src/loStorage.js', 'spec/*'],
tasks: 'test'
}
}
});
grunt.loadNpmTasks('grunt-jasmine-task');
grunt.registerTask('test', 'jasmine');
grunt.registerTask('release', 'test min');
grunt.registerTask('default', 'release');
}; | module.exports = function (grunt) {
grunt.initConfig({
meta: {
banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0]
},
min: {
dist: {
src: ['<banner>', 'src/loStorage.js'],
dest: 'src/loStorage.min.js'
}
},
jasmine: {
all: ['spec/index.html']
},
watch: {
test: {
files: ['src/loStorage.js', 'spec/*'],
tasks: 'test'
},
min: {
files: ['src/loStorage.js'],
tasks: 'min'
}
}
});
grunt.loadNpmTasks('grunt-jasmine-task');
grunt.registerTask('test', 'jasmine');
grunt.registerTask('release', 'test min');
grunt.registerTask('default', 'release');
}; | Add min task to watch | Add min task to watch
| JavaScript | mit | js-coder/loStorage.js,js-coder/loStorage.js,florian/loStorage.js,florian/loStorage.js,joshprice/loStorage.js,npmcomponent/js-coder-loStorage.js |
c945aa9f72df97c2244d108d7cb0a4a778d6e2f1 | vendor/assets/javascripts/_element.js | vendor/assets/javascripts/_element.js | this.Element && function (ElementPrototype) {
ElementPrototype.matches = ElementPrototype.matches ||
ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function (selector) {
var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1;
while (nodes[++i] && nodes[i] != node);
return !!nodes[i];
}
} (Element.prototype);
this.Element && function (ElementPrototype) {
ElementPrototype.closest =
function (selector) {
var node = this;
while (node) {
if (node == document) return undefined;
if (node.matches(selector)) return node;
node = node.parentNode;
}
}
} (Element.prototype);
| /*jshint bitwise: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: double, undef: true, unused: vars, strict: true, trailing: true, maxdepth: 3, devel: true, asi: true */
/*global HTMLElement: true */
//
// ELEMENT
//
// Closest
// Usage: element.closest(selector)
this.Element && function (ElementPrototype) {
ElementPrototype.closest =
function (selector) {
var node = this;
while (node) {
if (node == document) return undefined;
if (node.matches(selector)) return node;
node = node.parentNode;
}
}
} (Element.prototype);
// Matches
// Usage: element.matches(selector)
this.Element && function (ElementPrototype) {
ElementPrototype.matches = ElementPrototype.matches ||
ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function (selector) {
var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1;
while (nodes[++i] && nodes[i] != node);
return !!nodes[i];
}
} (Element.prototype);
| Add jshint options and comments. | Add jshint options and comments. | JavaScript | mit | smockle/black-coffee |
0dd0ec941fcc80c20a522ed409fd98b49b40e3a6 | src/app/utilities/api-clients/collections.js | src/app/utilities/api-clients/collections.js | import http from '../http';
export default class collections {
static get(collectionID) {
return http.get(`/zebedee/collectionDetails/${collectionID}`)
.then(response => {
return response;
})
}
static getAll() {
return http.get(`/zebedee/collections`)
.then(response => {
return response;
})
}
static create(body) {
return http.post(`/zebedee/collection`, body)
.then(response => {
return response;
})
}
static approve(collectionID) {
return http.post(`/zebedee/approve/${collectionID}`);
}
static delete(collectionID) {
return http.delete(`/zebedee/collection/${collectionID}`);
}
static update(collectionID, body) {
body.id = collectionID;
return http.put(`/zebedee/collection/${collectionID}`, body);
}
static deletePage(collectionID, pageURI) {
return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`);
}
static cancelDelete(collectionID, pageURI) {
return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`);
}
} | import http from '../http';
export default class collections {
static get(collectionID) {
return http.get(`/zebedee/collectionDetails/${collectionID}`)
.then(response => {
return response;
})
}
static getAll() {
return http.get(`/zebedee/collections`)
.then(response => {
return response;
})
}
static create(body) {
return http.post(`/zebedee/collection`, body)
.then(response => {
return response;
})
}
static approve(collectionID) {
return http.post(`/zebedee/approve/${collectionID}`);
}
static delete(collectionID) {
return http.delete(`/zebedee/collection/${collectionID}`);
}
static update(collectionID, body) {
body.id = collectionID;
return http.put(`/zebedee/collection/${collectionID}`, body);
}
static deletePage(collectionID, pageURI) {
return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`);
}
static cancelDelete(collectionID, pageURI) {
return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`);
}
static async checkContentIsInCollection(pageURI) {
return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`)
}
} | Add method to check is content is in another collection | Add method to check is content is in another collection
| JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence |
c56370a3518f967a6f4afed8bcc84c17500ee0b3 | assets/js/googlesitekit-settings.js | assets/js/googlesitekit-settings.js | /**
* Settings component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { HashRouter } from 'react-router-dom';
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { render } from '@wordpress/element';
/**
* Internal dependencies
*/
import './components/legacy-notifications';
import Root from './components/Root';
import SettingsApp from './components/settings/SettingsApp';
import './modules';
// Initialize the app once the DOM is ready.
domReady( () => {
const renderTarget = document.getElementById( 'googlesitekit-settings-wrapper' );
if ( renderTarget ) {
render(
<Root dataAPIContext="Settings">
<HashRouter>
<SettingsApp />
</HashRouter>
</Root>,
renderTarget
);
}
} );
| /**
* Settings component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { HashRouter } from 'react-router-dom';
/**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
import { render } from '@wordpress/element';
/**
* Internal dependencies
*/
import './components/legacy-notifications';
import Root from './components/Root';
import SettingsApp from './components/settings/SettingsApp';
// Initialize the app once the DOM is ready.
domReady( () => {
const renderTarget = document.getElementById( 'googlesitekit-settings-wrapper' );
if ( renderTarget ) {
render(
<Root dataAPIContext="Settings">
<HashRouter>
<SettingsApp />
</HashRouter>
</Root>,
renderTarget
);
}
} );
| Remove import ref so builds. | Remove import ref so builds.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp |
0427b16a7ca1a2f1f5811794d798952787ffc6ea | blueprints/ivy-redactor/index.js | blueprints/ivy-redactor/index.js | /* jshint node:true */
module.exports = {
afterInstall: function() {
return this.addBowerPackageToProject('polyfills-pkg');
},
normalizeEntityName: function() {
}
};
| /* jshint node:true */
module.exports = {
normalizeEntityName: function() {
}
};
| Stop requiring a polyfill that we don't need | Stop requiring a polyfill that we don't need
| JavaScript | mit | IvyApp/ivy-redactor,IvyApp/ivy-redactor |
1af89b716f562b046bb1673725ee2cb6b660a82d | spec/writeFile.spec.js | spec/writeFile.spec.js | var path = require('path'),
fs = require('fs'),
crypto = require('crypto');
describe("writeFile functionality", function() {
var _this = this;
require('./harness.js')(_this);
it("creates a directory", function(done) {
var fname = "testDir";
var resolved = path.resolve(_this.tempdir, fname);
crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
if (err) throw err;
_this.wd.writeFile(fname, data, function(err) {
expect(err).toBe(null);
fs.readFile(resolved, function(err, rdata) {
if (err) throw err;
expect(rdata.toString()).toBe(data.toString());
done();
});
});
});
});
}); | var path = require('path'),
fs = require('fs'),
crypto = require('crypto');
describe("writeFile functionality", function() {
var _this = this;
require('./harness.js')(_this);
it("writes data to a file that doesn't exist", function(done) {
var fname = "testDir";
var resolved = path.resolve(_this.tempdir, fname);
crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
if (err) throw err;
_this.wd.writeFile(fname, data, function(err) {
expect(err).toBe(null);
fs.readFile(resolved, function(err, rdata) {
if (err) throw err;
expect(rdata.toString()).toBe(data.toString());
done();
});
});
});
});
}); | Fix name of writeFile test | Fix name of writeFile test
| JavaScript | bsd-2-clause | terribleplan/WorkingDirectory |
1ec5cc77997e6cc254b1891c2efdc1839f63625e | client/src/actions.js | client/src/actions.js | import { createAction } from 'redux-actions';
export const REQUEST_LOGIN = "REQUEST_LOGIN";
export const SUCCESS_LOGIN = "SUCCESS_LOGIN";
export const FAILURE_LOGIN = "FAILURE_LOGIN";
export const REQUEST_SUBMIT_SONG = "REQUEST_SUBMIT_SONG";
export const SUCCESS_SUBMIT_SONG = "SUCCESS_SUBMIT_SONG";
export const FAILURE_SUBMIT_SONG = "FAILURE_SUBMIT_SONG";
export const INPUT_QUERY = "INPUT_QUERY";
export const REQUEST_SEARCH = "REQUEST_SEARCH";
export const SUCCESS_SEARCH = "SUCCESS_SEARCH";
export const FAILURE_SEARCH = "FAILURE_SEARCH";
export const ADDED_SONG = "ADDED_SONG";
export const RequestLogin = createAction(REQUEST_LOGIN);
export const SuccessLogin = createAction(SUCCESS_LOGIN);
export const FailureLogin = createAction(FAILURE_LOGIN);
export const RequestSubmitSong = createAction(REQUEST_SUBMIT_SONG);
export const SuccessSubmitSong = createAction(SUCCESS_SUBMIT_SONG);
export const FailureSubmitSong = createAction(FAILURE_SUBMIT_SONG);
export const InputQuery = createAction(INPUT_QUERY);
export const RequestSearch = createAction(REQUEST_SEARCH);
export const SuccessSearch = createAction(SUCCESS_SEARCH);
export const FailureSearch = createAction(FAILURE_SEARCH);
export const AddedSong = createAction(ADDED_SONG);
| import { createAction } from 'redux-actions';
export createActions(
"REQUEST_LOGIN",
"SUCCESS_LOGIN",
"FAILURE_LOGIN",
"REQUEST_SUBMIT_SONG",
"SUCCESS_SUBMIT_SONG",
"FAILURE_SUBMIT_SONG",
"INPUT_QUERY",
"REQUEST_SEARCH",
"SUCCESS_SEARCH",
"FAILURE_SEARCH",
"ADDED_SONG",
"PLAYED_SONG"
);
| Use createActions to create actioncreator | Use createActions to create actioncreator
| JavaScript | mit | ygkn/DJ-YAGICHAN-SYSTEM,ygkn/DJ-YAGICHAN-SYSTEM |
2c2517cef0f4b3183b8bbeabc72ff754a82178fc | web_external/js/init.js | web_external/js/init.js | /*global isic:true*/
var isic = isic || {};
_.extend(isic, {
models: {},
collections: {},
views: {},
router: new Backbone.Router(),
events: _.clone(Backbone.Events)
});
girder.router.enabled(false);
| /*global isic:true*/
var isic = isic || {};
_.extend(isic, {
models: {},
collections: {},
views: {},
router: new Backbone.Router(),
events: girder.events
});
girder.router.enabled(false);
| Make isic.events an alias for girder.events | Make isic.events an alias for girder.events
Make isic.events an alias for girder.events instead of a separate object. For
one, this ensures that triggering the 'g:appload.before' and 'g:appload.after'
events in main.js reach plugins that observe those events on girder.events, such
as the google_analytics plugin.
| JavaScript | apache-2.0 | ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive |
ddcc84a84d3eced473e57c46c5f667424b4386fa | test/integration/test-remote.js | test/integration/test-remote.js | const Test = require('./include/runner');
const setUp = (context) => {
return context.gitP(context.root).init();
};
describe('remote', () => {
let context;
let REMOTE_URL = 'https://github.com/steveukx/git-js.git';
beforeEach(() => setUp(context = Test.createContext()));
it('adds and removes named remotes', async () => {
const {gitP, root} = context;
await gitP(root).addRemote('remote-name', REMOTE_URL);
expect(await gitP(root).getRemotes(true)).toEqual([
{ name: 'remote-name', refs: { fetch: REMOTE_URL, push: REMOTE_URL }},
]);
await gitP(root).removeRemote('remote-name');
expect(await gitP(root).getRemotes(true)).toEqual([]);
});
})
| const Test = require('./include/runner');
const setUp = (context) => {
return context.gitP(context.root).init();
};
describe('remote', () => {
let context;
let REMOTE_URL_ROOT = 'https://github.com/steveukx';
let REMOTE_URL = `${ REMOTE_URL_ROOT }/git-js.git`;
beforeEach(() => setUp(context = Test.createContext()));
it('adds and removes named remotes', async () => {
const {gitP, root} = context;
await gitP(root).addRemote('remote-name', REMOTE_URL);
expect(await gitP(root).getRemotes(true)).toEqual([
{name: 'remote-name', refs: {fetch: REMOTE_URL, push: REMOTE_URL}},
]);
await gitP(root).removeRemote('remote-name');
expect(await gitP(root).getRemotes(true)).toEqual([]);
});
it('allows setting the remote url', async () => {
const {gitP, root} = context;
const git = gitP(root);
let repoName = 'origin';
let initialRemoteRepo = `${REMOTE_URL_ROOT}/initial.git`;
let updatedRemoteRepo = `${REMOTE_URL_ROOT}/updated.git`;
await git.addRemote(repoName, initialRemoteRepo);
expect(await git.getRemotes(true)).toEqual([
{name: repoName, refs: {fetch: initialRemoteRepo, push: initialRemoteRepo}},
]);
await git.remote(['set-url', repoName, updatedRemoteRepo]);
expect(await git.getRemotes(true)).toEqual([
{name: repoName, refs: {fetch: updatedRemoteRepo, push: updatedRemoteRepo}},
]);
});
})
| Add test for using `addRemote` and `remote(['set-url', ...])'` | Add test for using `addRemote` and `remote(['set-url', ...])'`
Ref: #452
| JavaScript | mit | steveukx/git-js,steveukx/git-js |
5f6c2a23b524f1b6465e3335956b2d62e9c6f42b | index.js | index.js | (function() {
'use strict';
var ripper = require('./Rip'),
encoder = require('./Encode'),
ui = require('bull-ui/app')({
redis: {
host: 'localhost',
port: '6379'
}
}),
Queue = require('bull');
ui.listen(1337, function() {
console.log('bull-ui started listening on port', this.address().port);
});
var ripQ = Queue('disc ripping');
var encodeQ = Queue('video encoding');
encodeQ.add({
type: './HandBrakeCLI',
options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o',
destination: '/mnt/temp'
});
ripQ.add({
destination: '/mnt/temp'
});
encodeQ.process(function(job) {
return encoder.encode(job);
});
ripQ.process(function(job) {
return ripper.rip(job);
});
}());
| (function() {
'use strict';
var ripper = require('./Rip'),
fs = require('fs'),
encoder = require('./Encode'),
ui = require('bull-ui/app')({
redis: {
host: 'localhost',
port: '6379'
}
}),
Queue = require('bull');
ui.listen(1337, function() {
console.log('bull-ui started listening on port', this.address().port);
});
var ripQ = Queue('disc ripping');
var encodeQ = Queue('video encoding');
encodeQ.add({
type: './HandBrakeCLI',
options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o',
destination: '/mnt/temp'
});
ripQ.add({
destination: '/mnt/temp'
});
encodeQ.process(function(job) {
return encoder.encode(job);
});
if(fs.existsSync('/dev/sr0')) {
//if a DVD device exists, then we can process the Ripping queue
ripQ.process(function(job) {
return ripper.rip(job);
});
}
}());
| Check for DVD device for ripping queue processing | Check for DVD device for ripping queue processing
| JavaScript | mit | aztechian/ncoder,aztechian/ncoder |
3086a6cb835bc47ca26c357178612f01b6f4ade8 | src/server/webapp.js | src/server/webapp.js | 'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./controllers/routes');
let app = express();
// Configure view engine and views directory
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Configure middleware
app.use(bodyParser.urlencoded({ extended: false }));
// Static file serving happens everywhere but in production
if (process.env.NODE_ENV !== 'production') {
let staticPath = path.join(__dirname, '..', '..', 'public');
app.use('/static', express.static(staticPath));
}
// Mount application routes
routes(app);
// Export Express webapp instance
module.exports = app;
| 'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./controllers/routes');
let app = express();
// Configure view engine and views directory
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('x-powered-by', false);
// Configure middleware
app.use(bodyParser.urlencoded({ extended: false }));
// Static file serving happens everywhere but in production
if (process.env.NODE_ENV !== 'production') {
let staticPath = path.join(__dirname, '..', '..', 'public');
app.use('/static', express.static(staticPath));
}
// Mount application routes
routes(app);
// Export Express webapp instance
module.exports = app;
| Remove the 'X-Powered-By: Express' HTTP response header | Remove the 'X-Powered-By: Express' HTTP response header
Fixes #2
| JavaScript | mit | kwhinnery/todomvc-plusplus,kwhinnery/todomvc-plusplus |
80ce4c3203bff1e5848360d91a507778ea86edc3 | index.js | index.js | var postcss = require('postcss');
module.exports = postcss.plugin('postcss-prefixer-font-face', function (opts) {
opts = opts || {};
var prefix = opts.prefix || '';
var usedFonts = [];
return function (css, result) {
/* Font Faces */
css.walkAtRules(/font-face$/, function (font) {
font.walkDecls(/font-family/, function (decl) {
var fontName = decl.value.replace(/['"]+/g, '');
usedFonts.push(fontName);
decl.value = '\''+String(prefix+fontName)+'\'';
});
});
css.walkDecls(/font-family/, function (decl) {
var fontName = decl.value.replace(/['"]+/g, '');
if (usedFonts.indexOf(fontName) > -1) {
decl.value = '\''+String(prefix+fontName)+'\'';
}
});
};
});
| var postcss = require('postcss');
module.exports = postcss.plugin('postcss-prefixer-font-face', function (opts) {
opts = opts || {};
var prefix = opts.prefix || '';
var usedFonts = [];
return function (css, result) {
/* Font Faces */
css.walkAtRules(/font-face$/, function (font) {
font.walkDecls(/font-family/, function (decl) {
var fontName = decl.value.replace(/['"]+/g, '');
usedFonts.push(fontName);
decl.value = String(prefix + fontName);
});
});
css.walkDecls(/font-family/, function (decl) {
var fontNames = decl.value.replace(/['"]+/g, '').split(',');
for (var i = 0; i < fontNames.length; i++) {
var fontName = fontNames[i].trim();
if (usedFonts.indexOf(fontName) > -1) {
fontNames[i] = String(prefix + fontName);
}
}
decl.value = fontNames.join(',');
});
};
});
| Support prefix if multiple font families are used | Support prefix if multiple font families are used
| JavaScript | bsd-2-clause | koala-framework/postcss-prefixer-font-face |
d117690efaadd5db838818cbe43a1dbaa63ca885 | index.js | index.js | 'use strict';
var async = require("async");
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = function seeder(seedObject, mongoose, logger, cb) {
if(!cb) {
cb = logger;
logger = console.log;
}
var ObjectId = mongoose.Types.ObjectId;
async.each(Object.keys(seedObject), function(mongoModel, cb) {
var documents = seedObject[mongoModel];
var mongoModelName = capitalize(mongoModel);
var Model = mongoose.model(mongoModelName);
async.each(Object.keys(documents), function(_id, cb) {
// Fake an upsert call, to keep the hooks
Model.findById(_id, function(err, mongoDocument) {
if(err) {
return cb(err);
}
if(!mongoDocument) {
mongoDocument = new Model({_id: new ObjectId(_id)});
}
var document = documents[_id];
for(var key in document) {
mongoDocument[key] = document[key];
mongoDocument.markModified(key);
}
logger(mongoModelName, _id);
mongoDocument.save(cb);
});
}, cb);
}, cb);
};
| 'use strict';
var async = require("async");
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = function seeder(seedObject, mongoose, logger, cb) {
if(!cb) {
cb = logger;
logger = console.log;
}
var ObjectId = mongoose.Types.ObjectId;
async.each(Object.keys(seedObject), function(mongoModel, cb) {
var documents = seedObject[mongoModel];
var mongoModelName = capitalize(mongoModel);
var Model = mongoose.model(mongoModelName);
async.each(Object.keys(documents), function(_id, cb) {
var document = documents[_id];
if(document._id) {
_id = document._id;
}
// Fake an upsert call, to keep the hooks
Model.findById(_id, function(err, mongoDocument) {
if(err) {
return cb(err);
}
if(!mongoDocument) {
mongoDocument = new Model({_id: new ObjectId(_id)});
}
for(var key in document) {
mongoDocument[key] = document[key];
mongoDocument.markModified(key);
}
logger(mongoModelName, _id);
mongoDocument.save(cb);
});
}, cb);
}, cb);
};
| Add managing of _id field | Add managing of _id field
| JavaScript | mit | AnyFetch/seeder.js |
b98db4ad0e627c6a5326e8cabfde1e71e4bfdf2e | test/plexacious.js | test/plexacious.js | const { expect } = require('chai');
const Plexacious = require('../lib/Plexacious');
const config = {
"hostname": process.env.PLEX_SERVER_HOST,
"port": process.env.PLEX_SERVER_PORT,
"https": process.env.PLEX_SERVER_HTTPS,
"token": process.env.PLEX_AUTH_TOKEN
};
const plex = new Plexacious(config);
describe('Plexacious:', () => {
describe('Event attaching:', () => {
it('should instantiate with no events', () => {
expect(plex.events()).to.deep.equal({});
expect(typeof plex.events('test')).to.equal('undefined');
});
it('should attach a callback to an event', () => {
plex.on('test', () => {});
expect(Object.keys(plex.events()).length).to.equal(1);
expect(typeof plex.events('test')).to.equal('function');
});
});
describe('Recently Added:', () => {
});
}); | const { expect } = require('chai');
const Plexacious = require('../lib/Plexacious');
const env = require('node-env-file');
env('./.env');
const config = {
"hostname": process.env.PLEX_SERVER_HOST,
"port": process.env.PLEX_SERVER_PORT,
"https": process.env.PLEX_SERVER_HTTPS,
"token": process.env.PLEX_AUTH_TOKEN
};
const plex = new Plexacious(config);
describe('Plexacious:', () => {
describe('Event attaching:', () => {
it('should instantiate with no events', () => {
expect(plex.eventFunctions()).to.deep.equal({});
expect(typeof plex.eventFunctions('test')).to.equal('undefined');
});
it('should attach a callback to an event', () => {
plex.on('test', () => {});
expect(Object.keys(plex.eventFunctions()).length).to.equal(1);
expect(typeof plex.eventFunctions('test')).to.equal('function');
});
});
describe('Recently Added:', () => {
});
}); | Fix events() call to match renamed function eventFunctions() | Fix events() call to match renamed function eventFunctions()
| JavaScript | isc | ketsugi/plexacious |
203add406fbf5e23976bb32cac99bf004ba5eb4d | src/filter.js | src/filter.js | function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
// Remove covers in "suggested collections"
$(".suggested_collection .covers").remove()
$(".suggested_collection").addClass("ext-coverless_card")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
var observer = new MutationObserver(filter)
observer.observe(document.getElementById("main"), {childList: true, subtree: true})
filter();
| function hide_covers() {
// Remove covers
$(".mix_element div.cover").remove()
// Add class so cards can be restyled
$(".mix_card.half_card").addClass("ext-coverless_card")
// Remove covers on track page
$("#cover_art").remove()
// Remove covers in the sidebar of a track page
$(".card.sidebar_mix .cover").remove()
$(".card.sidebar_mix").addClass("ext-coverless_card")
// Remove covers in "suggested collections"
$(".suggested_collection .covers").remove()
$(".suggested_collection").addClass("ext-coverless_card")
// Remove mini covers ("Because you liked ____")
// Replace with 8tracks icon
$(".card img.mini-cover")
.replaceWith("<span class='avatar'><span class='i-logo'></span></span>")
}
function filter() {
chrome.storage.local.get("state", function(result) {
if(result["state"] == "on") {
hide_covers()
}
});
}
// Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run
var observer = new MutationObserver(filter)
observer.observe(document.getElementById("main"), {childList: true, subtree: true})
filter();
| Replace mini covers with 8tracks icon | Replace mini covers with 8tracks icon
| JavaScript | mit | pbhavsar/8tracks-Filter |
877e9a521fe131978cd63b0af669c01746fe1d8c | index.js | index.js | var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
document.cookie = cookie.serialize(name, val, opt);
}
var reactCookie = {
load: load,
save: save
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
} | var cookie = require('cookie');
var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : '');
for (var key in _cookies) {
try {
_cookies[key] = JSON.parse(_cookies[key]);
} catch(e) {
// Not serialized object
}
}
function load(name) {
return _cookies[name];
}
function save(name, val, opt) {
_cookies[name] = val;
// Cookies only work in the browser
if (typeof document === 'undefined') return;
// allow you to work with cookies as objects.
if (typeof val === 'object') val = JSON.stringify(val);
document.cookie = cookie.serialize(name, val, opt);
}
var reactCookie = {
load: load,
save: save
};
if (typeof module !== 'undefined') {
module.exports = reactCookie
}
if (typeof window !== 'undefined') {
window['reactCookie'] = reactCookie;
}
| Fix cookie not being parsed on load. | Fix cookie not being parsed on load.
If you have to stringify your object before saving, and you add that,
to the `_cookies` cache, then you'll return that on `load` after setting
it with `save`.
While if the value is already set, the script correctly parses the cookie
values and what you load is returned as an object.
This oneliner takes care of that for you.
| JavaScript | mit | ChrisCinelli/react-cookie-async,reactivestack/cookies,xpepermint/react-cookie,eXon/react-cookie,reactivestack/cookies,reactivestack/cookies |
79bf07a15de57912c2f6a0306e028fb3e99fa31e | index.js | index.js | var child_process = require('child_process');
var byline = require('./byline');
exports.handler = function(event, context) {
var proc = child_process.spawn('./main', [JSON.stringify(event)], { stdio: [process.stdin, 'pipe', 'pipe'] });
proc.stdout.on('data', function(line){
var msg = JSON.parse(line);
context.succeed(msg);
})
proc.stderr.on('data', function(line){
var msg = new Error(line)
context.fail(msg);
})
proc.on('exit', function(code){
console.error('exit blabla: %s', code)
context.fail("No results")
})
} | var child_process = require('child_process');
exports.handler = function(event, context) {
var proc = child_process.spawn('./main', [JSON.stringify(event)], { stdio: [process.stdin, 'pipe', 'pipe'] });
proc.stdout.on('data', function(line){
var msg = JSON.parse(line);
context.succeed(msg);
})
proc.stderr.on('data', function(line){
var msg = new Error(line)
context.fail(msg);
})
proc.on('exit', function(code){
console.error('exit blabla: %s', code)
context.fail("No results")
})
} | Remove unused dependency from JS wrapper | Remove unused dependency from JS wrapper
| JavaScript | mit | ArjenSchwarz/igor,ArjenSchwarz/igor |
f232636afd0a7ab9cb148f7b87aac551a866f3ec | index.js | index.js | 'use strict';
class Mutex {
constructor() {
// Item at index 0 is the caller with the lock:
// [ <has the lock>, <waiting>, <waiting>, <waiting> ... ]
this.queue = [];
}
acquire({ timeout = 60000 } = {}) {
const queue = this.queue;
return new Promise((resolve, reject) => {
setTimeout(() => {
const index = queue.indexOf(resolve);
if (index > 0) { // Still waiting in the queue
queue.splice(index, 1);
reject('Queue timeout');
}
}, timeout);
if (queue.push(resolve) === 1) {
// Queue was empty, resolve the promise immediately. Caller is kept in the queue and
// blocks it until it caller calls release()
resolve({ release: function release() {
queue.shift();
if (queue.length > 0) {
queue[0]({ release }); // give the lock to the next in line by resolving the promise
}
}});
}
});
}
}
module.exports = Mutex;
| 'use strict';
class Mutex {
constructor() {
// Item at index 0 is the caller with the lock:
// [ <has the lock>, <waiting>, <waiting>, <waiting> ... ]
this.queue = [];
}
acquire({ timeout = false } = {}) {
const queue = this.queue;
return new Promise((resolve, reject) => {
if (timeout !== false) {
setTimeout(() => {
const index = queue.indexOf(resolve);
if (index > 0) { // Still waiting in the queue
queue.splice(index, 1);
reject('Queue timeout');
}
}, timeout);
}
if (queue.push(resolve) === 1) {
// Queue was empty, resolve this promise immediately. Caller is kept in the queue until
// it calls release()
resolve({
release: function release() {
queue.shift();
if (queue.length > 0) {
queue[0]({ release }); // give the lock to the next in line by resolving the promise
}
}
});
}
});
}
}
module.exports = Mutex;
| Make timeout disabled by default | Make timeout disabled by default
| JavaScript | mit | ilkkao/snap-mutex |
b758446bae6fc066626d04f207c3e668d2a38fd4 | index.js | index.js | 'use strict';
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var api = require('./nestor/api');
var app = express();
app.use(bodyParser.json());
var router = express.Router();
router.route('/')
.get(function (req, res) {
api.rtm.start();
});
app.use('/', router);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
console.log('Nestor listening on port ' + server.address().port);
});
| 'use strict';
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var api = require('./nestor/api');
var app = express();
app.use(bodyParser.json());
var router = express.Router();
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
api.rtm.start();
console.log('Nestor listening on port ' + server.address().port);
});
| Connect to RTM right away | Connect to RTM right away
| JavaScript | mit | maxdeviant/nestor |
e5e3e797753c954d1da82bf29adaf2d6bfacf945 | index.js | index.js | 'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
*/
exports.reporter = function (results, data, opts) {
console.log(arguments);
console.log('\n\n\n\n');
opts = opts || {};
opts.format = opts.format || 'checkstyle';
opts.filePath = opts.filePath || 'jshint.xml';
exports.opts = opts;
exports.xmlEmitter = loadFormatter(opts.format);
exports.out.push(exports.xmlEmitter.formatContent(results));
};
exports.writeFile = function () {
var outStream = fs.createWriteStream(exports.opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
outStream.write(exports.out.join('\n'));
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
| 'use strict';
var fs = require('fs');
function reset() {
exports.out = [];
exports.xmlEmitter = null;
exports.opts = {};
} reset();
/**
* Load a formatter
* @param {String} formatterPath
* @return
*/
function loadFormatter(formatterPath) {
return require('./lib/' + formatterPath + '_emitter');
}
/**
* Write out a XML file for the encountered results
* @param {Array} results
* @param {Array} data
* @param {Object} opts
*/
exports.reporter = function (results) {
exports.out.push(results);
};
exports.writeFile = function (opts) {
opts = opts || {};
opts.filePath = opts.filePath || 'jshint.xml';
opts.format = opts.format || 'checkstyle';
exports.xmlEmitter = loadFormatter(opts.format);
return function () {
if (!exports.out.length) {
reset();
return;
}
var outStream = fs.createWriteStream(opts.filePath);
outStream.write(exports.xmlEmitter.getHeader());
exports.out.forEach(function (item) {
outStream.write(exports.xmlEmitter.formatContent(item));
});
outStream.write(exports.out.join('\n'));
outStream.write(exports.xmlEmitter.getFooter());
reset();
};
};
| Restructure things to handle all-ok cases | Restructure things to handle all-ok cases
| JavaScript | mit | cleydsonjr/gulp-jshint-xml-file-reporter,lourenzo/gulp-jshint-xml-file-reporter |
63978e0a545bb6945964fe0b5c964ccb52a67624 | index.js | index.js | 'use strict';
var minimatch = require('minimatch');
var anymatch = function(criteria, string, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
if (arguments.length === 1) { return anymatch.bind(null, criteria); }
if (startIndex == null) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || minimatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion(string);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
| 'use strict';
var minimatch = require('minimatch');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
var string = Array.isArray(value) ? value[0] : value;
if (arguments.length === 1) { return anymatch.bind(null, criteria); }
if (startIndex == null) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || minimatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, Array.isArray(value) ? value : [value]);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
| Allow passing extra args to function matchers | Allow passing extra args to function matchers
| JavaScript | isc | es128/anymatch,floatdrop/anymatch |
f788366f2d9c21eb208bd53575210ed8da881b1b | index.js | index.js | /**
* Dispatcher prototype
*/
var dispatcher = Dispatcher.prototype;
/**
* Exports
*/
module.exports = Dispatcher;
/**
* Dispatcher
*
* @return {Object}
* @api public
*/
function Dispatcher() {
if (!(this instanceof Dispatcher)) return new Dispatcher;
this.callbacks = [];
};
/**
* Register a new store.
*
* dispatcher.register('update_course', callbackFunction);
*
* @param {String} action
* @param {Function} callback
* @api public
*/
dispatcher.register = function(action, callback) {
this.callbacks.push({
action: action,
callback: callback
});
};
/**
* Dispatch event to stores.
*
* dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'});
*
* @param {String} action
* @param {Object | Object[]} data
* @return {Function[]}
* @api public
*/
dispatcher.dispatch = function(action, data) {
this.getCallbacks(action)
.map(function(callback) {
return callback.call(callback, data);
});
};
/**
* Return registered callbacks.
*
* @param {String} action
* @return {Function[]}
* @api private
*/
dispatcher.getCallbacks = function(action) {
return this.callbacks
.filter(function(callback) {
return callback.action === action;
})
.map(function(callback) {
return callback.callback;
});
}; | /**
* Exports
*/
module.exports = Dispatcher;
/**
* Dispatcher prototype
*/
var dispatcher = Dispatcher.prototype;
/**
* Dispatcher
*
* @return {Object}
* @api public
*/
function Dispatcher() {
if (!(this instanceof Dispatcher)) return new Dispatcher;
this.callbacks = [];
};
/**
* Register a new store.
*
* dispatcher.register('update_course', callbackFunction);
*
* @param {String} action
* @param {Function} callback
* @api public
*/
dispatcher.register = function(action, callback) {
this.callbacks.push({
action: action,
callback: callback
});
};
/**
* Dispatch event to stores.
*
* dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'});
*
* @param {String} action
* @param {Object | Object[]} data
* @return {Function[]}
* @api public
*/
dispatcher.dispatch = function(action, data) {
this.getCallbacks(action)
.forEach(function(callback) {
callback.call(callback, data);
});
};
/**
* Return registered callbacks.
*
* @param {String} action
* @return {Function[]}
* @api private
*/
dispatcher.getCallbacks = function(action) {
return this.callbacks
.filter(function(callback) {
return callback.action === action;
})
.map(function(callback) {
return callback.callback;
});
}; | Remove last reference to array returns | Remove last reference to array returns
| JavaScript | mit | vebin/barracks,yoshuawuyts/barracks,yoshuawuyts/barracks |
f188b3030f519a90708a57b0b840ec7516d6c53b | index.js | index.js | var util = require('util');
GeometryBounds = function(bounds) {
this.xKey = "x";
this.yKey = "y";
this.bounds = [];
if(!bounds || !bounds[0]) return;
this.xKey = Object.keys(bounds[0])[0];
this.yKey = Object.keys(bounds[0])[1];
for(var b1 in bounds) {
var constructedBound = [];
var bound = bounds[b1];
for(var b2 in bound) {
var constructedPoint = [];
var point = bound[b2];
constructedPoint.push(parseFloat(point[this.xKey]));
constructedPoint.push(parseFloat(point[this.yKey]));
}
}
}
GeometryBounds.prototype.contains = function contains(dot) {
if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) {
return false;
}
var x = parseFloat(dot[this.xKey]);
var y = parseFloat(dot[this.yKey]);
for(var index in this.bounds) {
if(testInPolygon(this.bounds[index], x, y)) return true;
}
return false;
}
function testInPolygon(bound, x, y) {
var c = false;
for(i = 0, j = 1; i < bound.length; i++) {
}
}
exports.GeometryBounds = GeometryBounds;
| var util = require('util');
GeometryBounds = function(bounds) {
this.xKey = "x";
this.yKey = "y";
this.bounds = [];
if(!bounds || !bounds[0] || !bounds[0][0]) return;
this.xKey = Object.keys(bounds[0][0])[0];
this.yKey = Object.keys(bounds[0][0])[1];
for(var b1 in bounds) {
var constructedBound = [];
var bound = bounds[b1];
for(var b2 in bound) {
var constructedPoint = [];
var point = bound[b2];
constructedPoint.push(parseFloat(point[this.xKey]));
constructedPoint.push(parseFloat(point[this.yKey]));
}
}
}
GeometryBounds.prototype.contains = function contains(dot) {
if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) {
return false;
}
var x = parseFloat(dot[this.xKey]);
var y = parseFloat(dot[this.yKey]);
console.log(this.bounds);
for(var index in this.bounds) {
if(testInPolygon(this.bounds[index], x, y)) return true;
}
return false;
}
function testInPolygon(bound, x, y) {
var c = false;
console.log(bound);
for(i = 0, j = bound.length - 1; i < bound.length; j = i++) {
console.log(util.format("i = %d, j = %d", i, j));
}
}
exports.GeometryBounds = GeometryBounds;
| Fix in defining keys for x,y | Fix in defining keys for x,y
| JavaScript | mit | alandarev/node-geometry |
572907e88cc2acf6ad7482f8cee43cce03385d39 | library/CM/FormField/Text.js | library/CM/FormField/Text.js | /**
* @class CM_FormField_Text
* @extends CM_FormField_Abstract
*/
var CM_FormField_Text = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Text',
/** @type Boolean */
_skipTriggerChange: false,
events: {
'blur input': function() {
this.trigger('blur');
},
'focus input': function() {
this.trigger('focus');
}
},
/**
* @param {String} value
*/
setValue: function(value) {
this._skipTriggerChange = true;
this.$('input').val(value);
this._skipTriggerChange = false;
},
setFocus: function() {
this.$('input').focus();
},
enableTriggerChange: function() {
var self = this;
var $input = this.$('input');
var valueLast = $input.val();
var callback = function() {
var value = this.value;
if (value != valueLast) {
valueLast = value;
if (!self._skipTriggerChange) {
self.trigger('change');
}
}
};
// `propertychange` and `keyup` needed for IE9
$input.on('input propertychange keyup', callback);
}
});
| /**
* @class CM_FormField_Text
* @extends CM_FormField_Abstract
*/
var CM_FormField_Text = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Text',
/** @type Boolean */
_skipTriggerChange: false,
events: {
'blur input': function() {
this.trigger('blur');
},
'focus input': function() {
this.trigger('focus');
}
},
/**
* @param {String} value
*/
setValue: function(value) {
this._skipTriggerChange = true;
this.$('input').val(value);
this._skipTriggerChange = false;
},
setFocus: function() {
this.$('input').focus();
},
/**
* @return {Boolean}
*/
hasFocus: function() {
return this.$('input').is(':focus');
},
enableTriggerChange: function() {
var self = this;
var $input = this.$('input');
var valueLast = $input.val();
var callback = function() {
var value = this.value;
if (value != valueLast) {
valueLast = value;
if (!self._skipTriggerChange) {
self.trigger('change');
}
}
};
// `propertychange` and `keyup` needed for IE9
$input.on('input propertychange keyup', callback);
}
});
| Add hasFocus() for text formField | Add hasFocus() for text formField
| JavaScript | mit | vogdb/cm,fvovan/CM,tomaszdurka/CM,zazabe/cm,fauvel/CM,cargomedia/CM,mariansollmann/CM,mariansollmann/CM,njam/CM,vogdb/cm,christopheschwyzer/CM,fvovan/CM,fauvel/CM,tomaszdurka/CM,cargomedia/CM,alexispeter/CM,fvovan/CM,alexispeter/CM,zazabe/cm,fauvel/CM,fvovan/CM,cargomedia/CM,njam/CM,tomaszdurka/CM,mariansollmann/CM,vogdb/cm,mariansollmann/CM,cargomedia/CM,njam/CM,njam/CM,christopheschwyzer/CM,christopheschwyzer/CM,vogdb/cm,zazabe/cm,njam/CM,fauvel/CM,alexispeter/CM,tomaszdurka/CM,tomaszdurka/CM,vogdb/cm,christopheschwyzer/CM,fauvel/CM,alexispeter/CM,zazabe/cm |
ff3e075eba9f87013879c889a8d70e119be04e13 | lib/stack/Builder.js | lib/stack/Builder.js | /**
* Builder.js
*
* @author: Harish Anchu <harishanchu@gmail.com>
* @copyright Copyright (c) 2015-2016, QuorraJS.
* @license See LICENSE.txt
*/
var StackedHttpKernel = require('./StackedHttpKernel');
function Builder() {
/**
* Stores middleware classes
*
* @type {Array}
* @protected
*/
this.__specs = [];
}
Builder.prototype.push = function(spec) {
if (typeof spec != 'function') {
throw new Error("Spec error");
}
this.__specs.push(spec);
return this;
};
Builder.prototype.resolve = function(app)
{
var next = app;
var middlewares = [app];
var key;
var spec;
for(key = this.__specs.length -1; key >= 0; key--) {
spec = this.__specs[key];
next = new spec(app, next);
middlewares.unshift(next);
}
return new StackedHttpKernel(next, middlewares);
};
module.exports = Builder; | /**
* Builder.js
*
* @author: Harish Anchu <harishanchu@gmail.com>
* @copyright Copyright (c) 2015-2016, QuorraJS.
* @license See LICENSE.txt
*/
var StackedHttpKernel = require('./StackedHttpKernel');
function Builder() {
/**
* Stores middleware classes
*
* @type {Array}
* @protected
*/
this.__specs = [];
}
Builder.prototype.push = function(spec) {
if (typeof spec != 'function') {
throw new Error("Spec error");
}
this.__specs.push(spec);
return this;
};
Builder.prototype.resolve = function(app)
{
var next = app;
var key;
var spec;
for(key = this.__specs.length -1; key >= 0; key--) {
spec = this.__specs[key];
next = new spec(app, next);
}
return new StackedHttpKernel(next);
};
module.exports = Builder; | Stop passing middlewares array to stack | Stop passing middlewares array to stack
| JavaScript | mit | quorrajs/Positron,quorrajs/Positron |
1142407be4e1884fc79188680f2b8649f19d887f | test/unit/unit.js | test/unit/unit.js | 'use strict';
require.config({
baseUrl: '../lib',
paths: {
'test': '..',
'forge': 'forge.min'
},
shim: {
sinon: {
exports: 'sinon',
}
}
});
// add function.bind polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof FNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
mocha.setup('bdd');
require(['test/unit/browserbox-test', 'test/unit/browserbox-imap-test'], function() {
(window.mochaPhantomJS || window.mocha).run();
}); | 'use strict';
require.config({
baseUrl: '../lib',
paths: {
'test': '..',
'forge': 'forge.min'
}
});
// add function.bind polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
FNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof FNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
FNOP.prototype = this.prototype;
fBound.prototype = new FNOP();
return fBound;
};
}
mocha.setup('bdd');
require(['test/unit/browserbox-test', 'test/unit/browserbox-imap-test'], function() {
(window.mochaPhantomJS || window.mocha).run();
}); | Remove useless sinon require shim | Remove useless sinon require shim
| JavaScript | mit | dopry/browserbox,emailjs/emailjs-imap-client,nifgraup/browserbox,ltgorm/emailjs-imap-client,dopry/browserbox,emailjs/emailjs-imap-client,whiteout-io/browserbox,ltgorm/emailjs-imap-client |
6e5a575e2bab2ce9b1cb83182a791fe8d1995558 | test/utils-test.js | test/utils-test.js | describe('getFolders()', function() {
it('should return the correct list of folders', function() {
var objects = [
{ Key: '/' },
{ Key: 'test/' },
{ Key: 'test/test/' },
{ Key: 'test/a/b' },
{ Key: 'test' },
];
chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/', 'test/', 'test/test/', 'test/a/']);
});
it('should return the root folder if the array is empty', function() {
var objects = [];
chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/']);
});
});
describe('newFolder()', function() {
before(function(done) {
sinon
.stub(dodgercms.s3, 'putObject')
.yields(null, 'index');
done();
});
after(function(done) {
dodgercms.s3.putObject.restore();
done();
});
it('should match the given key', function(done) {
dodgercms.utils.newFolder('index', 'dataBucket','siteBucket', function(err, key) {
if (err) {
return done(err);
}
chai.assert(key === 'index');
done();
});
});
}); | describe('getFolders()', function() {
it('should return the correct list of folders', function() {
var objects = [
{ Key: '/' },
{ Key: 'test/' },
{ Key: 'test/test/' },
{ Key: 'test/a/b' },
{ Key: 'test' },
];
chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/', 'test/', 'test/test/', 'test/a/']);
});
it('should return the root folder if the array is empty', function() {
var objects = [];
chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/']);
});
});
describe('newFolder()', function() {
before(function(done) {
sinon
.stub(dodgercms.s3, 'putObject')
.yields(null, 'index');
done();
});
after(function(done) {
dodgercms.s3.putObject.restore();
done();
});
it('should match the given key', function(done) {
dodgercms.utils.newFolder('index', 'dataBucket','siteBucket', function(err, key) {
if (err) {
return done(err);
}
chai.assert(key === 'index');
done();
});
});
});
describe('isFolder()', function() {
it('should return true for root', function() {
chai.assert(dodgercms.utils.isFolder('/'));
});
it('should return true for folder', function() {
chai.assert(dodgercms.utils.isFolder('/folder/'));
});
it('should return true for nested folder', function() {
chai.assert(dodgercms.utils.isFolder('/folder/test/folder/'));
});
}); | Add test cases for the utils | Add test cases for the utils
| JavaScript | mit | ChrisZieba/dodgercms,ChrisZieba/dodgercms,etopian/dodgercms,etopian/dodgercms |
ed79ebfb2f092f386a2b6798ebbbd21dd2f68fbb | client/src/components/Header/Header.js | client/src/components/Header/Header.js | import React from 'react';
import { NavLink } from 'react-router-dom';
import './style.css';
const Header = props => {
const { isAdmin, loggedIn } = props;
return (
<div>
<div className="navbar">
<div className="navbar-brand">
<NavLink to="/">
<img src="http://via.placeholder.com/185x80" alt="Logo" />
</NavLink>
<NavLink
activeClassName="selected"
className="navbar-item"
to="/jobs"
>
Explore Jobs
</NavLink>
{isAdmin && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/admin"
>
Admin Panel
</NavLink>
)}
{!loggedIn && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/login"
>
Log in
</NavLink>
)}
{!loggedIn && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/join"
>
Join
</NavLink>
)}
</div>
</div>
</div>
);
};
export default Header;
| import React from 'react';
import { NavLink } from 'react-router-dom';
import './style.css';
const Header = props => {
const { isAdmin, loggedIn } = props;
return (
<div>
<div className="navbar">
<div className="navbar-brand">
<NavLink to="/">
<img src="http://via.placeholder.com/185x80" alt="Logo" />
</NavLink>
<NavLink
activeClassName="selected"
className="navbar-item"
to="/jobs"
>
Explore Jobs
</NavLink>
{isAdmin && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/admin"
>
Admin Panel
</NavLink>
)}
{!loggedIn && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/login"
>
Log in
</NavLink>
)}
{!loggedIn && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/join"
>
Join
</NavLink>
)}
{loggedIn && (
<NavLink
activeClassName="selected"
className="navbar-item"
to="/bookmarks"
>
My saved jobs
</NavLink>
)}
</div>
</div>
</div>
);
};
export default Header;
| Add navbar link to /bookmarks | Add navbar link to /bookmarks
| JavaScript | mit | jenovs/bears-team-14,jenovs/bears-team-14 |
4dc707df767bd7d4ace82747a9b478a29b7eda2e | config/log4js.js | config/log4js.js | var log4js = require('log4js');
log4js.configure({
appenders: [
{
'type': 'file',
'filename': 'logs/mymap.log',
'category': ['mymap', 'console'],
'maxLogSize': 5242880,
'backups': 10
},
{
type: 'console'
}
],
replaceConsole: true
});
exports.getLogger = function() {
return log4js.getLogger('mymap');
} | var log4js = require('log4js'),
fs = require('fs');
configure();
exports.getLogger = function() {
return log4js.getLogger('mymap');
}
function configure() {
if(!fs.existsSync('logs')) {
fs.mkdirSync('logs');
}
log4js.configure({
appenders: [
{
'type': 'file',
'filename': 'logs/mymap.log',
'category': ['mymap', 'console'],
'maxLogSize': 5242880,
'backups': 10
},
{
type: 'console'
}
],
replaceConsole: true
});
} | Create logs dir if necessary | Create logs dir if necessary
| JavaScript | mit | k4v1cs/mymap |
cf1b6a0f7df449b834d1fecca64a774a6f768593 | DataAccess/Meets.js | DataAccess/Meets.js | const MySql = require("./MySql.js");
class Meet{
constructor(obj){
Object.keys(obj).forEach(k=>this[k]=obj[k]);
}
asMarkdown(){
return `*${this.post_title}* ${this.meet_start_time}\n_${this.guid}_`;
}
}
Meet.fromObjArray = function(objArray){
return objArray.map(o=>new Meet(o));
};
function getAllMeets(){
return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`)
.then(results=>Meet.fromObjArray(results.results));
}
function getUpcomingMeets(){
return MySql.query(`
SELECT meta_value AS meet_start_time, wp_posts.*
FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID
WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE()
`).then(results=>Meet.fromObjArray(results.results));
}
module.exports = {getAllMeets,getUpcomingMeets};
| const MySql = require("./MySql.js");
const entities = require("entities");
class Meet{
constructor(obj){
Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k]));
}
asMarkdown(){
return `*${this.post_title}* ${this.meet_start_time}\n${this.guid}`;
}
}
Meet.fromObjArray = function(objArray){
return objArray.map(o=>new Meet(o));
};
function getAllMeets(){
return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`)
.then(results=>Meet.fromObjArray(results.results));
}
function getUpcomingMeets(){
return MySql.query(`
SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.*
FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID
WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE()
`).then(results=>Meet.fromObjArray(results.results));
}
module.exports = {getAllMeets,getUpcomingMeets};
| FIX broken markdown and entities | FIX broken markdown and entities
| JavaScript | mit | severnbronies/Sail |
703714a2b5d527aa87cd996cbc07c9f3fab3a55d | emcee.js | emcee.js | module.exports = exports = MC
function MC () {
this._loading = 0
this.models = {}
}
var modelLoaders = {}
MC.model = function (name, loader) {
modelLoaders[name] = loader
return MC
}
MC.prototype.load = function (name) {
if (!modelLoaders[name]) {
throw new Error('Unknown model: ' + name)
}
if (this.error) return
var a = new Array(arguments.length)
for (var i = 1; i < arguments.length; i ++) {
a[i-1] = arguments[i]
}
a[i-1] = next.bind(this)
this._loading ++
modelLoaders[name].apply(this, a)
function next (er, data) {
if (this.error) return
this.error = er
this.models[name] = data
this._loading --
if (er || this._loading === 0) {
this.ondone(this.error, this.models)
}
}
}
MC.prototype.end = function (cb) {
this.ondone = cb
if (this._loading === 0) this.ondone(this.error, this.models)
}
| module.exports = exports = MC
function MC () {
this.loading = 0
this.models = {}
this.ondone = function () {}
}
var modelLoaders = {}
MC.model = function (name, loader) {
if (MC.prototype.hasOwnProperty(name) ||
name === 'loading' ||
name === 'ondone' ||
name === 'error' ||
name === 'models') {
throw new Error('invalid model name: ' + name)
}
modelLoaders[name] = loader
return MC
}
MC.prototype.load = function (name) {
if (!modelLoaders[name]) {
throw new Error('Unknown model: ' + name)
}
if (this.error) return
var a = new Array(arguments.length)
for (var i = 1; i < arguments.length; i ++) {
a[i-1] = arguments[i]
}
a[i-1] = next.bind(this)
this.loading ++
modelLoaders[name].apply(this, a)
function next (er, data) {
if (this.error) return
this.error = er
this[name] = this.models[name] = data
this.loading --
if ((er || this.loading === 0) && this.ondone) {
this.ondone(this.error, this.models)
}
}
}
MC.prototype.end = function (cb) {
this.ondone = cb
if (this.loading === 0 || this.error) {
this.ondone(this.error, this.models)
}
}
| Put the model results right on the MC object | Put the model results right on the MC object
| JavaScript | isc | isaacs/emcee |
c2d0f37353c6ea1daf5f10c149d01c6e667c3524 | fetch.js | fetch.js | const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
// this is from the env of npm, not node
const nodePath = process.env.NODE;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');
if (!fs.existsSync(tmpfile)) {
exec('"'+nodePath+'" --v8-options', function (execErr, result) {
var flags;
if (execErr) {
throw new Error(execErr);
} else {
flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
return match.substring(2);
});
fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
function (writeErr) {
if (writeErr) {
throw new Error(writeErr);
} else {
console.log('flags for v8 '+version+' cached.');
}
}
);
}
});
}
module.exports = require.bind(null, tmpfile);
| const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;
const nodePath = process.execPath;
const version = process.versions.v8;
const tmpfile = path.join(__dirname, version+'.flags.json');
if (!fs.existsSync(tmpfile)) {
exec('"'+nodePath+'" --v8-options', function (execErr, result) {
var flags;
if (execErr) {
throw new Error(execErr);
} else {
flags = result.match(/\s\s--(\w+)/gm).map(function (match) {
return match.substring(2);
});
fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' },
function (writeErr) {
if (writeErr) {
throw new Error(writeErr);
} else {
console.log('flags for v8 '+version+' cached.');
}
}
);
}
});
}
module.exports = require.bind(null, tmpfile);
| Use process.execPath to find node executable on Windows | Fix: Use process.execPath to find node executable on Windows
| JavaScript | mit | js-cli/js-v8flags,tkellen/js-v8flags |
d6484cd7f2cb24f7c0596f363c983c6c2a71057a | tools/scripts/property-regex.js | tools/scripts/property-regex.js | const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
| const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
// This intentially includes only the binary properties required by UTS 18 Level 1 RL1.2 for Unicode
// regex support, minus `Assigned` which has special handling since it is the inverse of Unicode
// category `Unassigned` (`Cn`). To include all binary properties, change this to:
// `const properties = require(`${unicodeVersion}`).Binary_Property;`
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
| Add comment about level 1 Unicode properties | Add comment about level 1 Unicode properties
| JavaScript | mit | GerHobbelt/xregexp,slevithan/xregexp,slevithan/xregexp,slevithan/XRegExp,slevithan/xregexp,GerHobbelt/xregexp,GerHobbelt/xregexp,slevithan/XRegExp |
16f58e1d165b0d683fd44535ac6e8f6cb12fdd8c | popit-hosting/app.js | popit-hosting/app.js |
/**
* Module dependencies.
*/
var express = require('express'),
expressHogan = require('express-hogan.js'),
mongoose = require('mongoose'),
nodemailer = require('nodemailer');
// Connect to the default database
mongoose.connect('mongodb://localhost/all');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.register('.txt', expressHogan);
app.register('.html', expressHogan);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(express.logger({ format: ':method :status :url' }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.nodemailer_transport = nodemailer.createTransport("Sendmail");
// Routes
require('./routes').route(app);
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
|
/**
* Module dependencies.
*/
var express = require('express'),
expressHogan = require('express-hogan.js'),
mongoose = require('mongoose'),
nodemailer = require('nodemailer');
// Connect to the default database
mongoose.connect('mongodb://localhost/all');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.use(express.logger('dev'));
app.set('views', __dirname + '/views');
app.register('.txt', expressHogan);
app.register('.html', expressHogan);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
app.nodemailer_transport = nodemailer.createTransport("Sendmail");
// Routes
require('./routes').route(app);
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
| Add logging to all requests (needed to be at start of configure, perhaps a template rendering issue?) | Add logging to all requests (needed to be at start of configure, perhaps a template rendering issue?)
| JavaScript | agpl-3.0 | maxogden/popit,mysociety/popit,mysociety/popit,openstate/popit,mysociety/popit,openstate/popit,maxogden/popit,mysociety/popit,mysociety/popit,Sinar/popit,openstate/popit,Sinar/popit,Sinar/popit,Sinar/popit,openstate/popit |
a8514306b93f1311c6052cfe6440e84a1da1cca2 | scripts/generators.js | scripts/generators.js | var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage = 10;
}
var paginationDir = config.pagination_dir || 'page';
var result = [];
_.each(categories, function(data, title) {
_.each(data, function(data, lang) {
result = result.concat(
pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, {
perPage: perPage,
layout: ['category', 'archive', 'index'],
format: paginationDir + '/%d/',
data: {
lang: lang,
title: data.name,
category: data.category
}
})
);
});
});
return result;
});
function getCategoryByName(categories, name) {
return categories.toArray().filter(function(category){
return category.name == name;
})[0];
}
| var pagination = require('hexo-pagination');
var _ = require('lodash');
hexo.extend.generator.register('category', function(locals){
var config = this.config;
var categories = locals.data.categories;
if (config.category_generator) {
var perPage = config.category_generator.per_page;
} else {
var perPage = 10;
}
var paginationDir = config.pagination_dir || 'page';
var result = [];
_.each(categories, function(category, title) {
_.each(category, function(data, lang) {
result = result.concat(
pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, {
perPage: perPage,
layout: ['category', 'archive', 'index'],
format: paginationDir + '/%d/',
data: {
lang: lang,
title: data.name,
category: data.category,
alternates: getAlternateLangs(category, lang)
}
})
);
});
});
return result;
});
function getCategoryByName(categories, name) {
return categories.toArray().filter(function(category){
return category.name == name;
})[0];
}
function getAlternateLangs(category, currentLang) {
var result = [];
_.each(category, function(data, lang) {
if (currentLang != lang) {
result.push({
lang: lang,
path: lang + '/' + data.slug
});
}
});
return result;
}
| Add alternate language categories in generator | Add alternate language categories in generator
This will populate the `alternates` variable that will be available to
use in the layout files. The current language is not included for
obvious reasons.
Built from a10e346a1e29ca8ed1cb71666f8bf7b7d2fd8239.
| JavaScript | mit | ahaasler/hexo-theme-colos,ahaasler/hexo-theme-colos |
03bd8cd920c7d2d26e93da9e690cef5a01b710bf | core/util/DefaultKeystoneConfiguration.js | core/util/DefaultKeystoneConfiguration.js | /**
* DefaultKeystoneConfiguration contains the default settings for keystone.
* @class DefaultKeystoneConfiguration
* @param {Theme} theme
* @constructor
*
*/
module.exports = function DefaultKeystoneConfiguration(theme) {
return {
'name': process.env.DOMAIN || 'Estore',
'brand': process.env.DOMAIN || 'Estore',
'auto update': process.env.KEYSTONE_AUTO_UPDATE || true,
'session': true,
'session store': 'mongo',
'auth': true,
'cookie secret': process.env.COOKIE_SECRET,
'view engine': 'html',
'views': theme.getTemplatePath(),
'static': theme.getStaticPath(),
'emails': theme.getEmailPath(),
'port': process.env.PORT || 3000,
'mongo': process.env.MONGO_URI,
};
};
| /**
* DefaultKeystoneConfiguration contains the default settings for keystone.
* @class DefaultKeystoneConfiguration
* @param {Theme} theme
* @constructor
*
*/
module.exports = function DefaultKeystoneConfiguration(theme) {
return {
'name': process.env.DOMAIN || 'Estore',
'brand': process.env.DOMAIN || 'Estore',
'auto update': (process.env.KEYSTONE_AUTO_UPDATE === true) ? true : false,
'session': true,
'session store': 'mongo',
'auth': true,
'cookie secret': process.env.COOKIE_SECRET,
'view engine': 'html',
'views': theme.getTemplatePath(),
'static': theme.getStaticPath(),
'emails': theme.getEmailPath(),
'port': process.env.PORT || 3000,
'mongo': process.env.MONGO_URI,
};
};
| Use an explicit check for auto update override. | Use an explicit check for auto update override.
| JavaScript | mit | stunjiturner/estorejs,stunjiturner/estorejs,quenktechnologies/estorejs |
70b429733a5a9be44be5d21fb2703b27068552b4 | test-helpers/init.js | test-helpers/init.js | // First require your DOM emulation file (see below)
require('./emulateDom.js');
import db_config from '../knexfile';
let exec_env = process.env.DB_ENV || 'test';
global.$dbConfig = db_config[exec_env];
process.env.NODE_ENV = 'test';
| global.Promise = require('bluebird')
global.Promise.onPossiblyUnhandledRejection((e) => { throw e; });
global.Promise.config({
// Enable warnings.
warnings: false,
// Enable long stack traces.
longStackTraces: true,
// Enable cancellation.
cancellation: true
});
// First require your DOM emulation file (see below)
require('./emulateDom.js');
import db_config from '../knexfile';
let exec_env = process.env.DB_ENV || 'test';
global.$dbConfig = db_config[exec_env];
process.env.NODE_ENV = 'test';
| Use bluebird for debuggable promises in tests | Use bluebird for debuggable promises in tests
| JavaScript | agpl-3.0 | Lokiedu/libertysoil-site,Lokiedu/libertysoil-site |
1528ba519169e493fac28c21d6c483187d24bc36 | test/markup/index.js | test/markup/index.js | 'use strict';
var _ = require('lodash');
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var glob = require('glob');
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
var filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
_.each(filenames, function(filename) {
var testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it(`should markup ${testName}`, function(done) {
var sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
var actual = hljs.highlight(language, source).value;
actual.trim().should.equal(expected.trim());
done();
});
});
});
});
}
describe('hljs.highlight()', function() {
var languages = fs.readdirSync(utility.buildPath('markup'));
_.each(languages, testLanguage, this);
});
| 'use strict';
var _ = require('lodash');
var bluebird = require('bluebird');
var fs = bluebird.promisifyAll(require('fs'));
var glob = require('glob');
var hljs = require('../../build');
var path = require('path');
var utility = require('../utility');
function testLanguage(language) {
describe(language, function() {
var filePath = utility.buildPath('markup', language, '*.expect.txt'),
filenames = glob.sync(filePath);
_.each(filenames, function(filename) {
var testName = path.basename(filename, '.expect.txt'),
sourceName = filename.replace(/\.expect/, '');
it(`should markup ${testName}`, function(done) {
var sourceFile = fs.readFileAsync(sourceName, 'utf-8'),
expectedFile = fs.readFileAsync(filename, 'utf-8');
bluebird.join(sourceFile, expectedFile, function(source, expected) {
var actual = hljs.highlight(language, source).value;
actual.trim().should.equal(expected.trim());
done();
});
});
});
});
}
describe('hljs.highlight()', function() {
var markupPath = utility.buildPath('markup');
return fs.readdirAsync(markupPath).each(testLanguage);
});
| Change synchronous readdir to a promise | Change synchronous readdir to a promise
| JavaScript | bsd-3-clause | bluepichu/highlight.js,carlokok/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,MakeNowJust/highlight.js,palmin/highlight.js,teambition/highlight.js,palmin/highlight.js,Sannis/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,tenbits/highlight.js,Sannis/highlight.js,highlightjs/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,palmin/highlight.js,teambition/highlight.js,teambition/highlight.js,sourrust/highlight.js,lead-auth/highlight.js,tenbits/highlight.js,highlightjs/highlight.js,highlightjs/highlight.js,MakeNowJust/highlight.js,dbkaplun/highlight.js,dbkaplun/highlight.js,aurusov/highlight.js,tenbits/highlight.js,StanislawSwierc/highlight.js,dbkaplun/highlight.js,StanislawSwierc/highlight.js,Sannis/highlight.js,MakeNowJust/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,aurusov/highlight.js,carlokok/highlight.js |
34d660f07f603b9017fe2dcd88518c0a5c175503 | test/onerror-test.js | test/onerror-test.js | var assert = buster.referee.assert;
buster.testCase("Call onerror", {
setUp: function () {
$ = {};
$.post = this.spy();
initErrorHandler("/error", "localhost");
},
"exception within the system": function () {
window.onerror('error message', 'http://localhost/test.js', 11);
assert.isTrue($.post.called);
},
"error within the system": function (done) {
setTimeout(function() {
// throw some real-life exception
not_defined.not_defined();
}, 10);
setTimeout(function() {
assert.isTrue($.post.called);
done();
}, 100);
},
"error outside the system": function() {
window.onerror('error message', 'http://example.com/test.js', 11);
assert.isFalse($.post.called);
},
"error from unknown source": function() {
window.onerror('error message', 'http://localhost/foo', 11);
assert.isFalse($.post.called);
}
}); | var assert = buster.referee.assert;
var hostname = location.hostname;
buster.testCase("Call onerror", {
setUp: function () {
$ = {};
$.post = this.spy();
initErrorHandler("/error", hostname);
},
"exception within the system": function () {
window.onerror('error message', 'http://' + hostname + '/test.js', 11);
assert.isTrue($.post.called);
},
"error within the system": function (done) {
setTimeout(function() {
// throw some real-life exception
not_defined.not_defined();
}, 10);
setTimeout(function() {
assert.isTrue($.post.called);
done();
}, 100);
},
"error outside the system": function() {
window.onerror('error message', 'http://example.com/test.js', 11);
assert.isFalse($.post.called);
},
"error from unknown source": function() {
window.onerror('error message', 'http://' + hostname + '/foo', 11);
assert.isFalse($.post.called);
}
}); | Make the tests work for remote test clients. | Make the tests work for remote test clients.
| JavaScript | mit | lucho-yankov/window.onerror |
2b7213f17e1b6206329bbc02693053b04e52669a | this.js | this.js |
console.log(this) //contexto global
console.log(this === window) //true
var developer = {
name : 'Erik',
lastName : 'Ochoa',
isAdult : true,
completeName: function(){
return this.name + this.lastName
}
}
console.log(developer.name) // Erik
console.log(developer.lastName) // Ochoa
console.log(developer.isAdult) // true
//We call a function that is stored as a property of an object becoming a method
console.log(developer.completeName()) // ErikOchoa
|
console.log(this) //contexto global
console.log(this === window) //true
var developer = {
name : 'Erik',
lastName : 'Ochoa',
isAdult : true,
get completeName() {
return this.name + this.lastName
}
}
console.log(developer.name) // Erik
console.log(developer.lastName) // Ochoa
console.log(developer.isAdult) // true
console.log(developer.completeName) // ErikOchoa
| Use getter to call completeName as a property | Use getter to call completeName as a property
| JavaScript | mit | Elyager/this-in-depth,Elyager/this-in-depth |
3a04f4e532a7dbba3d560866e9e93b305ae3bf17 | test/prerequisite.js | test/prerequisite.js | describe('Prerequisites', () => {
describe('Call the same resource with both http client and iframe', () => {
it('http headers should be less or equal than iframe ones', () => {
browser.url('/');
browser.leftClick('.httpCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length;
browser.leftClick('.iframeCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length;
expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount);
expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount);
});
})
});
| describe('Prerequisites', () => {
describe('Call the same resource with both http client and iframe', () => {
it('http headers should be less or equal than iframe ones', () => {
browser.url('/');
browser.leftClick('.httpCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length;
browser.refresh();
browser.leftClick('.iframeCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length;
expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount);
expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount);
});
})
});
| Refresh the page between a test and another | Refresh the page between a test and another
| JavaScript | mit | apiaryio/apiary-console-seed,apiaryio/apiary-console-seed,apiaryio/console-proxy,apiaryio/console-proxy |
df378b792ed24f04915783f803cc3355b69e6129 | APE_Server/APScripts/framework/cmd_event.js | APE_Server/APScripts/framework/cmd_event.js | /*
* Command to handle APS events
*/
Ape.registerCmd("event", true, function(params, info) {
if(params.multi){
var recipient = Ape.getChannelByPubid(params.pipe);
}else{
var recipient = Ape.getUserByPubid(params.pipe);
}
if(recipient){
if(!!params.sync){
info.sendResponse("SYNC", {
data: params.data,
event: params.event,
chanid: params.pipe
});
}
delete params.sync;
recipient.sendEvent(params, {from: info.user.pipe});
}
return 1;
}); | /*
* Command to handle APS events
*/
Ape.registerCmd("event", true, function(params, info) {
if(params.multi){
var recipient = Ape.getChannelByPubid(params.pipe);
}else{
var recipient = Ape.getUserByPubid(params.pipe);
}
if(recipient){
if(!!params.sync){
info.sendResponse("SYNC", {
data: params.data,
event: params.event,
chanid: params.pipe
});
}
delete params.sync;
recipient.sendEvent(params, {from: info.user.pipe});
return 1;
}
return ["425", "UNKNOWN_RECIPIENT"];
}); | Send error 425 if the recipient of an event is not found | Send error 425 if the recipient of an event is not found
| JavaScript | mit | ptejada/ApePubSub,ptejada/ApePubSub |
35b55bec4912c6f14351422bc6e6c6fecfd5bfe5 | server/auth/index.js | server/auth/index.js | const logger = require('../logging');
const passport = require('passport');
const { setupOIDC } = require('./oidc');
const getUserById = require('../models/user.accessors').getUserById;
require('./providers/ow4.js');
module.exports = async (app) => {
passport.serializeUser((user, done) => {
logger.silly('Serializing user', { userId: user.id });
done(null, user.id);
});
passport.deserializeUser((id, done) => {
logger.silly('Deserializing user', { userId: id });
done(null, () => getUserById(id));
});
app.use(passport.initialize());
app.use(passport.session());
app.get('/login', passport.authenticate('oauth2', { successReturnToOrRedirect: '/' }));
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.get('/auth', passport.authenticate('oauth2', { callback: true }), (req, res) => {
res.redirect('/');
});
if (process.env.SDF_OIDC && process.env.SDF_OIDC.toLowerCase() === 'true') {
const success = await setupOIDC();
if (success) {
app.get('/openid-login', passport.authenticate('oidc'));
app.get('/openid-auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' }));
}
return app;
}
return app;
};
| const logger = require('../logging');
const passport = require('passport');
const { setupOIDC } = require('./oidc');
const getUserById = require('../models/user.accessors').getUserById;
require('./providers/ow4.js');
module.exports = async (app) => {
await setupOIDC();
passport.serializeUser((user, done) => {
logger.silly('Serializing user', { userId: user.id });
done(null, user.id);
});
passport.deserializeUser((id, done) => {
logger.silly('Deserializing user', { userId: id });
done(null, () => getUserById(id));
});
app.use(passport.initialize());
app.use(passport.session());
app.get('/login', passport.authenticate('oidc'));
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' }));
return app;
};
| Make OIDC be default auth mechanism | Make OIDC be default auth mechanism
| JavaScript | mit | dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta |
5e44054ad4223d32b53c2312ecd5798b0e114548 | main.js | main.js |
exports.AgGridAurelia = require('./lib/agGridAurelia').AgGridAurelia;
exports.AgGridColumn = require('./lib/agGridColumn').AgGridColumn;
exports.AgCellTemplate = require('./lib/agTemplate').AgCellTemplate;
exports.AgEditorTemplate = require('./lib/agTemplate').AgEditorTemplate;
exports.AgFilterTemplate = require('./lib/agTemplate').AgFilterTemplate;
exports.AureliaCellRendererComponent = require('./lib/aureliaCellRendererComponent').AureliaCellRendererComponent;
exports.AureliaComponentFactory = require('./lib/aureliaComponentFactory').AureliaComponentFactory;
exports.AureliaFrameworkFactory = require('./lib/aureliaFrameworkFactory').AureliaFrameworkFactory;
exports.BaseAureliaEditor = require('./lib/editorViewModels').BaseAureliaEditor;
function configure(config) {
config.globalResources(
'./lib/agGridAurelia',
'./lib/agGridColumn',
'./lib/agTemplate'
);
}
exports.configure = configure;
|
exports.AgGridAurelia = require('./lib/agGridAurelia').AgGridAurelia;
exports.AgGridColumn = require('./lib/agGridColumn').AgGridColumn;
exports.AgCellTemplate = require('./lib/agTemplate').AgCellTemplate;
exports.AgEditorTemplate = require('./lib/agTemplate').AgEditorTemplate;
exports.AgFullWidthRowTemplate = require('./lib/agTemplate').AgFullWidthRowTemplate;
exports.AgFilterTemplate = require('./lib/agTemplate').AgFilterTemplate;
exports.AureliaCellRendererComponent = require('./lib/aureliaCellRendererComponent').AureliaCellRendererComponent;
exports.AureliaComponentFactory = require('./lib/aureliaComponentFactory').AureliaComponentFactory;
exports.AureliaFrameworkFactory = require('./lib/aureliaFrameworkFactory').AureliaFrameworkFactory;
exports.BaseAureliaEditor = require('./lib/editorViewModels').BaseAureliaEditor;
function configure(config) {
config.globalResources(
'./lib/agGridAurelia',
'./lib/agGridColumn',
'./lib/agTemplate'
);
}
exports.configure = configure;
| Add FullWidth row template to exports | Add FullWidth row template to exports
| JavaScript | mit | ceolter/ag-grid,ceolter/angular-grid,ceolter/angular-grid,ceolter/ag-grid |
272e86c5f7e2d661fff0914abd612f5aef4ee6b1 | demo/Progress.js | demo/Progress.js | import React, {Component} from 'react';
import Style from 'styled-components';
class Progress extends Component {
state = {progress: 0};
componentDidMount() {
this.props.emitter.on(({progress}) => {
if (this.state.progress !== progress) {
this.setState({progress: progress});
}
});
}
Bar = Style.div`
position:absolute;
left: 0;
top: 0;
height: 2px;
background-color: #337ab7;
transition: all 0.4s ease-in-out;
`;
render() {
return <this.Bar style={{width: `${this.state.progress}%`}} />;
}
}
export default Progress;
| import React, {Component} from 'react';
import Style from 'styled-components';
class Progress extends Component {
state = {progress: 0};
componentDidMount() {
this.props.emitter.on(({progress}) => {
if (this.state.progress !== progress) {
this.setState({progress: progress});
}
});
}
Bar = Style.div`
position:absolute;
left: 0;
top: 0;
height: 2px;
background-color: #337ab7;
`;
render() {
return <this.Bar style={{width: `${this.state.progress}%`}} />;
}
}
export default Progress;
| Remove css transition from progress bar | Remove css transition from progress bar
| JavaScript | mit | chitchu/react-mosaic,chitchu/react-mosaic |
bdbeb4706abdf570ac5a926a2ed156a67909fac6 | template/_copyright.js | template/_copyright.js | /*
* Raven.js @VERSION
* https://github.com/getsentry/raven-js
*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2013 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
/*! Raven.js @VERSION | github.com/getsentry/raven-js */
| /*! Raven.js @VERSION | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2013 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
| Build the copyright header slightly less dumb | Build the copyright header slightly less dumb
| JavaScript | bsd-2-clause | grelas/raven-js,Mappy/raven-js,malandrew/raven-js,chrisirhc/raven-js,eaglesjava/raven-js,vladikoff/raven-js,malandrew/raven-js,iodine/raven-js,janmisek/raven-js,chrisirhc/raven-js,housinghq/main-raven-js,housinghq/main-raven-js,getsentry/raven-js,iodine/raven-js,samgiles/raven-js,PureBilling/raven-js,vladikoff/raven-js,danse/raven-js,benoitg/raven-js,clara-labs/raven-js,hussfelt/raven-js,samgiles/raven-js,benoitg/raven-js,getsentry/raven-js,getsentry/raven-js,housinghq/main-raven-js,janmisek/raven-js,hussfelt/raven-js,grelas/raven-js,clara-labs/raven-js,getsentry/raven-js,danse/raven-js,PureBilling/raven-js,Mappy/raven-js,Mappy/raven-js,eaglesjava/raven-js |
632cdba5fab5df66cbbc98bb7168c13e9b5eb81b | packages/mjml-spacer/src/index.js | packages/mjml-spacer/src/index.js | import { MJMLElement } from 'mjml-core'
import React, { Component } from 'react'
const tagName = 'mj-spacer'
const parentTag = ['mj-column', 'mj-hero-content']
const selfClosingTag = true
const defaultMJMLDefinition = {
attributes: {
'align': null,
'container-background-color': null,
'height': '20px',
'padding-bottom': null,
'padding-left': null,
'padding-right': null,
'padding-top': null,
'vertical-align': null
}
}
@MJMLElement
class Spacer extends Component {
styles = this.getStyles()
getStyles () {
const { mjAttribute, defaultUnit } = this.props
return {
div: {
fontSize: '1px',
lineHeight: defaultUnit(mjAttribute('height'))
}
}
}
render () {
return (
<div
dangerouslySetInnerHTML={{ __html: ' ' }}
style={this.styles.div} />
)
}
}
Spacer.tagName = tagName
Spacer.parentTag = parentTag
Spacer.selfClosingTag = selfClosingTag
Spacer.defaultMJMLDefinition = defaultMJMLDefinition
export default Spacer
| import { MJMLElement } from 'mjml-core'
import React, { Component } from 'react'
const tagName = 'mj-spacer'
const parentTag = ['mj-column', 'mj-hero-content']
const selfClosingTag = true
const defaultMJMLDefinition = {
attributes: {
'align': null,
'container-background-color': null,
'height': '20px',
'padding-bottom': null,
'padding-left': null,
'padding-right': null,
'padding-top': null,
'vertical-align': null
}
}
@MJMLElement
class Spacer extends Component {
styles = this.getStyles()
getStyles () {
const { mjAttribute, defaultUnit } = this.props
return {
div: {
fontSize: '1px',
lineHeight: defaultUnit(mjAttribute('height')),
whiteSpace: 'nowrap'
}
}
}
render () {
return (
<div
dangerouslySetInnerHTML={{ __html: ' ' }}
style={this.styles.div} />
)
}
}
Spacer.tagName = tagName
Spacer.parentTag = parentTag
Spacer.selfClosingTag = selfClosingTag
Spacer.defaultMJMLDefinition = defaultMJMLDefinition
export default Spacer
| Fix escaping servers which replace the ` ` with a space | Fix escaping servers which replace the ` ` with a space
We have seen some servers which replace the non-breaking space character with an actual space.
This should ensure that even when there is a space the div actually renders | JavaScript | mit | mjmlio/mjml |
9cfef29bf4495ee906341e1f3836142801093f9c | tests/lib/storage.js | tests/lib/storage.js | var ready;
beforeEach(function() {
storage = TEST_STORAGE;
storage.clear(function() {
ready = true;
});
waitsFor(function() {
return ready;
}, "the storage to be set up for testing", 500);
});
afterEach(function() {
storage = DEFAULT_STORAGE;
}); | var ready;
beforeEach(function() {
ready = false;
storage = TEST_STORAGE;
storage.clear(function() {
ready = true;
});
waitsFor(function() {
return ready;
}, "the storage to be set up for testing", 500);
});
afterEach(function() {
storage = DEFAULT_STORAGE;
}); | Set ready var to false before each test so it doesn't run prematurely. | Set ready var to false before each test so it doesn't run prematurely.
| JavaScript | mit | AntarcticApps/Tiles,AntarcticApps/Tiles |
627f1de997b292bd0069048bdda36b2ba0f144c2 | lib/plugins/dataforms.js | lib/plugins/dataforms.js | 'use strict';
require('../stanza/dataforms');
module.exports = function (client) {
client.disco.addFeature('jabber:x:data');
client.disco.addFeature('urn:xmpp:media-element');
client.disco.addFeature('http://jabber.org/protocol/xdata-validate');
client.on('message', function (msg) {
if (msg.form) {
client.emit('dataform', msg);
}
});
};
| 'use strict';
require('../stanza/dataforms');
module.exports = function (client) {
client.disco.addFeature('jabber:x:data');
client.disco.addFeature('urn:xmpp:media-element');
client.disco.addFeature('http://jabber.org/protocol/xdata-validate');
client.disco.addFeature('http://jabber.org/protocol/xdata-layout');
client.on('message', function (msg) {
if (msg.form) {
client.emit('dataform', msg);
}
});
};
| Add disco feature for forms layout | Add disco feature for forms layout
| JavaScript | mit | soapdog/stanza.io,legastero/stanza.io,rogervaas/stanza.io,legastero/stanza.io,otalk/stanza.io,flavionegrao/stanza.io,otalk/stanza.io,soapdog/stanza.io,spunkydunker/stanza.io,firdausramlan/stanza.io,spunkydunker/stanza.io,flavionegrao/stanza.io,rogervaas/stanza.io,glpenghui/stanza.io,Palid/stanza.io,glpenghui/stanza.io,Palid/stanza.io,firdausramlan/stanza.io |
a3e393d43c1752420360f71c319d2d6ea2300712 | components/dash-core-components/src/utils/optionTypes.js | components/dash-core-components/src/utils/optionTypes.js | import {type} from 'ramda';
export const sanitizeOptions = options => {
if (type(options) === 'Object') {
return Object.entries(options).map(([value, label]) => ({
label: String(label),
value,
}));
}
if (type(options) === 'Array') {
if (
options.length > 0 &&
['String', 'Number', 'Bool'].includes(type(options[0]))
) {
return options.map(option => ({
label: String(option),
value: option,
}));
}
return options;
}
return options;
};
| import React from 'react';
import {type} from 'ramda';
export const sanitizeOptions = options => {
if (type(options) === 'Object') {
return Object.entries(options).map(([value, label]) => ({
label: React.isValidElement(label) ? label : String(label),
value,
}));
}
if (type(options) === 'Array') {
if (
options.length > 0 &&
['String', 'Number', 'Bool'].includes(type(options[0]))
) {
return options.map(option => ({
label: String(option),
value: option,
}));
}
return options;
}
return options;
};
| Fix objects options with component label. | Fix objects options with component label.
| JavaScript | mit | plotly/dash,plotly/dash,plotly/dash,plotly/dash,plotly/dash |
1dc21a911253f9485a71963701355a226b8a71e5 | test/load-json-spec.js | test/load-json-spec.js | /* global require, describe, it */
import assert from 'assert';
var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/';
var katasUrl = urlPrefix + '__grouped__.json';
var GroupedKata = require('../src/grouped-kata.js');
describe('load ES6 kata data', function() {
it('loaded data are as expected', function(done) {
function onSuccess(groupedKatas) {
assert.ok(groupedKatas);
done();
}
new GroupedKata(katasUrl).load(function() {}, onSuccess);
});
describe('on error, call error callback and the error passed', function() {
it('invalid JSON', function(done) {
function onError(err) {
assert.ok(err);
done();
}
var invalidUrl = urlPrefix;
new GroupedKata(invalidUrl).load(onError);
});
it('for invalid data', function(done) {
function onError(err) {
assert.ok(err);
done();
}
var invalidData = urlPrefix + '__all__.json';
new GroupedKata(invalidData).load(onError);
});
});
});
| /* global describe, it */
import assert from 'assert';
const urlPrefix = 'http://katas.tddbin.com/katas/es6/language';
const katasUrl = `${urlPrefix}/__grouped__.json`;
import GroupedKata from '../src/grouped-kata.js';
describe('load ES6 kata data', function() {
it('loaded data are as expected', function(done) {
function onSuccess(groupedKatas) {
assert.ok(groupedKatas);
done();
}
new GroupedKata(katasUrl).load(() => {}, onSuccess);
});
describe('on error, call error callback and the error passed', function() {
it('invalid JSON', function(done) {
function onError(err) {
assert.ok(err);
done();
}
var invalidUrl = urlPrefix;
new GroupedKata(invalidUrl).load(onError);
});
it('for invalid data', function(done) {
function onError(err) {
assert.ok(err);
done();
}
var invalidData = `${urlPrefix}/__all__.json`;
new GroupedKata(invalidData).load(onError);
});
});
});
| Use ES6 in the tests. | Use ES6 in the tests. | JavaScript | mit | wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop |
fd3e37f287d48df7185f8655dab37894ffafaae6 | main.js | main.js | import ExamplePluginComponent from "./components/ExamplePluginComponent";
var PluginHelper = global.MarathonUIPluginAPI.PluginHelper;
PluginHelper.registerMe("examplePlugin-0.0.1");
PluginHelper.injectComponent(ExamplePluginComponent, "SIDEBAR_BOTTOM");
| import ExamplePluginComponent from "./components/ExamplePluginComponent";
var MarathonUIPluginAPI = global.MarathonUIPluginAPI;
var PluginHelper = MarathonUIPluginAPI.PluginHelper;
var PluginMountPoints = MarathonUIPluginAPI.PluginMountPoints;
PluginHelper.registerMe("examplePlugin-0.0.1");
PluginHelper.injectComponent(ExamplePluginComponent,
PluginMountPoints.SIDEBAR_BOTTOM);
| Introduce read-only but extensible mount points file | Introduce read-only but extensible mount points file
| JavaScript | apache-2.0 | mesosphere/marathon-ui-example-plugin |
87cb50db1913fccaee9e06f4eef8ab16d8564488 | popup.js | popup.js | document.addEventListener('DOMContentLoaded', function () {
display('Searching...');
});
function display(msg) {
var el = document.body;
el.innerHTML = msg;
}
chrome.runtime.getBackgroundPage(displayMessages);
function displayMessages(backgroundPage) {
var html = '<ul>';
html += backgroundPage.services.map(function (service) {
return '<li class="service">'
+ service.name
+ '<span class="host">'
+ service.host + ':' + service.port
+ '</span>'
'</li>';
}).join('');
html += '</ul>';
display(html);
var items = Array.prototype.slice.call(document.getElementsByTagName('li')),
uiPage = chrome.extension.getURL("ui.html");
items.forEach(function(li) {
li.addEventListener('click', function() {
chrome.tabs.create({url: uiPage});
});
});
}
| document.addEventListener('DOMContentLoaded', function () {
display('Searching...');
});
function display(msg) {
var el = document.body;
el.innerHTML = msg;
}
chrome.runtime.getBackgroundPage(displayMessages);
function displayMessages(backgroundPage) {
var html = '<ul>';
html += backgroundPage.services.map(function (service) {
return '<li class="service">'
+ service.host
+ '<span class="host">'
+ service.address + ':' + service.port
+ '</span>'
'</li>';
}).join('');
html += '</ul>';
display(html);
var items = Array.prototype.slice.call(document.getElementsByTagName('li')),
uiPage = chrome.extension.getURL("ui.html");
items.forEach(function(li) {
li.addEventListener('click', function() {
chrome.tabs.create({url: uiPage});
});
});
}
| Change name to match new service instance object | Change name to match new service instance object
| JavaScript | apache-2.0 | mediascape/discovery-extension,mediascape/discovery-extension |
06164aff052d6922f1506398dc60a7dde78a9f98 | resolve-cache.js | resolve-cache.js | 'use strict';
const _ = require('lodash');
const tests = {
db: (value) => {
const keys = ['query', 'connect', 'begin'];
return keys.every((key) => _.has(value, key));
},
};
const ok = require('ok')(tests);
const previous = [];
module.exports = (obj) => {
const result = obj ? previous.find((item) => _.isEqual(item, obj)) : _.last(previous);
if (result) {
return result;
} else {
const errors = ok(obj);
if (errors.length) {
throw new Error(`Configuration is invalid: ${errors.join(', ')}`);
}
if (obj) {
previous.push(obj);
}
return obj;
}
};
| 'use strict';
const _ = require('lodash');
const tests = {
db: (value) => {
const keys = ['query', 'connect', 'begin'];
return keys.every((key) => _.has(value, key));
},
};
const ok = require('ok')(tests);
const previous = [];
module.exports = (obj) => {
let result;
if (obj) {
result = previous.find((item) => _.isEqual(item, obj));
}
if (result) {
return result;
} else {
const errors = ok(obj);
if (errors.length) {
throw new Error(`Configuration is invalid: ${errors.join(', ')}`);
}
if (obj) {
previous.push(obj);
}
return obj;
}
};
| Remove ability to get last memoize result by passing falsy argument | Remove ability to get last memoize result by passing falsy argument
| JavaScript | mit | thebitmill/midwest-membership-services |
69454caa8503cb7cfa7366d569ed16cd9bf4caa8 | app/configureStore.js | app/configureStore.js | import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import oaaChat from './reducers'
const configureStore = () => {
const store = createStore(
oaaChat, applyMiddleware(thunk, logger()))
return store
}
export default configureStore | import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import oaaChat from './reducers'
const configureStore = () => {
const store = createStore(
oaaChat,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
applyMiddleware(thunk))
return store
}
export default configureStore | Remove redux-logger and setup redux devtools | Remove redux-logger and setup redux devtools
| JavaScript | mit | danielzy95/oaa-chat,danielzy95/oaa-chat |
f7d6d3ff62ac6de0022e4b014ac5b04096758d48 | src/db/migrations/20161005172637_init_demo.js | src/db/migrations/20161005172637_init_demo.js | export async function up(knex) {
await knex.schema.createTable('Resource', (table) => {
table.uuid('id').notNullable().primary()
table.string('name', 32).notNullable()
table.string('mime', 32)
table.string('md5')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
await knex.schema.createTable('Content', (table) => {
table.increments()
table.uuid('resourceId').notNullable().references('Resource.id')
table.string('name', 32)
table.string('title', 255)
table.text('description')
table.json('data')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
}
export async function down(knex) {
await knex.schema.dropTableIfExists('Content')
await knex.schema.dropTableIfExists('Resource')
}
| export async function up(knex) {
await knex.schema.createTable('Resource', (table) => {
table.uuid('id').notNullable().primary()
table.string('name', 32).notNullable()
table.string('mime', 32)
table.string('md5')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
await knex.schema.createTable('Content', (table) => {
table.increments()
table.uuid('resourceId').notNullable().references('Resource.id')
table.string('name', 32).notNullable()
table.string('title', 255)
table.text('description')
table.json('data')
table.integer('status').notNullable()
table.bigInteger('createdAt')
table.bigInteger('updatedAt')
})
}
export async function down(knex) {
await knex.schema.dropTableIfExists('Content')
await knex.schema.dropTableIfExists('Resource')
}
| Tweak Content name to be not nullable | Tweak Content name to be not nullable
| JavaScript | mit | thangntt2/chatbot_api_hapi,vietthang/hapi-boilerplate |
fcbaeb4705d02858f59c1142f77117e953c4db96 | app/libs/locale/available-locales.js | app/libs/locale/available-locales.js | 'use strict';
// Load our requirements
const glob = require('glob'),
path = require('path'),
logger = require('../log');
// Build a list of the available locale files in a given directory
module.exports = function(dir) {
// Variables
let available = [];
// Run through the installed locales and add to array to be loaded
glob.sync(path.join(dir, '/*.json')).forEach((file) => {
// Get the shortname for the file
let lang = path.basename(file, '.json');
// Add to our object
logger.debug('Found the "%s" locale.', lang);
available.push(lang);
});
return available;
};
| 'use strict';
// Load our requirements
const glob = require('glob'),
path = require('path'),
logger = require(__base + 'libs/log');
// Build a list of the available locale files in a given directory
module.exports = function(dir) {
// Variables
let available = ['en'];
// Run through the installed locales and add to array to be loaded
glob.sync(path.join(dir, '/*.json')).forEach((file) => {
// Get the shortname for the file
let lang = path.basename(file, '.json');
// Ignore english
if ( lang !== 'en' ) { available.push(lang); }
});
return available;
};
| Update available locales to prioritise english | Update available locales to prioritise english
| JavaScript | apache-2.0 | transmutejs/core |
27ea2b2e1951431b0f6bae742d7c3babf5053bc1 | jest.config.js | jest.config.js | module.exports = {
verbose: !!process.env.VERBOSE,
moduleNameMapper: {
testHelpers: '<rootDir>/testHelpers/index.js',
},
setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js',
testResultsProcessor: './node_modules/jest-junit',
testPathIgnorePatterns: ['/node_modules/'],
testEnvironment: 'node',
}
| module.exports = {
verbose: !!process.env.VERBOSE,
moduleNameMapper: {
testHelpers: '<rootDir>/testHelpers/index.js',
},
setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js',
testResultsProcessor: './node_modules/jest-junit',
testPathIgnorePatterns: ['/node_modules/'],
testEnvironment: 'node',
bail: true,
}
| Configure tests to fail fast | Configure tests to fail fast
| JavaScript | mit | tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs |
4fd824256e18f986f2cbd3c54cb1b9019cc1918e | index.js | index.js | var pkg = require(process.cwd() + '/package.json');
var intrepidjsVersion = pkg.version;
// Dummy index, only shows intrepidjs-cli version
console.log(intrepidjsVersion);
| var pkg = require(__dirname + '/package.json');
var intrepidjsVersion = pkg.version;
// Dummy index, only shows intrepidjs-cli version
console.log(intrepidjsVersion);
| Use __dirname instead of process.cwd | Use __dirname instead of process.cwd
process.cwd refers to the directory in which file was executed, not the directory in which it lives | JavaScript | mit | wtelecom/intrepidjs-cli |
2f747d79f542577e5cf60d18b9fbf8eea82070da | index.js | index.js | 'use strict';
module.exports = {
name: 'Ember CLI ic-ajax',
init: function(name) {
this.treePaths['vendor'] = 'node_modules';
},
included: function(app) {
var options = this.app.options.icAjaxOptions || {enabled: true};
if (options.enabled) {
this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
exports: {
'ic-ajax': [
'default',
'defineFixture',
'lookupFixture',
'raw',
'request',
]
}
});
}
}
};
| 'use strict';
module.exports = {
name: 'Ember CLI ic-ajax',
init: function(name) {
this.treePaths['vendor'] = require.resolve('ic-ajax').replace('ic-ajax/dist/cjs/main.js', '');
},
included: function(app) {
var options = this.app.options.icAjaxOptions || {enabled: true};
if (options.enabled) {
this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
exports: {
'ic-ajax': [
'default',
'defineFixture',
'lookupFixture',
'raw',
'request',
]
}
});
}
}
};
| Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);"" | Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);""
This reverts commit 2aeb7307e81c8052b2fb6021bf4ab10ca433abce.
| JavaScript | mit | rwjblue/ember-cli-ic-ajax,tsing80/ember-cli-ic-ajax,stefanpenner/ember-cli-ic-ajax,taras/ember-cli-ic-ajax |
cb0ebc4c7ca492ed3c1144777643468ef0db054e | index.js | index.js | import postcss from 'postcss';
const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => {
css.walkRules(rule => {
const isDisabled = rule.some(({prop, text}) =>
prop === '-js-display' || text === 'flexibility-disable' || text === '! flexibility-disable'
);
if (!isDisabled) {
rule.walkDecls('display', decl => {
const {value} = decl;
if (value === 'flex') {
decl.cloneBefore({prop: '-js-display'});
}
});
}
});
});
export default postcssFlexibility;
| import postcss from 'postcss';
const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => {
css.walkRules(rule => {
const isDisabled = rule.some(({prop, text = ''}) =>
prop === '-js-display' || text.endsWith('flexibility-disable')
);
if (!isDisabled) {
rule.walkDecls('display', decl => {
const {value} = decl;
if (value === 'flex') {
decl.cloneBefore({prop: '-js-display'});
}
});
}
});
});
export default postcssFlexibility;
| Change check to use endsWith for supporting loud comments | Change check to use endsWith for supporting loud comments | JavaScript | mit | 7rulnik/postcss-flexibility |
a2172115022e7658573428d9ddf9b094f9c6d1b5 | index.js | index.js | module.exports = isPromise;
function isPromise(obj) {
return obj && typeof obj.then === 'function';
} | module.exports = isPromise;
function isPromise(obj) {
return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
| Make the test a bit more strict | Make the test a bit more strict
| JavaScript | mit | floatdrop/is-promise,then/is-promise,then/is-promise |
edbc6e8931c9c2777520c0ccf0a3d74b8f75ebf6 | index.js | index.js |
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require("./config.json");
client.on('ready', () => {
console.log("I am ready!");
// client.channels.get('spam').send("Soup is ready!")
});
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return;
let msg = message.content.slice(config.prefix.length);
if (msg.startsWith('ping')) {
message.reply('pong');
}
if (msg.startsWith('echo')) {
if (msg.length > 5) {
message.channel.send(msg.slice(5));
} else {
message.channel.send("Please provide valid text to echo!");
}
}
if (msg.startsWith('die')) {
message.channel.send("Shutting down...");
client.destroy((err) => {
console.log(err);
});
}
});
client.on('disconnected', () => {
console.log("Disconnected!");
process.exit(0);
});
client.login(config.token); |
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require("./config.json");
client.on('ready', () => {
console.log("I am ready!");
});
client.on('message', (message) => {
if (!message.content.startsWith(config.prefix) || message.author.bot) return; // Ignore messages not
// starting with your prefix
let msg = message.content.slice(config.prefix.length);
if (msg.startsWith('ping')) {
message.reply('pong');
}
if (msg.startsWith('echo')) {
if (msg.length > 5 && msg[4] === ' ') { // If msg starts with 'echo '
message.channel.send(msg.slice(5)); // Echo the rest of msg.
} else {
message.channel.send("Please provide valid text to echo!");
}
}
if (msg.startsWith('die')) {
message.channel.send("Shutting down...");
client.destroy((err) => {
console.log(err);
});
}
});
client.on('disconnected', () => {
console.log("Disconnected!");
process.exit(0);
});
client.login(config.token); | Add some comments and refine echo command | Add some comments and refine echo command
| JavaScript | mit | Rafer45/soup |
e1e5840e921465d0454213cb455aca4661bcf715 | index.js | index.js | var Q = require('q');
/**
* Chai-Mugshot Plugin
*
* @param mugshot - Mugshot instance
* @param testRunnerCtx - Context of the test runner where the assertions are
* done
*/
module.exports = function(mugshot, testRunnerCtx) {
return function(chai) {
var Assertion = chai.Assertion;
function composeMessage(message) {
var standardMessage = 'expected baseline and screenshot of #{act}';
return {
affirmative: standardMessage + ' to ' + message,
negative: standardMessage + ' to not ' + message
};
}
function mugshotProperty(name, message) {
var msg = composeMessage(message);
Assertion.addProperty(name, function() {
var captureItem = this._obj;
var deferred = Q.defer();
var _this = this;
mugshot.test(captureItem, function(error, result) {
if (error) {
deferred.reject(error);
} else {
if (testRunnerCtx !== undefined) {
testRunnerCtx.result = result;
}
try {
_this.assert(result.isEqual, msg.affirmative, msg.negative);
deferred.resolve();
} catch (error) {
deferred.reject(error);
}
}
});
return deferred.promise;
});
}
mugshotProperty('identical', 'be identical');
}
};
| /**
* Chai-Mugshot Plugin
*
* @param mugshot - Mugshot instance
* @param testRunnerCtx - Context of the test runner where the assertions are
* done
*/
module.exports = function(mugshot, testRunnerCtx) {
return function(chai) {
var Assertion = chai.Assertion;
function composeMessage(message) {
var standardMessage = 'expected baseline and screenshot of #{act}';
return {
affirmative: standardMessage + ' to ' + message,
negative: standardMessage + ' to not ' + message
};
}
function mugshotProperty(name, message) {
var msg = composeMessage(message);
Assertion.addProperty(name, function() {
var _this = this,
captureItem = this._obj,
promise, resolve, reject;
promise = new Promise(function(res, rej) {
resolve = res;
reject = rej;
});
mugshot.test(captureItem, function(error, result) {
if (error) {
reject(error);
} else {
if (testRunnerCtx !== undefined) {
testRunnerCtx.result = result;
}
try {
_this.assert(result.isEqual, msg.affirmative, msg.negative);
resolve();
} catch (error) {
reject(error);
}
}
});
return promise;
});
}
mugshotProperty('identical', 'be identical');
}
};
| Replace q with native Promises | Replace q with native Promises
| JavaScript | mit | uberVU/chai-mugshot,uberVU/chai-mugshot |
bc3e85aafc3fa1095169153661093d3f012424e2 | node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js | node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js | "use strict";
/*!
* Module dependencies.
*/
var dummy
, hotplate = require('hotplate')
;
exports.getAllStores = hotplate.cachable( function( done ){
var res = {
stores: {},
collections: {},
};
hotplate.hotEvents.emit( 'stores', function( err, results){
results.forEach( function( element ) {
element.result.forEach( function( Store ){
try {
var store = new Store();
} catch ( e ){
hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " );
hotplate.log( e );
hotplate.log( element );
hotplate.log( Store );
}
// If the store was created (no exception thrown...)
if( store ){
// Add the module to the store registry
res.stores[ store.storeName ] = { Store: Store, storeObject: store };
// Add the module to the collection registry
if( store.collectionName ){
res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || [];
res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } );
}
}
});
});
done( null, res );
});
});
| "use strict";
/*!
* Module dependencies.
*/
var dummy
, hotplate = require('hotplate')
;
exports.getAllStores = hotplate.cachable( function( done ){
var res = {
stores: {},
collections: {},
};
hotplate.hotEvents.emit( 'stores', function( err, results){
results.forEach( function( element ) {
Object.keys( element.result ).forEach( function( k ){
var Store = element.result[ k ];
try {
var store = new Store();
} catch ( e ){
hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " );
hotplate.log( e );
hotplate.log( element );
hotplate.log( Store );
}
// If the store was created (no exception thrown...)
if( store ){
// Add the module to the store registry
res.stores[ store.storeName ] = { Store: Store, storeObject: store };
// Add the module to the collection registry
if( store.collectionName ){
res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || [];
res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } );
}
}
});
});
done( null, res );
});
});
| Change way in which storeRegistry expects stores to be returned, it's now a hash | Change way in which storeRegistry expects stores to be returned, it's now a hash
| JavaScript | mit | shelsonjava/hotplate,mercmobily/hotplate,mercmobily/hotplate,shelsonjava/hotplate |
9235990779b1098df387e534656a921107732818 | src/mw-menu/directives/mw_menu_top_entries.js | src/mw-menu/directives/mw_menu_top_entries.js | angular.module('mwUI.Menu')
.directive('mwMenuTopEntries', function ($rootScope, $timeout) {
return {
scope: {
menu: '=mwMenuTopEntries',
right: '='
},
transclude: true,
templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html',
controller: function ($scope) {
var menu = $scope.menu || new mwUI.Menu.MwMenu();
this.getMenu = function () {
return menu;
};
},
link: function (scope, el, attrs, ctrl) {
scope.entries = ctrl.getMenu();
scope.unCollapse = function () {
var collapseEl = el.find('.navbar-collapse');
if (collapseEl.hasClass('in')) {
collapseEl.collapse('hide');
}
};
$rootScope.$on('$locationChangeSuccess', function () {
scope.unCollapse();
});
scope.$on('mw-menu:triggerReorder', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:reorder');
});
}));
scope.$on('mw-menu:triggerResort', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:resort');
scope.entries.sort();
});
}));
scope.entries.on('add remove reset', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:reorder');
});
}));
}
};
}); | angular.module('mwUI.Menu')
.directive('mwMenuTopEntries', function ($rootScope, $timeout) {
return {
scope: {
menu: '=mwMenuTopEntries',
right: '='
},
transclude: true,
templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html',
controller: function ($scope) {
var menu = $scope.menu || new mwUI.Menu.MwMenu();
this.getMenu = function () {
return menu;
};
},
link: function (scope, el, attrs, ctrl) {
scope.entries = ctrl.getMenu();
scope.$on('mw-menu:triggerReorder', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:reorder');
});
}));
scope.$on('mw-menu:triggerResort', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:resort');
scope.entries.sort();
});
}));
scope.entries.on('add remove reset', _.throttle(function () {
$timeout(function () {
scope.$broadcast('mw-menu:reorder');
});
}));
}
};
}); | Move close functionality on location change into mwMenuTopBar | Move close functionality on location change into mwMenuTopBar
| JavaScript | apache-2.0 | mwaylabs/uikit,mwaylabs/uikit,mwaylabs/uikit |
b9c96cfc73b6e0adcb7b747c40ac40c74995ea7f | eslint-rules/no-primitive-constructors.js | eslint-rules/no-primitive-constructors.js | /**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
module.exports = function(context) {
function check(node) {
const name = node.callee.name;
let msg = null;
switch (name) {
case 'Boolean':
msg = 'To cast a value to a boolean, use double negation: !!value';
break;
case 'String':
msg = 'To cast a value to a string, concat it with the empty string: \'\' + value';
break;
}
if (msg) {
context.report(node, `Do not use the ${name} constructor. ${msg}`);
}
}
return {
CallExpression: check,
NewExpression: check,
};
};
| /**
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
module.exports = function(context) {
function report(node, name, msg) {
context.report(node, `Do not use the ${name} constructor. ${msg}`);
}
function check(node) {
const name = node.callee.name;
switch (name) {
case 'Boolean':
report(
node,
name,
'To cast a value to a boolean, use double negation: !!value'
);
break;
case 'String':
report(
node,
name,
'To cast a value to a string, concat it with the empty string ' +
'(unless it\'s a symbol, which have different semantics): ' +
'\'\' + value'
);
break;
}
}
return {
CallExpression: check,
NewExpression: check,
};
};
| Add caveat about symbols to string error message | Add caveat about symbols to string error message
| JavaScript | bsd-3-clause | acdlite/react,apaatsio/react,jorrit/react,krasimir/react,jordanpapaleo/react,mosoft521/react,facebook/react,jameszhan/react,yungsters/react,STRML/react,AlmeroSteyn/react,glenjamin/react,tomocchino/react,Simek/react,trueadm/react,jzmq/react,TheBlasfem/react,silvestrijonathan/react,joecritch/react,yiminghe/react,prometheansacrifice/react,shergin/react,jzmq/react,sekiyaeiji/react,STRML/react,quip/react,wmydz1/react,ArunTesco/react,ArunTesco/react,Simek/react,camsong/react,terminatorheart/react,aickin/react,pyitphyoaung/react,ArunTesco/react,facebook/react,silvestrijonathan/react,yiminghe/react,AlmeroSteyn/react,glenjamin/react,quip/react,cpojer/react,chicoxyzzy/react,kaushik94/react,rickbeerendonk/react,acdlite/react,prometheansacrifice/react,TheBlasfem/react,camsong/react,silvestrijonathan/react,yungsters/react,rricard/react,yungsters/react,flarnie/react,yangshun/react,rickbeerendonk/react,jquense/react,syranide/react,VioletLife/react,anushreesubramani/react,jorrit/react,joecritch/react,jordanpapaleo/react,rickbeerendonk/react,glenjamin/react,roth1002/react,edvinerikson/react,jameszhan/react,wmydz1/react,roth1002/react,jdlehman/react,anushreesubramani/react,yangshun/react,edvinerikson/react,AlmeroSteyn/react,AlmeroSteyn/react,jzmq/react,cpojer/react,chicoxyzzy/react,billfeller/react,AlmeroSteyn/react,apaatsio/react,terminatorheart/react,yiminghe/react,leexiaosi/react,STRML/react,maxschmeling/react,mosoft521/react,roth1002/react,Simek/react,empyrical/react,joecritch/react,shergin/react,kaushik94/react,mhhegazy/react,jdlehman/react,nhunzaker/react,roth1002/react,jzmq/react,mosoft521/react,prometheansacrifice/react,mjackson/react,kaushik94/react,rickbeerendonk/react,cpojer/react,Simek/react,acdlite/react,nhunzaker/react,mhhegazy/react,AlmeroSteyn/react,jquense/react,silvestrijonathan/react,silvestrijonathan/react,yungsters/react,joecritch/react,dilidili/react,kaushik94/react,anushreesubramani/react,chenglou/react,ericyang321/react,mhhegazy/react,jzmq/react,jdlehman/react,tomocchino/react,STRML/react,facebook/react,dilidili/react,yiminghe/react,acdlite/react,aickin/react,TheBlasfem/react,dilidili/react,krasimir/react,jordanpapaleo/react,mjackson/react,TheBlasfem/react,yiminghe/react,aickin/react,ericyang321/react,yungsters/react,brigand/react,jzmq/react,chenglou/react,mhhegazy/react,jameszhan/react,cpojer/react,cpojer/react,mjackson/react,brigand/react,shergin/react,jquense/react,anushreesubramani/react,brigand/react,jordanpapaleo/react,pyitphyoaung/react,pyitphyoaung/react,edvinerikson/react,jdlehman/react,roth1002/react,jorrit/react,kaushik94/react,jdlehman/react,glenjamin/react,tomocchino/react,TheBlasfem/react,pyitphyoaung/react,acdlite/react,maxschmeling/react,jordanpapaleo/react,maxschmeling/react,krasimir/react,rricard/react,AlmeroSteyn/react,mhhegazy/react,kaushik94/react,jzmq/react,billfeller/react,joecritch/react,leexiaosi/react,krasimir/react,STRML/react,prometheansacrifice/react,ericyang321/react,trueadm/react,trueadm/react,aickin/react,shergin/react,Simek/react,ericyang321/react,facebook/react,billfeller/react,maxschmeling/react,pyitphyoaung/react,apaatsio/react,VioletLife/react,camsong/react,terminatorheart/react,anushreesubramani/react,silvestrijonathan/react,jquense/react,tomocchino/react,chenglou/react,yiminghe/react,empyrical/react,chenglou/react,yiminghe/react,yangshun/react,aickin/react,facebook/react,nhunzaker/react,prometheansacrifice/react,maxschmeling/react,glenjamin/react,flarnie/react,rricard/react,joecritch/react,prometheansacrifice/react,quip/react,billfeller/react,edvinerikson/react,syranide/react,STRML/react,yangshun/react,aickin/react,jorrit/react,camsong/react,terminatorheart/react,billfeller/react,dilidili/react,ericyang321/react,maxschmeling/react,facebook/react,trueadm/react,nhunzaker/react,VioletLife/react,jameszhan/react,chicoxyzzy/react,mhhegazy/react,brigand/react,empyrical/react,acdlite/react,anushreesubramani/react,yangshun/react,kaushik94/react,jquense/react,apaatsio/react,dilidili/react,quip/react,tomocchino/react,empyrical/react,jdlehman/react,syranide/react,mosoft521/react,cpojer/react,sekiyaeiji/react,jameszhan/react,krasimir/react,prometheansacrifice/react,roth1002/react,shergin/react,krasimir/react,yangshun/react,jorrit/react,trueadm/react,edvinerikson/react,apaatsio/react,TheBlasfem/react,wmydz1/react,mhhegazy/react,flarnie/react,jordanpapaleo/react,leexiaosi/react,pyitphyoaung/react,anushreesubramani/react,mjackson/react,dilidili/react,Simek/react,tomocchino/react,chicoxyzzy/react,VioletLife/react,quip/react,rricard/react,ericyang321/react,quip/react,mosoft521/react,brigand/react,edvinerikson/react,yungsters/react,jameszhan/react,glenjamin/react,sekiyaeiji/react,brigand/react,apaatsio/react,brigand/react,VioletLife/react,mosoft521/react,flarnie/react,rickbeerendonk/react,mjackson/react,mjackson/react,mosoft521/react,cpojer/react,flipactual/react,empyrical/react,wmydz1/react,trueadm/react,dilidili/react,jquense/react,roth1002/react,edvinerikson/react,chicoxyzzy/react,rickbeerendonk/react,wmydz1/react,Simek/react,flipactual/react,chicoxyzzy/react,apaatsio/react,shergin/react,camsong/react,jameszhan/react,chenglou/react,empyrical/react,yungsters/react,mjackson/react,camsong/react,nhunzaker/react,chenglou/react,wmydz1/react,glenjamin/react,flipactual/react,VioletLife/react,jorrit/react,shergin/react,jorrit/react,silvestrijonathan/react,krasimir/react,ericyang321/react,joecritch/react,wmydz1/react,empyrical/react,chenglou/react,billfeller/react,aickin/react,jdlehman/react,nhunzaker/react,VioletLife/react,yangshun/react,rricard/react,rricard/react,rickbeerendonk/react,maxschmeling/react,flarnie/react,quip/react,camsong/react,terminatorheart/react,chicoxyzzy/react,nhunzaker/react,trueadm/react,acdlite/react,pyitphyoaung/react,STRML/react,flarnie/react,facebook/react,jquense/react,syranide/react,jordanpapaleo/react,billfeller/react,tomocchino/react,terminatorheart/react,flarnie/react |
8aa85b90cbffc79fdc54ba1aac070d7fb2a8dccb | public/controllers/main.routes.js | public/controllers/main.routes.js | 'use strict';
angular.module('StudentApp').config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.when('/studentPage', {
templateUrl: 'views/student/student.list.html',
controller: 'StudentController'
}).when('/comments/:id', {
templateUrl: 'views/comment/comments.list.html',
controller: 'CommentsController'
}).when('/stockPage', {
templateUrl: 'views/Stock/StockManagment.html',
controller: 'StockController'
}).when('/orderPage', {
templateUrl: 'views/Stock/OrderManagment.html',
controller: 'OrderController'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]); | 'use strict';
angular.module('StudentApp').config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.when('/studentPage', {
templateUrl: 'views/student/student.list.html',
controller: 'StudentController'
}).when('/comments/:id', {
templateUrl: 'views/comment/comments.list.html',
controller: 'CommentsController'
}).when('/stockPage', {
templateUrl: 'views/Stock/StockManagment.html',
controller: 'StockController'
}).when('/orderPage', {
templateUrl: 'views/Stock/OrderManagment.html',
controller: 'OrderController'
}).when('/customerPage', {
templateUrl: 'views/Customer/Customer.html',
controller: 'CustomerController'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]); | Add relevant Customer section changes to main.router.js | Add relevant Customer section changes to main.router.js
| JavaScript | mit | scoobygroup/IWEX,scoobygroup/IWEX |
c11d0b3d616fb1d03cdbf0453dcdc5cb39ac122a | lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js | lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js | 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {...integer} idx - indices
* @throws {TypeError} provided indices must be integer valued
* @throws {RangeError} index exceeds array dimensions
* @returns {*} array element
*/
function get() {
/* eslint-disable no-invalid-this */
var len;
var idx;
var i;
// TODO: support index modes
len = arguments.length;
idx = this._offset;
for ( i = 0; i < len; i++ ) {
if ( !isInteger( arguments[ i ] ) ) {
throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' );
}
idx += this._strides[ i ] * arguments[ i ];
}
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
| 'use strict';
// MODULES //
var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive;
var getIndex = require( './get_index.js' );
// FUNCTIONS //
/**
* Returns an array element.
*
* @private
* @param {...integer} idx - indices
* @throws {TypeError} provided indices must be integer valued
* @throws {RangeError} index exceeds array dimensions
* @returns {*} array element
*/
function get() {
/* eslint-disable no-invalid-this */
var len;
var idx;
var ind;
var i;
len = arguments.length;
idx = this._offset;
for ( i = 0; i < len; i++ ) {
if ( !isInteger( arguments[ i ] ) ) {
throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' );
}
ind = getIndex( arguments[ i ], this._shape[ i ], this._mode );
idx += this._strides[ i ] * ind;
}
return this._buffer[ idx ];
} // end FUNCTION get()
// EXPORTS //
module.exports = get;
| Add support for an index mode | Add support for an index mode
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib |
2d1bd23a872645053b8e19bdf8b656b8ca872c4b | index.js | index.js | require('babel/register');
require('dotenv').load();
var startServer = require('./app');
var port = process.env['PORT'] || 3000;
startServer(port);
| require('babel/register');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').load();
}
var startServer = require('./app');
var port = process.env.PORT || 3000;
startServer(port);
| Handle case where dotenv is not included in production. | Handle case where dotenv is not included in production.
| JavaScript | mit | keokilee/hitraffic-api,hitraffic/api-server |
3321cc95a521445a1ad1a2f70c057acb583ac71e | solutions.digamma.damas.ui/src/components/layouts/app-page.js | solutions.digamma.damas.ui/src/components/layouts/app-page.js | import Vue from "vue"
export default {
name: 'AppPage',
props: {
layout: {
type: String,
required: true,
validator: [].includes.bind(["standard", "empty"])
}
},
created() {
let component = components[this.layout]
if (!Vue.options.components[component.name]) {
Vue.component(
component.name,
component,
);
}
this.$parent.$emit('update:layout', component);
},
render(h) {
return this.$slots.default ? this.$slots.default[0] : h();
},
}
const components = {
"standard": () => import("./layout-standard"),
"empty": () => import("./layout-empty")
} | import Vue from "vue"
export default {
name: 'AppPage',
props: {
layout: {
type: String,
required: true,
validator: [].includes.bind(["standard", "empty"])
}
},
created() {
let component = components[this.layout]
if (!Vue.options.components[component.name]) {
Vue.component(
component.name,
component,
);
}
if (this.$parent.layout !== component) {
this.$parent.$emit('update:layout', component);
}
},
render(h) {
return this.$slots.default ? this.$slots.default[0] : h();
},
}
const components = {
"standard": () => import("./layout-standard"),
"empty": () => import("./layout-empty")
}
| Add identity gard before firing layout change | Add identity gard before firing layout change
| JavaScript | mit | digammas/damas,digammas/damas,digammas/damas,digammas/damas |
77174ca4c0e6e663ed9fb1cd5ef74d3ae7ec865c | index.js | index.js | "use strict";
var _ = require("lodash");
var HTTP_STATUS_CODES = require("http").STATUS_CODES;
var request = require("request");
var url = require("url");
function LamernewsAPI(root) {
this.root = root;
return this;
}
LamernewsAPI.prototype.getNews = function getNews(options, callback) {
var defaults = {
count: 30,
start: 0,
type: "latest"
};
var signature;
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
options = _.defaults(options || {}, defaults);
signature = ["getnews", options.type, options.start, options.count];
this.query(signature.join("/"), callback);
return this;
};
LamernewsAPI.prototype.query = function query(signature, callback) {
if (!this.root) {
throw new Error("No API root specified");
}
request(url.resolve(this.root, signature), function(err, res, body) {
var status;
if (err) {
return callback(err);
}
status = res.statusCode;
if (status !== 200) {
err = new Error(HTTP_STATUS_CODES[status]);
err.code = status;
return callback(err);
}
try {
body = JSON.parse(body);
} catch (err) {
callback(err);
}
callback(null, body);
});
};
module.exports = LamernewsAPI;
| "use strict";
var _ = require("lodash");
var HTTP_STATUS_CODES = require("http").STATUS_CODES;
var request = require("request");
var url = require("url");
function LamernewsAPI(root) {
this.root = root;
return this;
}
LamernewsAPI.prototype = {
getNews: function getNews(options, callback) {
var defaults = {
count: 30,
start: 0,
type: "latest"
};
var signature;
if (!callback && typeof options === "function") {
callback = options;
options = {};
}
options = _.defaults(options || {}, defaults);
signature = ["getnews", options.type, options.start, options.count];
this.query(signature.join("/"), callback);
return this;
},
query: function query(signature, callback) {
if (!this.root) {
throw new Error("No API root specified");
}
request(url.resolve(this.root, signature), function(err, res, body) {
var status;
if (err) {
return callback(err);
}
status = res.statusCode;
if (status !== 200) {
err = new Error(HTTP_STATUS_CODES[status]);
err.code = status;
return callback(err);
}
try {
body = JSON.parse(body);
} catch (err) {
callback(err);
}
callback(null, body);
});
}
};
module.exports = LamernewsAPI;
| Refactor method definitions on prototype to be more DRY | Refactor method definitions on prototype to be more DRY
| JavaScript | mit | sbruchmann/lamernews-api |
5e4c5c4d4ecc1698c5adddb31a2378df0e78ec22 | index.js | index.js | /**
* espower-source - Power Assert instrumentor from source to source.
*
* https://github.com/twada/espower-source
*
* Copyright (c) 2014 Takuto Wada
* Licensed under the MIT license.
* https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt
*/
var espower = require('espower'),
esprima = require('esprima'),
escodegen = require('escodegen'),
merge = require('lodash.merge'),
convert = require('convert-source-map');
function espowerSourceToSource(jsCode, filepath, options) {
'use strict';
var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map;
jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath});
espowerOptions = merge(merge(espower.defaultOptions(), options), {
destructive: true,
path: filepath
});
modifiedAst = espower(jsAst, espowerOptions);
escodegenOutput = escodegen.generate(modifiedAst, {
sourceMap: true,
sourceMapWithCode: true
});
code = escodegenOutput.code; // Generated source code
map = convert.fromJSON(escodegenOutput.map.toString());
map.sourcemap.sourcesContent = [jsCode];
return code + '\n' + map.toComment() + '\n';
}
module.exports = espowerSourceToSource;
| /**
* espower-source - Power Assert instrumentor from source to source.
*
* https://github.com/twada/espower-source
*
* Copyright (c) 2014 Takuto Wada
* Licensed under the MIT license.
* https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt
*/
var espower = require('espower'),
esprima = require('esprima'),
escodegen = require('escodegen'),
merge = require('lodash.merge'),
convert = require('convert-source-map');
function espowerSource(jsCode, filepath, options) {
'use strict';
var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map;
jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath});
espowerOptions = merge(merge(espower.defaultOptions(), options), {
destructive: true,
path: filepath
});
modifiedAst = espower(jsAst, espowerOptions);
escodegenOutput = escodegen.generate(modifiedAst, {
sourceMap: true,
sourceMapWithCode: true
});
code = escodegenOutput.code; // Generated source code
map = convert.fromJSON(escodegenOutput.map.toString());
map.sourcemap.sourcesContent = [jsCode];
return code + '\n' + map.toComment() + '\n';
}
module.exports = espowerSource;
| Change exposed function name to espowerSource | Change exposed function name to espowerSource
| JavaScript | mit | power-assert-js/espower-source |
24ae87eca54f0baa1a379c21cac17fcc3c70f10c | index.js | index.js | function Fs() {}
Fs.prototype = require('fs')
var fs = new Fs()
, Promise = require('promise')
module.exports = exports = fs
for (var key in fs)
if (!(typeof fs[key] != 'function'
|| key.match(/Sync$/)
|| key.match(/^[A-Z]/)
|| key.match(/^create/)
|| key.match(/^(un)?watch/)
))
fs[key] = Promise.denodeify(fs[key])
| var fs = Object.create(require('fs'))
var Promise = require('promise')
module.exports = exports = fs
for (var key in fs)
if (!(typeof fs[key] != 'function'
|| key.match(/Sync$/)
|| key.match(/^[A-Z]/)
|| key.match(/^create/)
|| key.match(/^(un)?watch/)
))
fs[key] = Promise.denodeify(fs[key])
| Use multiple var statements and `Object.create` | Use multiple var statements and `Object.create`
| JavaScript | mit | then/fs |
3c8494b2151178eb169947e7da0775521e1c2bfd | index.js | index.js | /* eslint-env node */
"use strict";
module.exports = {
name: "ember-component-attributes",
setupPreprocessorRegistry(type, registry) {
registry.add("htmlbars-ast-plugin", {
name: "attributes-expression",
plugin: require("./lib/attributes-expression-transform"),
baseDir: function() {
return __dirname;
}
});
}
};
| /* eslint-env node */
"use strict";
module.exports = {
name: "ember-component-attributes",
setupPreprocessorRegistry(type, registry) {
registry.add("htmlbars-ast-plugin", {
name: "attributes-expression",
plugin: require("./lib/attributes-expression-transform"),
baseDir: function() {
return __dirname;
}
});
},
included() {
this.import('vendor/ember-component-attributes/index.js');
},
treeForVendor(rawVendorTree) {
let babelAddon = this.addons.find(addon => addon.name === 'ember-cli-babel');
let transpiledVendorTree = babelAddon.transpileTree(rawVendorTree, {
'ember-cli-babel': {
compileModules: false
}
});
return transpiledVendorTree;
},
};
| Add `treeForVendor` and `included` hook implementations. | Add `treeForVendor` and `included` hook implementations.
| JavaScript | mit | mmun/ember-component-attributes,mmun/ember-component-attributes |
9dcd369bcd7529f8c925d82a73111df72fbdd433 | index.js | index.js | /**
* @jsx React.DOM
*/
var React = require('react');
var Pdf = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
var self = this;
PDFJS.getDocument(this.props.file).then(function(pdf) {
pdf.getPage(self.props.page).then(function(page) {
self.setState({pdfPage: page, pdf: pdf});
});
});
},
componentWillReceiveProps: function(newProps) {
var self = this;
if (newProps.page) {
self.state.pdf.getPage(newProps.page).then(function(page) {
self.setState({pdfPage: page, pageId: newProps.page});
});
}
this.setState({
pdfPage: null
});
},
render: function() {
var self = this;
this.state.pdfPage && setTimeout(function() {
var canvas = self.getDOMNode(),
context = canvas.getContext('2d'),
scale = 1.0,
viewport = self.state.pdfPage.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
self.state.pdfPage.render(renderContext);
});
return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>;
}
});
module.exports = Pdf;
| /**
* @jsx React.DOM
*/
var React = require('react');
var Pdf = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
var self = this;
PDFJS.getDocument(this.props.file).then(function(pdf) {
pdf.getPage(self.props.page).then(function(page) {
self.setState({pdfPage: page, pdf: pdf});
});
});
},
componentWillReceiveProps: function(newProps) {
var self = this;
if (newProps.page) {
self.state.pdf.getPage(newProps.page).then(function(page) {
self.setState({pdfPage: page, pageId: newProps.page});
});
}
this.setState({
pdfPage: null
});
},
getDefaultProps: function() {
return {page: 1};
},
render: function() {
var self = this;
this.state.pdfPage && setTimeout(function() {
var canvas = self.getDOMNode(),
context = canvas.getContext('2d'),
scale = 1.0,
viewport = self.state.pdfPage.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
self.state.pdfPage.render(renderContext);
});
return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>;
}
});
module.exports = Pdf;
| Add default prop for page | Add default prop for page
| JavaScript | mit | nnarhinen/react-pdf,wojtekmaj/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,suancarloj/react-pdf,peergradeio/react-pdf,wojtekmaj/react-pdf,wojtekmaj/react-pdf,peergradeio/react-pdf,suancarloj/react-pdf,nnarhinen/react-pdf,suancarloj/react-pdf |
546a6787123156b39c9b7ac7c518e09edeaf9512 | app/utils/keys-map.js | app/utils/keys-map.js | import Ember from 'ember';
var configKeys, configKeysMap, languageConfigKeys;
languageConfigKeys = {
go: 'Go',
php: 'PHP',
node_js: 'Node.js',
perl: 'Perl',
perl6: 'Perl6',
python: 'Python',
scala: 'Scala',
smalltalk: 'Smalltalk',
ruby: 'Ruby',
d: 'D',
julia: 'Julia',
csharp: 'C#',
mono: 'Mono',
dart: 'Dart',
elixir: 'Elixir',
ghc: 'GHC',
haxe: 'Haxe',
jdk: 'JDK',
rvm: 'Ruby',
otp_release: 'OTP Release',
rust: 'Rust',
c: 'C',
cpp: 'C++',
clojure: 'Clojure',
lein: 'Lein',
compiler: 'Compiler',
crystal: 'Crystal',
osx_image: 'Xcode'
};
configKeys = {
env: 'ENV',
gemfile: 'Gemfile',
xcode_sdk: 'Xcode SDK',
xcode_scheme: 'Xcode Scheme',
compiler: 'Compiler',
os: 'OS'
};
configKeysMap = Ember.merge(configKeys, languageConfigKeys);
export default configKeysMap;
export { languageConfigKeys, configKeys };
| import Ember from 'ember';
var configKeys, configKeysMap, languageConfigKeys;
languageConfigKeys = {
go: 'Go',
php: 'PHP',
node_js: 'Node.js',
perl: 'Perl',
perl6: 'Perl6',
python: 'Python',
scala: 'Scala',
smalltalk: 'Smalltalk',
ruby: 'Ruby',
d: 'D',
julia: 'Julia',
csharp: 'C#',
mono: 'Mono',
dart: 'Dart',
elixir: 'Elixir',
ghc: 'GHC',
haxe: 'Haxe',
jdk: 'JDK',
rvm: 'Ruby',
otp_release: 'OTP Release',
rust: 'Rust',
c: 'C',
cpp: 'C++',
clojure: 'Clojure',
lein: 'Lein',
compiler: 'Compiler',
crystal: 'Crystal',
osx_image: 'Xcode',
r: 'R'
};
configKeys = {
env: 'ENV',
gemfile: 'Gemfile',
xcode_sdk: 'Xcode SDK',
xcode_scheme: 'Xcode Scheme',
compiler: 'Compiler',
os: 'OS'
};
configKeysMap = Ember.merge(configKeys, languageConfigKeys);
export default configKeysMap;
export { languageConfigKeys, configKeys };
| Add R language key for matrix column | Add R language key for matrix column
| JavaScript | mit | fauxton/travis-web,fotinakis/travis-web,fotinakis/travis-web,travis-ci/travis-web,fotinakis/travis-web,travis-ci/travis-web,fauxton/travis-web,fotinakis/travis-web,fauxton/travis-web,travis-ci/travis-web,fauxton/travis-web,travis-ci/travis-web |
275f8ce0c77ca79c32359d8780849684ed44bedb | samples/people/me.js | samples/people/me.js | // Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const {google} = require('googleapis');
const sampleClient = require('../sampleclient');
const plus = google.plus({
version: 'v1',
auth: sampleClient.oAuth2Client,
});
async function runSample() {
const res = await plus.people.get({userId: 'me'});
console.log(res.data);
}
const scopes = [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
];
if (module === require.main) {
sampleClient
.authenticate(scopes)
.then(runSample)
.catch(console.error);
}
| // Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const {google} = require('googleapis');
const sampleClient = require('../sampleclient');
const people = google.people({
version: 'v1',
auth: sampleClient.oAuth2Client,
});
async function runSample() {
// See documentation of personFields at
// https://developers.google.com/people/api/rest/v1/people/get
const res = await people.people.get({
resourceName: 'people/me',
personFields: 'emailAddresses,names,photos',
});
console.log(res.data);
}
const scopes = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
];
if (module === require.main) {
sampleClient
.authenticate(scopes)
.then(runSample)
.catch(console.error);
}
| Use people API instead of plus API | Use people API instead of plus API
Use people API instead of plus API
The plus API is being deprecated. This updates the sample code to use the people API instead.
Fixes #1600.
- [x] Tests and linter pass
- [x] Code coverage does not decrease (if any source code was changed)
- [x] Appropriate docs were updated (if necessary)
#1601 automerged by dpebot | JavaScript | apache-2.0 | googleapis/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,googleapis/google-api-nodejs-client,googleapis/google-api-nodejs-client |
b88c06ce00120abbfef8ea8fb2dfae8fe89f7160 | test.js | test.js | var sys = require("sys"),
stomp = require("./stomp");
var client = new stomp.Client("localhost", 61613);
client.subscribe("/queue/news", function(data){
console.log('received: ' + data.body);
});
client.publish('/queue/news','hello');
var repl = require('repl').start( 'stomp-test> ' );
repl.context.client = client;
| var sys = require("sys"),
stomp = require("./stomp");
var client = new stomp.Client("localhost", 61613);
client.subscribe("/queue/news", function(data){
console.log('received: ' + JSON.stringify(data));
});
client.publish('/queue/news','hello');
var repl = require('repl').start( 'stomp-test> ' );
repl.context.client = client;
| Test program now emits JSON strings of messages, not just message bodies | Test program now emits JSON strings of messages, not just message bodies
| JavaScript | agpl-3.0 | jbalonso/node-stomp-server |
86b3bd06d76d8ea3806acaf397cda97bff202127 | src/components/ControlsComponent.js | src/components/ControlsComponent.js | 'use strict';
import React from 'react';
require('styles//Controls.scss');
class ControlsComponent extends React.Component {
renderStopButton() {
if (this.props.isPlaying) {
return <button id="stop">Stop</button>
}
return <button id="stop" style={{display: 'none'}}>Stop</button>
}
renderPlayButton() {
if (this.props.isPlaying) {
return <button id="play" style={{display: 'none'}}>Play</button>
}
return <button id="play">Play</button>
}
render() {
return (
<div className="controls-component">
<button id="rewind">Rewind</button>
{this.renderStopButton()}
{this.renderPlayButton()}
<button id="forward">Forward</button>
</div>
);
}
}
ControlsComponent.displayName = 'ControlsComponent';
ControlsComponent.propTypes = {
isPlaying : React.PropTypes.bool.isRequired
};
ControlsComponent.defaultProps = {
isPlaying : true
};
export default ControlsComponent;
| 'use strict';
import React from 'react';
require('styles//Controls.scss');
class ControlsComponent extends React.Component {
renderStopButton() {
if (this.props.isPlaying) {
return <button id="stop">Stop</button>
}
return <button id="stop" style={{display: 'none'}}>Stop</button>
}
renderPlayButton() {
if (this.props.isPlaying) {
return <button id="play" style={{display: 'none'}}>Play</button>
}
return <button id="play">Play</button>
}
render() {
return (
<div className="controls-component">
<button id="previous">Previous</button>
{this.renderStopButton()}
{this.renderPlayButton()}
<button id="next">Next</button>
</div>
);
}
}
ControlsComponent.displayName = 'ControlsComponent';
ControlsComponent.propTypes = {
isPlaying : React.PropTypes.bool.isRequired,
onPrevious : React.PropTypes.func,
onStop : React.PropTypes.func,
onPlay : React.PropTypes.func,
onNext : React.PropTypes.func
};
ControlsComponent.defaultProps = {
isPlaying : true
};
export default ControlsComponent;
| Add props for the action trigger | Add props for the action trigger
| JavaScript | mit | C3-TKO/junkan,C3-TKO/junkan,C3-TKO/gaiyo,C3-TKO/gaiyo |
41bd5bdd133e5b6d74b76b454d1a5681ffb90201 | js/file.js | js/file.js | var save = (function() {
"use strict";
// saveAs from https://gist.github.com/MrSwitch/3552985
var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) {
return window.navigator.msSaveBlob(b, n);
} : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () {
// URL's
window.URL = window.URL || window.webkitURL;
if (!window.URL) {
return false;
}
return function (blob, name) {
var url = URL.createObjectURL(blob);
// Test for download link support
if ("download" in document.createElement('a')) {
var a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', name);
// Create Click event
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initMouseEvent("click", true, true, window, 0,
event.screenX, event.screenY, event.clientX, event.clientY,
event.ctrlKey, event.altKey, event.shiftKey, event.metaKey,
0, null);
// dispatch click event to simulate download
a.dispatchEvent(clickEvent);
} else {
// fallover, open resource in new tab.
window.open(url, '_blank', '');
}
};
})();
function save (text, fileName) {
var blob = new Blob([text], {
type: 'text/plain'
});
saveAs(blob, fileName || 'subtitle.srt');
}
return save;
})();
| var save = (function() {
"use strict";
// saveAs from https://gist.github.com/MrSwitch/3552985
var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) {
return window.navigator.msSaveBlob(b, n);
} : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () {
// URL's
window.URL = window.URL || window.webkitURL;
if (!window.URL) {
return false;
}
return function (blob, name) {
var url = URL.createObjectURL(blob);
// Test for download link support
if ("download" in document.createElement('a')) {
var a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', name);
// Create Click event
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initMouseEvent("click", true, true, window, 0,
0, 0, 0, 0, false, false, false, false, 0, null);
// dispatch click event to simulate download
a.dispatchEvent(clickEvent);
} else {
// fallover, open resource in new tab.
window.open(url, '_blank', '');
}
};
})();
function save (text, fileName) {
var blob = new Blob([text], {
type: 'text/plain'
});
saveAs(blob, fileName || 'subtitle.srt');
}
return save;
})();
| Fix ReferenceError in saveAs polyfill | Fix ReferenceError in saveAs polyfill
| JavaScript | mit | JMPerez/linkedin-to-json-resume,JMPerez/linkedin-to-json-resume |
e2235a00a2a5e375b1b2bacbf190bdc328445bd9 | js/main.js | js/main.js | var questions = [
Q1 = {
question: "What does HTML means?",
answer: "HyperText Markup Language"
},
Q2 = {
question: "What does CSS means?",
answer: "Cascading Style Sheet"
},
Q3 = {
question: "Why the \"C\" in CSS, is called Cascading?",
answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required"
}
];
var question = document.getElementById('question');
var questionNum = 0;
// Generate random number to display random QA set
function createNum() {
questionNum = Math.floor(Math.random() * 3);
}
createNum();
question.innerHTML = questions[questionNum].question;
| var questions = [
Q1 = {
question: "What does HTML means?",
answer: "HyperText Markup Language"
},
Q2 = {
question: "What does CSS means?",
answer: "Cascading Style Sheet"
},
Q3 = {
question: "Why the \"C\" in CSS, is called Cascading?",
answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required"
}
];
var question = document.getElementById('question');
var questionNum = 0;
// Generate random number to display random QA set
function createNum() {
questionNum = Math.floor(Math.random() * 3);
}
createNum();
question.innerHTML = questions[questionNum].question;
| Increase indention by 2 spaces | Increase indention by 2 spaces
| JavaScript | mit | vinescarlan/FlashCards,vinescarlan/FlashCards |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.