commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
10503ba849b7f43e18509e08bd26b66917fa84ea | src/config.js | src/config.js | module.exports = {
token: process.env.TOKEN || '1234567890abcdef',
settings: {
webHook: {
port: process.env.PORT || 443,
host: process.env.HOST || '0.0.0.0'
}
},
telegram: {
port: 443,
host: process.env.URL || 'https://rollrobot.herokuapp.com'
},
botan: {
token: process.env.TOKEN || '1234abcd-12ab-12ab-12ab-1234567890ab'
}
};
| module.exports = {
token: process.env.TOKEN || '1234567890abcdef',
settings: {
webHook: {
port: process.env.PORT || 443,
host: process.env.HOST || '0.0.0.0'
}
},
telegram: {
port: 443,
host: process.env.URL || 'https://rollrobot.herokuapp.com'
},
botan: {
token: process.env.BOTAN || '1234abcd-12ab-12ab-12ab-1234567890ab'
}
};
| Fix Botan token variable name | :bug: Fix Botan token variable name
| JavaScript | mit | edloidas/rollrobot | ---
+++
@@ -11,6 +11,6 @@
host: process.env.URL || 'https://rollrobot.herokuapp.com'
},
botan: {
- token: process.env.TOKEN || '1234abcd-12ab-12ab-12ab-1234567890ab'
+ token: process.env.BOTAN || '1234abcd-12ab-12ab-12ab-1234567890ab'
}
}; |
bc6633cdbfaccdec91725caf578c159e7bbd8baa | bin/cli.js | bin/cli.js | #!/usr/bin/env node
require('babel-polyfill');
var cli = require('../lib/cli');
cli.run(process);
| #!/usr/bin/env node
require('babel-polyfill');
var cli = require('../lib/cli');
cli.default.run(process);
| Use `.default` to access exported function | Use `.default` to access exported function
| JavaScript | mit | Springworks/node-scale-reader | ---
+++
@@ -3,4 +3,4 @@
require('babel-polyfill');
var cli = require('../lib/cli');
-cli.run(process);
+cli.default.run(process); |
b41e1a78f7ac0fa996b290391273cd70d6375193 | test/components/control.js | test/components/control.js | import React from 'react/addons';
let find = React.addons.TestUtils.findRenderedDOMComponentWithTag;
let render = React.addons.TestUtils.renderIntoDocument;
let Control = reqmod('components/control');
/**
* Control components are those little icon based buttons, which can be toggled
* active.
*/
describe('components/control', () => {
it('should render correctly', () => {
// First we render the actual 'control' component into our 'document'.
let controlComponent = render(
<Control icon="book" onClick={() => {}} />
);
// Next we check that it has the correct class... It should not be
// toggled 'active' by default.
controlComponent.getDOMNode().className.should.equal('control');
// Retrieve the actual 'icon' component from inside the 'control'.
let iconComponent = find(controlComponent, 'span');
// Make sure the 'book' icon is reflected in the CSS classes.
iconComponent.getDOMNode().className.should.endWith('fa-book');
});
it('should be able to be toggled active', () => {
let controlComponent = render(
<Control icon="book" onClick={() => {}} active={true} />
);
controlComponent.getDOMNode().className.should.endWith('active');
});
});
| import React from 'react/addons';
let find = React.addons.TestUtils.findRenderedDOMComponentWithTag;
let render = React.addons.TestUtils.renderIntoDocument;
let Control = reqmod('components/control');
// Since we don't want React warnings about some deprecated stuff being spammed
// in our test run, we disable the warnings with this...
console.warn = () => { }
/**
* Control components are those little icon based buttons, which can be toggled
* active.
*/
describe('components/control', () => {
it('should render correctly', () => {
// First we render the actual 'control' component into our 'document'.
let controlComponent = render(
<Control icon="book" onClick={() => {}} />
);
// Next we check that it has the correct class... It should not be
// toggled 'active' by default.
controlComponent.getDOMNode().className.should.equal('control');
// Retrieve the actual 'icon' component from inside the 'control'.
let iconComponent = find(controlComponent, 'span');
// Make sure the 'book' icon is reflected in the CSS classes.
iconComponent.getDOMNode().className.should.endWith('fa-book');
});
it('should be able to be toggled active', () => {
let controlComponent = render(
<Control icon="book" onClick={() => {}} active={true} />
);
controlComponent.getDOMNode().className.should.endWith('active');
});
});
| Add an override to console.warn for testing to suppress React warnings. | Add an override to console.warn for testing to suppress React warnings.
| JavaScript | mit | melonmanchan/teamboard-client-react,JanKuukkanen/Oauth-client-react,JanKuukkanen/Oauth-client-react,N4SJAMK/teamboard-client-react,tanelih/teamboard-client-react,melonmanchan/teamboard-client-react,santtusulander/teamboard-client-react,N4SJAMK/teamboard-client-react,santtusulander/teamboard-client-react,nikolauska/teamboard-client-react,AatuPitkanen/teamboard-client-react,AatuPitkanen/teamboard-client-react,JanKuukkanen/teamboard-client-react,nikolauska/teamboard-client-react,tanelih/teamboard-client-react,JanKuukkanen/teamboard-client-react | ---
+++
@@ -4,6 +4,10 @@
let render = React.addons.TestUtils.renderIntoDocument;
let Control = reqmod('components/control');
+
+// Since we don't want React warnings about some deprecated stuff being spammed
+// in our test run, we disable the warnings with this...
+console.warn = () => { }
/**
* Control components are those little icon based buttons, which can be toggled |
fd876469738834dc91e5ce179e2ccd9bc18ab37a | ui/app/serializers/node.js | ui/app/serializers/node.js | import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
config: service(),
attrs: {
isDraining: 'Drain',
httpAddr: 'HTTPAddr',
},
normalize(modelClass, hash) {
// Transform map-based objects into an array-based fragment lists
const drivers = hash.Drivers || {};
hash.Drivers = Object.keys(drivers).map(key => {
return assign({}, drivers[key], { Name: key });
});
const hostVolumes = hash.HostVolumes || {};
hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]);
return this._super(modelClass, hash);
},
extractRelationships(modelClass, hash) {
const { modelName } = modelClass;
const nodeURL = this.store
.adapterFor(modelName)
.buildURL(modelName, this.extractId(modelClass, hash), hash, 'findRecord');
return {
allocations: {
links: {
related: `${nodeURL}/allocations`,
},
},
};
},
});
| import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
config: service(),
attrs: {
isDraining: 'Drain',
httpAddr: 'HTTPAddr',
},
normalize(modelClass, hash) {
// Transform map-based objects into an array-based fragment lists
const drivers = hash.Drivers || {};
hash.Drivers = Object.keys(drivers).map(key => {
return assign({}, drivers[key], { Name: key });
});
if (hash.HostVolumes) {
const hostVolumes = hash.HostVolumes;
hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]);
}
return this._super(modelClass, hash);
},
extractRelationships(modelClass, hash) {
const { modelName } = modelClass;
const nodeURL = this.store
.adapterFor(modelName)
.buildURL(modelName, this.extractId(modelClass, hash), hash, 'findRecord');
return {
allocations: {
links: {
related: `${nodeURL}/allocations`,
},
},
};
},
});
| Fix a bug where the NodeListStub API response would override existing HostVolumes in the store | Fix a bug where the NodeListStub API response would override existing HostVolumes in the store
| JavaScript | mpl-2.0 | hashicorp/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,burdandrei/nomad,dvusboy/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,burdandrei/nomad,burdandrei/nomad,burdandrei/nomad,dvusboy/nomad,dvusboy/nomad,dvusboy/nomad,dvusboy/nomad,burdandrei/nomad,dvusboy/nomad,burdandrei/nomad | ---
+++
@@ -17,8 +17,10 @@
return assign({}, drivers[key], { Name: key });
});
- const hostVolumes = hash.HostVolumes || {};
- hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]);
+ if (hash.HostVolumes) {
+ const hostVolumes = hash.HostVolumes;
+ hash.HostVolumes = Object.keys(hostVolumes).map(key => hostVolumes[key]);
+ }
return this._super(modelClass, hash);
}, |
0b9bed076bac3f942e904a5e8388880af515ced0 | api/db/user.js | api/db/user.js | 'use strict'
module.exports = function (sequelize, DataTypes) {
let User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING(1024),
allowNull: false
},
salt: {
type: DataTypes.STRING,
allowNull: true
},
nicknames: {
type: 'citext[]',
allowNull: true,
defaultValue: 'ARRAY[]::citext[]'
},
drilled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
drilledDispatch: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
group: {
type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
allowNull: false,
defaultValue: 'normal'
},
dispatch: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: null,
unique: true
}
}, {
paranoid: true,
classMethods: {
associate: function (models) {
User.hasMany(models.Rat, { as: 'rats' })
}
}
})
return User
}
| 'use strict'
module.exports = function (sequelize, DataTypes) {
let User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
email: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING(1024),
allowNull: false
},
salt: {
type: DataTypes.STRING,
allowNull: true
},
nicknames: {
type: 'citext[]',
allowNull: true,
defaultValue: sequelize.literal('ARRAY[]::citext[]')
},
drilled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
drilledDispatch: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
group: {
type: DataTypes.ENUM('normal', 'overseer', 'moderator', 'admin'),
allowNull: false,
defaultValue: 'normal'
},
dispatch: {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: null,
unique: true
}
}, {
paranoid: true,
classMethods: {
associate: function (models) {
User.hasMany(models.Rat, { as: 'rats' })
}
}
})
return User
}
| Use literal function for citext array default value, not string | Use literal function for citext array default value, not string
| JavaScript | bsd-3-clause | FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com | ---
+++
@@ -22,7 +22,7 @@
nicknames: {
type: 'citext[]',
allowNull: true,
- defaultValue: 'ARRAY[]::citext[]'
+ defaultValue: sequelize.literal('ARRAY[]::citext[]')
},
drilled: {
type: DataTypes.BOOLEAN, |
ed6eed2c1f589c179cb57d9386f29cbfdbf1fc37 | packages/rocketchat-ui-sidenav/client/sidebarItem.js | packages/rocketchat-ui-sidenav/client/sidebarItem.js | /* globals menu */
Template.sidebarItem.helpers({
canLeave() {
const roomData = Session.get(`roomData${ this.rid }`);
if (!roomData) { return false; }
if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) {
return false;
} else {
return true;
}
}
});
Template.sidebarItem.events({
'click [data-id], click .sidebar-item__link'() {
return menu.close();
}
});
Template.sidebarItem.onCreated(function() {
// console.log('sidebarItem', this.data);
});
| /* globals menu popover */
Template.sidebarItem.helpers({
canLeave() {
const roomData = Session.get(`roomData${ this.rid }`);
if (!roomData) { return false; }
if (((roomData.cl != null) && !roomData.cl) || (roomData.t === 'd')) {
return false;
} else {
return true;
}
}
});
Template.sidebarItem.events({
'click [data-id], click .sidebar-item__link'() {
return menu.close();
},
'click .sidebar-item__menu'(e) {
const config = {
popoverClass: 'sidebar-item',
columns: [
{
groups: [
{
items: [
{
icon: 'eye-off',
name: t('Hide_room'),
type: 'sidebar-item',
id: 'hide'
},
{
icon: 'sign-out',
name: t('Leave_room'),
type: 'sidebar-item',
id: 'leave'
}
]
}
]
}
],
mousePosition: {
x: e.clientX,
y: e.clientY
},
data: {
template: this.t,
rid: this.rid,
name: this.name
}
};
popover.open(config);
}
});
Template.sidebarItem.onCreated(function() {
// console.log('sidebarItem', this.data);
});
| Add leave and hide buttons again | Add leave and hide buttons again | JavaScript | mit | NexFive/DrustChat,NexFive/DrustChat,NexFive/DrustChat,NexFive/DrustChat | ---
+++
@@ -1,4 +1,4 @@
-/* globals menu */
+/* globals menu popover */
Template.sidebarItem.helpers({
canLeave() {
@@ -17,6 +17,44 @@
Template.sidebarItem.events({
'click [data-id], click .sidebar-item__link'() {
return menu.close();
+ },
+ 'click .sidebar-item__menu'(e) {
+ const config = {
+ popoverClass: 'sidebar-item',
+ columns: [
+ {
+ groups: [
+ {
+ items: [
+ {
+ icon: 'eye-off',
+ name: t('Hide_room'),
+ type: 'sidebar-item',
+ id: 'hide'
+ },
+ {
+ icon: 'sign-out',
+ name: t('Leave_room'),
+ type: 'sidebar-item',
+ id: 'leave'
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ mousePosition: {
+ x: e.clientX,
+ y: e.clientY
+ },
+ data: {
+ template: this.t,
+ rid: this.rid,
+ name: this.name
+ }
+ };
+
+ popover.open(config);
}
});
|
9c6ee2b1a02d751bb4a1134a2a0d07e531d50acd | examples/simple-svg/app/stores/circle.js | examples/simple-svg/app/stores/circle.js | import { animate } from '../actions/animate'
const Circle = {
getInitialState() {
return Circle.set(null, { color: 'orange', time: Date.now() })
},
set (_, { color, time }) {
let sin = Math.sin(time / 200)
let cos = Math.cos(time / 200)
return {
color : color,
cx : 50 * sin,
cy : 35 * cos,
r : 12 + (8 * cos)
}
},
register () {
return {
[animate.loadings] : Circle.set,
[animate.done] : Circle.set
}
}
}
export default Circle
| import { animate } from '../actions/animate'
const Circle = {
getInitialState() {
return Circle.set(null, { color: 'orange', time: Date.now() })
},
set (_, { color, time }) {
let sin = Math.sin(time / 200)
let cos = Math.cos(time / 200)
return {
color : color,
cx : 50 * sin,
cy : 35 * cos,
r : 12 + (8 * cos)
}
},
register () {
return {
[animate.loading] : Circle.set,
[animate.done] : Circle.set
}
}
}
export default Circle
| Remove intentional error added for error reporting. | Remove intentional error added for error reporting.
| JavaScript | mit | vigetlabs/microcosm,leobauza/microcosm,leobauza/microcosm,vigetlabs/microcosm,leobauza/microcosm,vigetlabs/microcosm | ---
+++
@@ -20,7 +20,7 @@
register () {
return {
- [animate.loadings] : Circle.set,
+ [animate.loading] : Circle.set,
[animate.done] : Circle.set
}
} |
461893aac3ec8cd55caa2946b015891a9daff0cc | lib/engine/buildDigest.js | lib/engine/buildDigest.js | const _ = require('lodash'),
fstate = require('../util/fstate'),
digest = require('../util/digest'),
hashcache = require('../util/hashcache'),
log = require('../util/log')
;
function buildDigest(buildDir, cb) {
fstate(buildDir, { includeDirectories: true }, (err, files) => {
if (err) return cb(err);
const buildId = digest(_.map(
_.sortBy(files, 'relPath'),
fileInfo => hashcache(fileInfo.absPath)).join(' '), 'base64');
log.verbose(`Current build-digest for ${buildDir} is "${buildId}"`);
return cb(null, buildId);
});
}
module.exports = _.debounce(buildDigest, 300);
| const _ = require('lodash'),
fstate = require('../util/fstate'),
digest = require('../util/digest'),
hashcache = require('../util/hashcache'),
log = require('../util/log')
;
function buildDigest(buildDir, cb) {
fstate(buildDir, (err, files) => {
if (err) return cb(err);
const buildId = digest(_.map(
_.sortBy(files, 'relPath'),
fileInfo => hashcache(fileInfo.absPath)).join(' '), 'base64');
log.verbose(`Current build-digest for ${buildDir} is "${buildId}"`);
return cb(null, buildId);
});
}
module.exports = _.debounce(buildDigest, 300);
| Exclude directories from build digest. | Exclude directories from build digest.
| JavaScript | mit | Iceroad/martinet,Iceroad/martinet,Iceroad/martinet | ---
+++
@@ -7,7 +7,7 @@
function buildDigest(buildDir, cb) {
- fstate(buildDir, { includeDirectories: true }, (err, files) => {
+ fstate(buildDir, (err, files) => {
if (err) return cb(err);
const buildId = digest(_.map( |
de04f9e1f50dc38e70cb4b47271829042dc9b301 | client/reducers/index.js | client/reducers/index.js | import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import { reducer as formReducer } from 'redux-form';
import auth from './userSignUp';
import login from './login';
import book from './book';
import favorites from './favorites';
import profile from './profile';
import { books, mostUpvotedBooks } from './books';
const rootReducer = combineReducers({
form: formReducer,
auth,
login,
books,
book,
mostUpvotedBooks,
favorites,
profile,
routing: routerReducer,
});
export default rootReducer;
| import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import { reducer as formReducer } from 'redux-form';
import auth from './userSignUp';
import login from './login';
import book from './book';
import favorites from './favorites';
import profile from './profile';
import addBook from './addBook';
import { books, mostUpvotedBooks } from './books';
const rootReducer = combineReducers({
form: formReducer,
auth,
login,
books,
book,
addBook,
mostUpvotedBooks,
favorites,
profile,
routing: routerReducer,
});
export default rootReducer;
| Add addBook reducer to root reducer | Add addBook reducer to root reducer
| JavaScript | mit | amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books | ---
+++
@@ -6,6 +6,7 @@
import book from './book';
import favorites from './favorites';
import profile from './profile';
+import addBook from './addBook';
import { books, mostUpvotedBooks } from './books';
const rootReducer = combineReducers({
@@ -14,6 +15,7 @@
login,
books,
book,
+ addBook,
mostUpvotedBooks,
favorites,
profile, |
a7af375c66552df8a73f945679b1ff01f95c6f36 | client/webpack.common.js | client/webpack.common.js | const path = require('path');
const cleanWebPackPlugin = require('clean-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [
new cleanWebPackPlugin(['dist']),
],
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
},
exclude: /node_modules/,
},
{
test: /\.scss$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" },
]
},
{
test: /\.(png|svg|gif|jpg)$/,
use: {
loader: 'file-loader',
},
},
],
},
};
| const path = require('path');
const cleanWebPackPlugin = require('clean-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [
new cleanWebPackPlugin(['dist']),
],
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: {
cacheDirectory: true,
plugins: ['react-hot-loader/babel'],
},
exclude: /node_modules/,
},
{
test: /\.scss$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'sass-loader' },
]
},
{
test: /\.(png|svg|gif|jpg)$/,
use: {
loader: 'file-loader',
},
},
],
},
};
| Set up hot module replacement for react components | Set up hot module replacement for react components
| JavaScript | mit | amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books | ---
+++
@@ -14,17 +14,19 @@
rules: [
{
test: /\.js$/,
- use: {
- loader: 'babel-loader',
+ loader: 'babel-loader',
+ options: {
+ cacheDirectory: true,
+ plugins: ['react-hot-loader/babel'],
},
exclude: /node_modules/,
},
{
test: /\.scss$/,
use: [
- { loader: "style-loader" },
- { loader: "css-loader" },
- { loader: "sass-loader" },
+ { loader: 'style-loader' },
+ { loader: 'css-loader' },
+ { loader: 'sass-loader' },
]
},
{ |
219639c6d2d3df9b6126b1cb6407173d95a53d80 | packages/soya-next/src/cookies/withCookiesPage.js | packages/soya-next/src/cookies/withCookiesPage.js | import React from "react";
import PropTypes from "prop-types";
import hoistStatics from "hoist-non-react-statics";
import { Cookies } from "react-cookie";
import getDisplayName from "../utils/getDisplayName";
import { NEXT_STATICS } from "../constants/Statics";
export default Page => {
class WithCookies extends React.Component {
static displayName = getDisplayName("WithCookies", Page);
static propTypes = {
cookies: PropTypes.oneOfType([
PropTypes.shape({
cookies: PropTypes.objectOf(PropTypes.string)
}),
PropTypes.instanceOf(Cookies)
]).isRequired
};
static async getInitialProps(ctx) {
const cookies = ctx.req ? ctx.req.universalCookies : new Cookies();
const props =
Page.getInitialProps &&
(await Page.getInitialProps({ ...ctx, cookies }));
return {
...props,
cookies
};
}
constructor(props) {
super(props);
this.cookies = process.browser ? new Cookies() : props.cookies;
}
render() {
const { ...props } = this.props;
delete props.cookies;
return <Page {...props} cookies={this.cookies} />;
}
}
return hoistStatics(WithCookies, Page, NEXT_STATICS);
};
| import React from "react";
import PropTypes from "prop-types";
import hoistStatics from "hoist-non-react-statics";
import { Cookies } from "react-cookie";
import getDisplayName from "../utils/getDisplayName";
import { NEXT_STATICS } from "../constants/Statics";
export default Page => {
class WithCookies extends React.Component {
static displayName = getDisplayName("WithCookies", Page);
static propTypes = {
cookies: PropTypes.oneOfType([
PropTypes.shape({
cookies: PropTypes.objectOf(PropTypes.string)
}),
PropTypes.instanceOf(Cookies)
]).isRequired
};
static async getInitialProps(ctx) {
const cookies = (ctx.req && ctx.req.universalCookies) || new Cookies();
const props =
Page.getInitialProps &&
(await Page.getInitialProps({ ...ctx, cookies }));
return {
...props,
cookies
};
}
constructor(props) {
super(props);
this.cookies = process.browser ? new Cookies() : props.cookies;
}
render() {
const { ...props } = this.props;
delete props.cookies;
return <Page {...props} cookies={this.cookies} />;
}
}
return hoistStatics(WithCookies, Page, NEXT_STATICS);
};
| Fix undefined cookies on server | Fix undefined cookies on server
| JavaScript | mit | traveloka/soya-next | ---
+++
@@ -19,7 +19,7 @@
};
static async getInitialProps(ctx) {
- const cookies = ctx.req ? ctx.req.universalCookies : new Cookies();
+ const cookies = (ctx.req && ctx.req.universalCookies) || new Cookies();
const props =
Page.getInitialProps &&
(await Page.getInitialProps({ ...ctx, cookies })); |
92d8cf6dbaa7145f225366a874f1b69a6382b1c3 | server/helpers/subscriptionManager.js | server/helpers/subscriptionManager.js | // import { RedisPubSub } from 'graphql-redis-subscriptions';
import { PubSub } from 'graphql-subscriptions';
const pubsub = new PubSub();
/*
const pubsub = new RedisPubSub({
connection: {
host: 'redis.ralexanderson.com',
port: 6379,
},
});*/
export { pubsub };
| // import { RedisPubSub } from 'graphql-redis-subscriptions';
import { PubSub } from "graphql-subscriptions";
const pubsub = new PubSub();
/*
const pubsub = new RedisPubSub({
connection: {
host: 'redis.ralexanderson.com',
port: 6379,
},
});*/
pubsub.ee.setMaxListeners(150);
export { pubsub };
| Increase the max event listener count | Increase the max event listener count
| JavaScript | apache-2.0 | Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium,Thorium-Sim/thorium | ---
+++
@@ -1,5 +1,5 @@
// import { RedisPubSub } from 'graphql-redis-subscriptions';
-import { PubSub } from 'graphql-subscriptions';
+import { PubSub } from "graphql-subscriptions";
const pubsub = new PubSub();
/*
@@ -10,5 +10,6 @@
},
});*/
+pubsub.ee.setMaxListeners(150);
+
export { pubsub };
- |
a20e046f7b866fe23a6cb6547653ab97107deac9 | frontend/src/store.js | frontend/src/store.js | import { createStore, applyMiddleware, compose } from 'redux'
import { browserHistory} from 'react-router'
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux'
import createReducer from './reducers'
import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'
export default function configureStore(initialState = {}) {
const sagaMiddleware = createSagaMiddleware()
const history = browserHistory
const middlewares = [
sagaMiddleware,
routerMiddleware(history)
]
const enhancers = [
applyMiddleware(...middlewares)
]
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
const store = createStore(
createReducer(),
initialState,
composeEnhancers(...enhancers)
)
const syncedHistory = syncHistoryWithStore(history, store)
sagaMiddleware.run(rootSaga, syncedHistory)
return {
store,
history: syncedHistory
}
}
| import { createStore, applyMiddleware, compose } from 'redux'
import { browserHistory } from 'react-router'
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux'
import createReducer from './reducers'
import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'
export default function configureStore(initialState = {}) {
const sagaMiddleware = createSagaMiddleware()
const middlewares = [
sagaMiddleware,
routerMiddleware(browserHistory)
]
const enhancers = [
applyMiddleware(...middlewares)
]
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
const store = createStore(
createReducer(),
initialState,
composeEnhancers(...enhancers)
)
sagaMiddleware.run(rootSaga, browserHistory)
return {
store,
history: syncHistoryWithStore(browserHistory, store)
}
}
| Fix duplicated calls of sagas based on history | Fix duplicated calls of sagas based on history
| JavaScript | mit | luxons/seven-wonders,luxons/seven-wonders,luxons/seven-wonders | ---
+++
@@ -1,5 +1,5 @@
import { createStore, applyMiddleware, compose } from 'redux'
-import { browserHistory} from 'react-router'
+import { browserHistory } from 'react-router'
import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux'
import createReducer from './reducers'
@@ -8,11 +8,10 @@
export default function configureStore(initialState = {}) {
const sagaMiddleware = createSagaMiddleware()
- const history = browserHistory
const middlewares = [
sagaMiddleware,
- routerMiddleware(history)
+ routerMiddleware(browserHistory)
]
const enhancers = [
@@ -31,12 +30,10 @@
composeEnhancers(...enhancers)
)
- const syncedHistory = syncHistoryWithStore(history, store)
-
- sagaMiddleware.run(rootSaga, syncedHistory)
+ sagaMiddleware.run(rootSaga, browserHistory)
return {
store,
- history: syncedHistory
+ history: syncHistoryWithStore(browserHistory, store)
}
} |
bea0e08a0f75d9ce5cd5f661db0aca50e678534c | lib/tooltip/fix-button.js | lib/tooltip/fix-button.js | /* @flow */
import React from 'react'
class FixButton extends React.Component {
handleClick(): void {
this.props.cb()
}
render() {
return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button>
}
}
module.exports = FixButton
| /* @flow */
import React from 'react'
class FixButton extends React.Component {
props: {
cb: () => void,
};
handleClick(): void {
this.props.cb()
}
render() {
return <button className="fix-btn" onClick={() => this.handleClick()}>Fix</button>
}
}
module.exports = FixButton
| Add props declaration of FixButton | Add props declaration of FixButton
To fix CI error
| JavaScript | mit | steelbrain/linter-ui-default,steelbrain/linter-ui-default,AtomLinter/linter-ui-default | ---
+++
@@ -3,6 +3,9 @@
import React from 'react'
class FixButton extends React.Component {
+ props: {
+ cb: () => void,
+ };
handleClick(): void {
this.props.cb()
} |
98df85a394c3d3b64f017cfcf8481dead53bd858 | components/CopyButton.js | components/CopyButton.js | import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
import levelNames from "../constants/levelNames";
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
// this.setState({ isSuccessMsgShow: true });
const copyBtnRef = this.copyBtnRef.current;
copyBtnRef.setAttribute('data-balloon', '複製成功!');
copyBtnRef.setAttribute('data-balloon-visible', '');
copyBtnRef.setAttribute('data-balloon-pos', 'up');
setTimeout(function() {
copyBtnRef.removeAttribute('data-balloon');
copyBtnRef.removeAttribute('data-balloon-visible');
copyBtnRef.removeAttribute('data-balloon-pos');
}, 3000);
});
}
render() {
return (
<button
ref={this.copyBtnRef}
key="copy"
onClick={() => {}}
className="btn-copy"
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
| import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
export default class CopyButton extends React.PureComponent {
constructor(props) {
super(props);
this.copyBtnRef = React.createRef();
this.clipboardRef = React.createRef();
}
static defaultProps = {
content: '',
};
state = {
btnAttributes: {},
};
componentDidMount() {
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
const self = this;
this.setState({
btnAttributes: {
'data-balloon': '複製成功!',
'data-balloon-visible': '',
'data-balloon-pos': 'up',
}});
setTimeout(function() {
self.setState({ btnAttributes: {} });
}, 1000);
});
}
render() {
return (
<button
ref={this.copyBtnRef}
key="copy"
onClick={() => {}}
className="btn-copy"
{ ...this.state.btnAttributes }
>
複製到剪貼簿
<style jsx>{`
.btn-copy {
margin-left: 10px;
}
`}</style>
</button>
);
}
}
| Use attribute object from state | Use attribute object from state
| JavaScript | mit | cofacts/rumors-site,cofacts/rumors-site | ---
+++
@@ -1,7 +1,6 @@
import React from 'react';
import ClipboardJS from 'clipboard';
import 'balloon-css/balloon.css';
-import levelNames from "../constants/levelNames";
export default class CopyButton extends React.PureComponent {
constructor(props) {
@@ -13,23 +12,26 @@
static defaultProps = {
content: '',
};
+ state = {
+ btnAttributes: {},
+ };
componentDidMount() {
-
this.clipboardRef.current = new ClipboardJS(this.copyBtnRef.current, {
text: () => this.props.content,
});
this.clipboardRef.current.on('success', () => {
- // this.setState({ isSuccessMsgShow: true });
- const copyBtnRef = this.copyBtnRef.current;
- copyBtnRef.setAttribute('data-balloon', '複製成功!');
- copyBtnRef.setAttribute('data-balloon-visible', '');
- copyBtnRef.setAttribute('data-balloon-pos', 'up');
+ const self = this;
+ this.setState({
+ btnAttributes: {
+ 'data-balloon': '複製成功!',
+ 'data-balloon-visible': '',
+ 'data-balloon-pos': 'up',
+ }});
+
setTimeout(function() {
- copyBtnRef.removeAttribute('data-balloon');
- copyBtnRef.removeAttribute('data-balloon-visible');
- copyBtnRef.removeAttribute('data-balloon-pos');
- }, 3000);
+ self.setState({ btnAttributes: {} });
+ }, 1000);
});
}
@@ -40,6 +42,7 @@
key="copy"
onClick={() => {}}
className="btn-copy"
+ { ...this.state.btnAttributes }
>
複製到剪貼簿
<style jsx>{` |
5ce70bfc71c927a7abce4de2a1ac5840003ceebd | src/js/Helpers/VectorHelpers.js | src/js/Helpers/VectorHelpers.js | const massToRadius = mass => Math.log2(mass)/10;
const translate = (object3D, velocity) => {
object3D.translateX(velocity.x);
object3D.translateY(velocity.y);
object3D.translateZ(velocity.z);
}
const rand = (min, max) => min + Math.random()*(max - min);
const vLog = (v, msg) => console.log(msg, JSON.stringify(v.toArray()));
const filterClose = (dancers, position, radius) => (
dancers.filter(dancer => dancer.position.distanceTo(position) > radius)
);
const vectorToString = vector => {
return vector.toArray().map(component => +component.toString().slice(0,15)).join(' ')
};
const objToArr = obj => {
const result = [];
for (var i = 0; i < obj.length; i++) { result.push(obj[i]); }
return result;
};
export {
massToRadius,
translate,
rand,
vLog,
filterClose,
vectorToString,
objToArr,
}
| const massToRadius = mass => Math.log2(mass)/10;
const translate = (object3D, velocity) => {
object3D.translateX(velocity.x);
object3D.translateY(velocity.y);
object3D.translateZ(velocity.z);
}
const getR = (body1, body2) => body2.position.sub(body1.position);
const rand = (min, max) => min + Math.random()*(max - min);
const vLog = (v, msg) => console.log(msg, JSON.stringify(v.toArray()));
const filterClose = (dancers, position, radius) => (
dancers.filter(dancer => dancer.position.distanceTo(position) > radius)
);
const vectorToString = vector => {
return vector.toArray().map(component => +component.toString().slice(0,15)).join(' ')
};
const objToArr = obj => {
const result = [];
for (var i = 0; i < obj.length; i++) { result.push(obj[i]); }
return result;
};
export {
massToRadius,
getR,
translate,
rand,
vLog,
filterClose,
vectorToString,
objToArr,
}
| Add function to get displacement (vR) vector | Add function to get displacement (vR) vector
| JavaScript | mit | elliotaplant/celestial-dance,elliotaplant/celestial-dance | ---
+++
@@ -5,6 +5,8 @@
object3D.translateY(velocity.y);
object3D.translateZ(velocity.z);
}
+
+const getR = (body1, body2) => body2.position.sub(body1.position);
const rand = (min, max) => min + Math.random()*(max - min);
@@ -26,6 +28,7 @@
export {
massToRadius,
+ getR,
translate,
rand,
vLog, |
f163eac1c635e9573cc2c11083312acd0cce9c21 | src/land_registry_elements/email-repeat/EmailRepeat.js | src/land_registry_elements/email-repeat/EmailRepeat.js | /* global $ */
'use strict'
/**
* Email repeat
*/
function EmailRepeat (element, config) {
var options = {}
$.extend(options, config)
// Private variables
var hintWrapper
var hint
/**
* Set everything up
*/
function create () {
// Bail out if we don't have the proper element to act upon
if (!element) {
return
}
hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p><p class="bold email-hint-value"></p></div>')
hint = $(hintWrapper).find('.email-hint-value')
$(element).on('change', updateHint)
$(element).on('input', updateHint)
}
/**
*
*/
function updateHint () {
$(element).after(hintWrapper)
// If the input field gets emptied out again, remove the hint
if (element.value.length === 0) {
hintWrapper.remove()
return
}
// Update the hint to match the input value
hint.text(element.value)
}
/**
* Tear everything down again
*/
function destroy () {
hintWrapper.remove()
$(element).off('change', updateHint)
$(element).off('input', updateHint)
}
var self = {
create: create,
destroy: destroy
}
return self
}
export { EmailRepeat }
| /* global $ */
'use strict'
/**
* Email repeat
*/
function EmailRepeat (element, config) {
var options = {}
$.extend(options, config)
// Private variables
var hintWrapper
var hint
/**
* Set everything up
*/
function create () {
// Bail out if we don't have the proper element to act upon
if (!element) {
return
}
hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p></div>')
hint = $('<p class="bold email-hint-value"></p>')
$(hintWrapper).append(hint)
$(element).on('change', updateHint)
$(element).on('input', updateHint)
}
/**
*
*/
function updateHint () {
$(element).after(hintWrapper)
// If the input field gets emptied out again, remove the hint
if (element.value.length === 0) {
hintWrapper.remove()
return
}
// Update the hint to match the input value
hint.text(element.value)
}
/**
* Tear everything down again
*/
function destroy () {
hintWrapper.remove()
$(element).off('change', updateHint)
$(element).off('input', updateHint)
}
var self = {
create: create,
destroy: destroy
}
return self
}
export { EmailRepeat }
| Fix IE8 bug with email repeat | Fix IE8 bug with email repeat
| JavaScript | mit | LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements | ---
+++
@@ -22,9 +22,10 @@
return
}
- hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p><p class="bold email-hint-value"></p></div>')
+ hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p></div>')
- hint = $(hintWrapper).find('.email-hint-value')
+ hint = $('<p class="bold email-hint-value"></p>')
+ $(hintWrapper).append(hint)
$(element).on('change', updateHint)
$(element).on('input', updateHint) |
67a3aee413c05e895ed200b6cb1912bcebd538dd | eloquent_js_exercises/chapter05/chapter05_ex04.js | eloquent_js_exercises/chapter05/chapter05_ex04.js | function every(array, test) {
for (var i = 0; i < array.length; ++i) {
if (!test(array[i]))
return false;
}
return true;
}
function some(array, test) {
for (var i = 0; i < array.length; ++i) {
if (test(array[i]))
return true;
}
return false;
}
| function dominantDirection(text) {
let scripts = countBy(text, char => {
let script = characterScript(char.codePointAt(0));
return script ? script.direction : "none";
}).filter(({name}) => name != "none");
return scripts.reduce((a, b) => a.count > b.count ? a : b).name;
}
| Add Chapter 05, exercise 4 | Add Chapter 05, exercise 4
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,15 +1,8 @@
-function every(array, test) {
- for (var i = 0; i < array.length; ++i) {
- if (!test(array[i]))
- return false;
- }
- return true;
+function dominantDirection(text) {
+ let scripts = countBy(text, char => {
+ let script = characterScript(char.codePointAt(0));
+ return script ? script.direction : "none";
+ }).filter(({name}) => name != "none");
+
+ return scripts.reduce((a, b) => a.count > b.count ? a : b).name;
}
-
-function some(array, test) {
- for (var i = 0; i < array.length; ++i) {
- if (test(array[i]))
- return true;
- }
- return false;
-} |
4f6299f4e88e89c0cd0971f318eef6823ae0cfc2 | src/js/utils/Announcer.js | src/js/utils/Announcer.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import CSSClassnames from './CSSClassnames';
const CLASS_ROOT = CSSClassnames.APP;
function clearAnnouncer() {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
announcer.innerHTML = '';
};
export function announcePageLoaded (title) {
announce(`${title} page was loaded`);
}
export function announce (message, mode = 'assertive') {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
announcer.setAttribute('aria-live', 'off');
announcer.innerHTML = message;
setTimeout(clearAnnouncer, 500);
announcer.setAttribute('aria-live', mode);
}
export default { announce, announcePageLoaded };
| // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import CSSClassnames from './CSSClassnames';
const CLASS_ROOT = CSSClassnames.APP;
function clearAnnouncer() {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
if(announcer) {
announcer.innerHTML = '';
}
};
export function announcePageLoaded (title) {
announce(`${title} page was loaded`);
}
export function announce (message, mode = 'assertive') {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
if(announcer) {
announcer.setAttribute('aria-live', 'off');
announcer.innerHTML = message;
setTimeout(clearAnnouncer, 500);
announcer.setAttribute('aria-live', mode);
}
}
export default { announce, announcePageLoaded };
| Fix exceptions when using Toast without having App | Fix exceptions when using Toast without having App
See issue #995 | JavaScript | apache-2.0 | nickjvm/grommet,nickjvm/grommet,HewlettPackard/grommet,linde12/grommet,HewlettPackard/grommet,kylebyerly-hp/grommet,HewlettPackard/grommet,grommet/grommet,grommet/grommet,grommet/grommet | ---
+++
@@ -6,7 +6,9 @@
function clearAnnouncer() {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
- announcer.innerHTML = '';
+ if(announcer) {
+ announcer.innerHTML = '';
+ }
};
export function announcePageLoaded (title) {
@@ -15,10 +17,12 @@
export function announce (message, mode = 'assertive') {
const announcer = document.querySelector(`.${CLASS_ROOT}__announcer`);
- announcer.setAttribute('aria-live', 'off');
- announcer.innerHTML = message;
- setTimeout(clearAnnouncer, 500);
- announcer.setAttribute('aria-live', mode);
+ if(announcer) {
+ announcer.setAttribute('aria-live', 'off');
+ announcer.innerHTML = message;
+ setTimeout(clearAnnouncer, 500);
+ announcer.setAttribute('aria-live', mode);
+ }
}
export default { announce, announcePageLoaded }; |
572baf69c38359e6f86df7a0ce53ae4a3d440ae7 | src/layouts/layout-1-1.js | src/layouts/layout-1-1.js | import React from 'react';
export default (components, className, onClick) => (
<div className={className + ' horizontal'} onClick={onClick}>
{components[0]}
</div>
);
| import React from 'react';
export default (components, className, onClick) => (
<div className={className + ' vertical'} onClick={onClick}>
{components[0]}
</div>
);
| Make the 1-1 layout vertical | Make the 1-1 layout vertical
| JavaScript | mit | nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen | ---
+++
@@ -1,7 +1,7 @@
import React from 'react';
export default (components, className, onClick) => (
- <div className={className + ' horizontal'} onClick={onClick}>
+ <div className={className + ' vertical'} onClick={onClick}>
{components[0]}
</div>
); |
3a5eedacce41150794cd17a53de9b7cffd2be6d1 | src/templateLayout.wef.js | src/templateLayout.wef.js | /*!
* TemplateLayout Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: cssParser
//exports: templateLayout
(function () {
var templateLayout = {
name:"templateLayout",
version:"0.0.1",
description:"W3C CSS Template Layout Module",
authors:["Pablo Escalada <uo1398@uniovi.es>"],
licenses:["MIT"], //TODO: Licenses
templateLayout:function () {
document.addEventListener('selectorFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.selectorText | lastEvent.property);
}, false);
document.addEventListener('propertyFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.selectorText | lastEvent.property);
}, false);
return templateLayout;
},
getLastEvent:function () {
return lastEvent;
}
};
var lastEvent = 0;
wef.plugins.register("templateLayout", templateLayout);
})(); | /*!
* TemplateLayout Wef plugin
* Copyright (c) 2011 Pablo Escalada
* MIT Licensed
*/
//requires: cssParser
//exports: templateLayout
(function () {
var templateLayout = {
name:"templateLayout",
version:"0.0.1",
description:"W3C CSS Template Layout Module",
authors:["Pablo Escalada <uo1398@uniovi.es>"],
licenses:["MIT"], //TODO: Licenses
init:function () {
document.addEventListener('propertyFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
//console.log(lastEvent.property);
}, false);
return templateLayout;
},
getLastEvent:function () {
return lastEvent;
}
};
var lastEvent = 0;
wef.plugins.register("templateLayout", templateLayout);
})(); | Remove selectorFound event listener Rename templateLayout() to init() | Remove selectorFound event listener
Rename templateLayout() to init()
| JavaScript | mit | diesire/cssTemplateLayout,diesire/cssTemplateLayout,diesire/cssTemplateLayout | ---
+++
@@ -13,17 +13,12 @@
description:"W3C CSS Template Layout Module",
authors:["Pablo Escalada <uo1398@uniovi.es>"],
licenses:["MIT"], //TODO: Licenses
- templateLayout:function () {
- document.addEventListener('selectorFound', function (e) {
- // e.target matches the elem from above
- lastEvent = e;
- //console.log(lastEvent.selectorText | lastEvent.property);
- }, false);
+ init:function () {
document.addEventListener('propertyFound', function (e) {
// e.target matches the elem from above
lastEvent = e;
- //console.log(lastEvent.selectorText | lastEvent.property);
+ //console.log(lastEvent.property);
}, false);
return templateLayout;
}, |
39a9f5fd3f0c2c5ab00f51c36c21b281e0476928 | application.js | application.js | #!/usr/bin/env node
var express = require('express'),
kotoumi = require('./index'),
http = require('http');
var application = express();
var server = http.startServer(application);
application.kotoumi({
prefix: '',
server: server
});
serer.listen(13000);
| #!/usr/bin/env node
var express = require('express'),
kotoumi = require('./index'),
http = require('http');
var application = express();
var server = http.createServer(application);
application.kotoumi({
prefix: '',
server: server
});
serer.listen(13000);
| Fix typo on the method name: startServer => createServer | Fix typo on the method name:
startServer =>
createServer
| JavaScript | mit | KitaitiMakoto/express-droonga,droonga/express-droonga,KitaitiMakoto/express-droonga,droonga/express-droonga | ---
+++
@@ -5,7 +5,7 @@
http = require('http');
var application = express();
-var server = http.startServer(application);
+var server = http.createServer(application);
application.kotoumi({
prefix: '',
server: server |
2afc346f0fa3492cdbadff72dd47abec9b53fe76 | source/assets/js/components/sass-syntax-switcher.js | source/assets/js/components/sass-syntax-switcher.js | $(function() {
$( "#topic-2" ).tabs();
$( "#topic-3" ).tabs();
$( "#topic-5" ).tabs();
$( "#topic-6" ).tabs();
$( "#topic-7" ).tabs();
$( "#topic-8" ).tabs();
// Hover states on the static widgets
$( "#dialog-link, #icons li" ).hover(
function() {
$( this ).addClass( "ui-state-hover" );
},
function() {
$( this ).removeClass( "ui-state-hover" );
}
);
});
| $(function() {
$( "#topic-2" ).tabs();
$( "#topic-3" ).tabs();
$( "#topic-5" ).tabs();
$( "#topic-6" ).tabs();
$( "#topic-7" ).tabs();
$( "#topic-8" ).tabs();
// Hover states on the static widgets
$( "#dialog-link, #icons li" ).hover(
function() {
$( this ).addClass( "ui-state-hover" );
},
function() {
$( this ).removeClass( "ui-state-hover" );
}
);
// Switch ALL the tabs (Sass/SCSS) together
var
noRecursion = false,
jqA = $( "a.ui-tabs-anchor" ),
jqASass = jqA.filter( ":contains('Sass')" ).click(function() {
if ( !noRecursion ) {
noRecursion = true;
jqASass.not( this ).click();
noRecursion = false;
}
}),
jqASCSS = jqA.filter( ":contains('SCSS')" ).click(function() {
if ( !noRecursion ) {
noRecursion = true;
jqASCSS.not( this ).click();
noRecursion = false;
}
})
;
});
| Switch all the Sass/SCSS tabs together | Switch all the Sass/SCSS tabs together
| JavaScript | mit | lostapathy/sass-site,Mr21/sass-site,mikaspell/sass-site-rus,lostapathy/sass-site,sass/sass-site,mikaspell/sass-site-rus,Mr21/sass-site,mikaspell/sass-site-rus,arhoads/sass-site,una/sass-site,lostapathy/sass-site,sass/sass-site,una/sass-site,arhoads/sass-site,Mr21/sass-site,sass/sass-site,una/sass-site,arhoads/sass-site | ---
+++
@@ -15,4 +15,24 @@
$( this ).removeClass( "ui-state-hover" );
}
);
+
+ // Switch ALL the tabs (Sass/SCSS) together
+ var
+ noRecursion = false,
+ jqA = $( "a.ui-tabs-anchor" ),
+ jqASass = jqA.filter( ":contains('Sass')" ).click(function() {
+ if ( !noRecursion ) {
+ noRecursion = true;
+ jqASass.not( this ).click();
+ noRecursion = false;
+ }
+ }),
+ jqASCSS = jqA.filter( ":contains('SCSS')" ).click(function() {
+ if ( !noRecursion ) {
+ noRecursion = true;
+ jqASCSS.not( this ).click();
+ noRecursion = false;
+ }
+ })
+ ;
}); |
8e5dfec02570e58741c6a92b694d854efbcc23f2 | lib/controllers/api/v1/users.js | lib/controllers/api/v1/users.js | 'use strict';
var mongoose = require('mongoose'),
utils = require('../utils'),
User = mongoose.model('User'),
Application = mongoose.model('Application'),
SimpleApiKey = mongoose.model('SimpleApiKey'),
OauthConsumer = mongoose.model('OauthConsumer'),
Event = mongoose.model('Event'),
User = mongoose.model('User'),
Chapter = mongoose.model('Chapter'),
middleware = require('../../../middleware'),
devsite = require('../../../clients/devsite');
module.exports = function(app, cacher) {
app.route("get", "/organizer/:gplusId", {
summary: "Returns if the specified Google+ user is an Organizer of one or more Chapters"
}, cacher.cache('hours', 24), function(req, res) {
Chapter.find({organizers: req.params.gplusId}, function(err, chapters) {
if (err) { console.log(err); return res.send(500, "Internal Error"); }
var response = {
msg: "ok",
user: req.params.gplusId,
chapters: []
};
for(var i = 0; i < chapters.length; i++) {
response.chapters.push({ id: chapters[i]._id, name: chapters[i].name });
}
return res.send(200, response);
}
);
});
}
| 'use strict';
var mongoose = require('mongoose'),
utils = require('../utils'),
User = mongoose.model('User'),
Application = mongoose.model('Application'),
SimpleApiKey = mongoose.model('SimpleApiKey'),
OauthConsumer = mongoose.model('OauthConsumer'),
Event = mongoose.model('Event'),
User = mongoose.model('User'),
Chapter = mongoose.model('Chapter'),
middleware = require('../../../middleware'),
devsite = require('../../../clients/devsite');
module.exports = function(app, cacher) {
app.route("get", "/organizer/:gplusId", {
summary: "Returns if the specified Google+ user is an Organizer of one or more Chapters"
}, cacher.cache('hours', 24), function(req, res) {
Chapter.find({organizers: req.params.gplusId}, function(err, chapters) {
if (err) { console.log(err); return res.send(500, "Internal Error"); }
var response = {
user: req.params.gplusId,
chapters: []
};
for(var i = 0; i < chapters.length; i++) {
response.chapters.push({ id: chapters[i]._id, name: chapters[i].name });
}
return res.jsonp(response);
}
);
});
}
| Fix missin JSONP support on /organizer/:gplusId | Fix missin JSONP support on /organizer/:gplusId
| JavaScript | apache-2.0 | Splaktar/hub,fchuks/hub,gdg-x/hub,Splaktar/hub,nassor/hub,gdg-x/hub,nassor/hub,fchuks/hub | ---
+++
@@ -20,7 +20,6 @@
if (err) { console.log(err); return res.send(500, "Internal Error"); }
var response = {
- msg: "ok",
user: req.params.gplusId,
chapters: []
};
@@ -28,7 +27,7 @@
response.chapters.push({ id: chapters[i]._id, name: chapters[i].name });
}
- return res.send(200, response);
+ return res.jsonp(response);
}
);
}); |
19b3f18accbbe1dccceae3e3471fc20ade51c914 | khufu-runtime/src/dom.js | khufu-runtime/src/dom.js | import {text} from 'incremental-dom'
export function item(value) {
if(typeof value == 'function') {
value()
} else {
text(value)
}
}
| import {text} from 'incremental-dom'
export function item(value, key) {
if(typeof value == 'function') {
value(key)
} else {
text(value)
}
}
| Fix incorrect key propagation to child view | Fix incorrect key propagation to child view
| JavaScript | apache-2.0 | tailhook/khufu | ---
+++
@@ -1,8 +1,8 @@
import {text} from 'incremental-dom'
-export function item(value) {
+export function item(value, key) {
if(typeof value == 'function') {
- value()
+ value(key)
} else {
text(value)
} |
385fa00d3219f84eec099ebf2551e8941f5e7262 | sashimi-webapp/src/database/stringManipulation.js | sashimi-webapp/src/database/stringManipulation.js |
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) {
return stringToReplace.replace(/["'\\]/g, (char) => {
switch (char) {
case '"':
case '\\':
return `\\${char}`; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.revertSQLInjections = function revertSQLInjections(stringToReplace) {
return stringToReplace.replace(/[\\\\"\\\\\\\\]/g, (char) => {
switch (char) {
case '\\\\"':
return '"';
case '\\\\\\\\':
return '\\'; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
|
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
this.replaceAll = function replaceAll(string, stringToReplace, replacement) {
return string.replace(new RegExp(stringToReplace, 'g'), replacement);
};
this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) {
return stringToReplace.replace(/["\\]/g, (char) => {
switch (char) {
case '"':
case '\\':
return `\\${char}`; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.revertSQLInjections = function revertSQLInjections(stringToReplace) {
stringToReplace = this.replaceAll(stringToReplace, '\\\\"', '"');
stringToReplace = this.replaceAll(stringToReplace, '\\\\\\\\', '\\');
return stringToReplace;
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
| Fix unable to revert resolving of SQLinjection | Fix unable to revert resolving of SQLinjection
[1] Revert back code for replaceAll
[2] Revert 2 resolve strings one by one
| JavaScript | mit | nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note | ---
+++
@@ -13,8 +13,12 @@
return dateTimeNumber;
};
+ this.replaceAll = function replaceAll(string, stringToReplace, replacement) {
+ return string.replace(new RegExp(stringToReplace, 'g'), replacement);
+ };
+
this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) {
- return stringToReplace.replace(/["'\\]/g, (char) => {
+ return stringToReplace.replace(/["\\]/g, (char) => {
switch (char) {
case '"':
case '\\':
@@ -27,17 +31,9 @@
};
this.revertSQLInjections = function revertSQLInjections(stringToReplace) {
- return stringToReplace.replace(/[\\\\"\\\\\\\\]/g, (char) => {
- switch (char) {
- case '\\\\"':
- return '"';
- case '\\\\\\\\':
- return '\\'; // prepends a backslash to backslash, percent,
- // and double/single quotes
- default:
- return char;
- }
- });
+ stringToReplace = this.replaceAll(stringToReplace, '\\\\"', '"');
+ stringToReplace = this.replaceAll(stringToReplace, '\\\\\\\\', '\\');
+ return stringToReplace;
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) { |
e8797027f38494db861d946f74e07e3a2b805a8a | src/md_document_block.js | src/md_document_block.js | "use strict";
var getItemURL = require('./get_item_url')
, regex = /^document (\d+)$/
module.exports = function (md, opts) {
opts = opts || {};
md.use(require('markdown-it-container'), 'document', {
validate: function (params) {
return params.trim().match(regex)
},
render: function (tokens, idx) {
var match = tokens[idx].info.trim().match(regex)
if (tokens[idx].nesting === 1) {
let documentURL = getItemURL(opts.projectBaseURL, 'document', match[1])
, documentText = opts.makeCitationText(documentURL)
tokens[idx].meta = { enItemType: 'document', enItemID: match[1] }
return '<div class="doc-block"><div class="doc">' + documentText + '</div>';
} else {
return '</div>';
}
}
});
}
| "use strict";
var getItemURL = require('./get_item_url')
, regex = /^document (\d+)$/
function createRule(md, projectBaseURL, makeCitationText) {
return function enDocumentBlockMetaRule(state) {
var blockTokens = state.tokens
blockTokens.forEach(function (token) {
if (token.type === 'container_document_open') {
let match = token.info.trim().match(regex)
, documentURL = getItemURL(projectBaseURL, 'document', match[1])
, documentText = makeCitationText(documentURL)
token.meta = {
enCitationText: documentText,
enItemType: 'document',
enItemID: match[1]
}
}
})
}
}
module.exports = function (md, opts) {
opts = opts || {};
md.use(require('markdown-it-container'), 'document', {
validate: function (params) {
return params.trim().match(regex)
},
render: function (tokens, idx) {
if (tokens[idx].nesting === 1) {
return '<div class="doc-block"><div class="doc">' + tokens[idx].meta.enCitationText + '</div>';
} else {
return '</div>';
}
}
});
md.core.ruler.push(
'en_document_block_meta',
createRule(md, opts.projectBaseURL, opts.makeCitationText)
)
}
| Store document meta properties in document block extension | Store document meta properties in document block extension
| JavaScript | agpl-3.0 | editorsnotes/editorsnotes-markup-parser | ---
+++
@@ -2,6 +2,26 @@
var getItemURL = require('./get_item_url')
, regex = /^document (\d+)$/
+
+function createRule(md, projectBaseURL, makeCitationText) {
+ return function enDocumentBlockMetaRule(state) {
+ var blockTokens = state.tokens
+
+ blockTokens.forEach(function (token) {
+ if (token.type === 'container_document_open') {
+ let match = token.info.trim().match(regex)
+ , documentURL = getItemURL(projectBaseURL, 'document', match[1])
+ , documentText = makeCitationText(documentURL)
+
+ token.meta = {
+ enCitationText: documentText,
+ enItemType: 'document',
+ enItemID: match[1]
+ }
+ }
+ })
+ }
+}
module.exports = function (md, opts) {
@@ -12,18 +32,16 @@
return params.trim().match(regex)
},
render: function (tokens, idx) {
- var match = tokens[idx].info.trim().match(regex)
-
if (tokens[idx].nesting === 1) {
- let documentURL = getItemURL(opts.projectBaseURL, 'document', match[1])
- , documentText = opts.makeCitationText(documentURL)
-
- tokens[idx].meta = { enItemType: 'document', enItemID: match[1] }
-
- return '<div class="doc-block"><div class="doc">' + documentText + '</div>';
+ return '<div class="doc-block"><div class="doc">' + tokens[idx].meta.enCitationText + '</div>';
} else {
return '</div>';
}
}
});
+
+ md.core.ruler.push(
+ 'en_document_block_meta',
+ createRule(md, opts.projectBaseURL, opts.makeCitationText)
+ )
} |
22aadec7318bbf4c79bb14d2615cef9480c7469f | library/CM/FormField/Integer.js | library/CM/FormField/Integer.js | /**
* @class CM_FormField_Integer
* @extends CM_FormField_Abstract
*/
var CM_FormField_Integer = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Integer',
ready: function() {
var field = this;
var $slider = this.$(".slider");
var $input = this.$("input");
$slider.slider({
value: $input.val(),
min: field.getOption("min"),
max: field.getOption("max"),
step: field.getOption("step"),
slide: function(event, ui) {
var value = ui.value + 0;
$input.val(value);
$(this).children(".ui-slider-handle").text(value);
},
change: function(event, ui) {
var value = ui.value + 0;
$input.val(value);
$(this).children(".ui-slider-handle").text(value);
}
});
$slider.children(".ui-slider-handle").text($input.val());
$input.watch("disabled", function (propName, oldVal, newVal) {
$slider.slider("option", "disabled", newVal);
$slider.toggleClass("disabled", newVal);
});
$input.changetext(function() {
$slider.slider("option", "value", $(this).val());
field.trigger('change');
});
}
}); | /**
* @class CM_FormField_Integer
* @extends CM_FormField_Abstract
*/
var CM_FormField_Integer = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Integer',
ready: function() {
var field = this;
var $slider = this.$(".slider");
var $input = this.$("input");
$slider.slider({
value: $input.val(),
min: field.getOption("min"),
max: field.getOption("max"),
step: field.getOption("step"),
slide: function(event, ui) {
var value = ui.value + 0;
$input.val(value);
$(this).children(".ui-slider-handle").text(value);
},
change: function(event, ui) {
var value = ui.value + 0;
$input.val(value);
$(this).children(".ui-slider-handle").text(value);
}
});
$slider.children(".ui-slider-handle").text($input.val());
$input.watch("disabled", function (propName, oldVal, newVal) {
$slider.slider("option", "disabled", newVal);
});
$input.changetext(function() {
$slider.slider("option", "value", $(this).val());
field.trigger('change');
});
}
});
| Remove unneeded disabled class for slider | Remove unneeded disabled class for slider
| JavaScript | mit | njam/CM,fauvel/CM,cargomedia/CM,tomaszdurka/CM,alexispeter/CM,tomaszdurka/CM,fvovan/CM,alexispeter/CM,fauvel/CM,vogdb/cm,alexispeter/CM,fvovan/CM,zazabe/cm,zazabe/cm,vogdb/cm,njam/CM,alexispeter/CM,mariansollmann/CM,vogdb/cm,cargomedia/CM,vogdb/cm,tomaszdurka/CM,zazabe/cm,cargomedia/CM,mariansollmann/CM,vogdb/cm,fauvel/CM,njam/CM,fvovan/CM,christopheschwyzer/CM,christopheschwyzer/CM,mariansollmann/CM,fvovan/CM,christopheschwyzer/CM,tomaszdurka/CM,christopheschwyzer/CM,tomaszdurka/CM,fauvel/CM,njam/CM,fauvel/CM,njam/CM,zazabe/cm,mariansollmann/CM,cargomedia/CM | ---
+++
@@ -28,7 +28,6 @@
$slider.children(".ui-slider-handle").text($input.val());
$input.watch("disabled", function (propName, oldVal, newVal) {
$slider.slider("option", "disabled", newVal);
- $slider.toggleClass("disabled", newVal);
});
$input.changetext(function() {
$slider.slider("option", "value", $(this).val()); |
fa62c68db63dd7e8ca0543947191d2586aed76e4 | app/components/Footer/__tests__/Footer-test.js | app/components/Footer/__tests__/Footer-test.js | 'use strict';
jest.unmock('./../Footer');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';
describe('Footer', () => {
it('verify the text content and link are correctly', () => {
const footer = TestUtils.renderIntoDocument(
<Footer />
);
const footerNode = ReactDOM.findDOMNode(footer);
expect(footerNode.textContent).toEqual('Made with by @afonsopacifer');
});
}); | 'use strict';
jest.unmock('./../Footer');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Footer from './../Footer';
describe('Footer', () => {
it('verify the text content are correctly', () => {
const footer = TestUtils.renderIntoDocument(
<Footer />
);
const footerNode = ReactDOM.findDOMNode(footer);
expect(footerNode.textContent).toEqual('Made with by @afonsopacifer');
});
it('link of github author should be https://github.com/afonsopacifer', () => {
const footer = TestUtils.renderIntoDocument(
<Footer />
);
const linkElement = TestUtils.scryRenderedDOMComponentsWithTag(footer, 'a');
expect(linkElement.length).toEqual(1);
expect(linkElement[0].getAttribute('href')).toEqual('https://github.com/afonsopacifer');
});
}); | Make more tests at Footer component | Make more tests at Footer component
| JavaScript | mit | afonsopacifer/react-pomodoro,afonsopacifer/react-pomodoro | ---
+++
@@ -9,10 +9,10 @@
describe('Footer', () => {
- it('verify the text content and link are correctly', () => {
+ it('verify the text content are correctly', () => {
const footer = TestUtils.renderIntoDocument(
- <Footer />
+ <Footer />
);
const footerNode = ReactDOM.findDOMNode(footer);
@@ -20,4 +20,16 @@
expect(footerNode.textContent).toEqual('Made with by @afonsopacifer');
});
+ it('link of github author should be https://github.com/afonsopacifer', () => {
+
+ const footer = TestUtils.renderIntoDocument(
+ <Footer />
+ );
+
+ const linkElement = TestUtils.scryRenderedDOMComponentsWithTag(footer, 'a');
+
+ expect(linkElement.length).toEqual(1);
+ expect(linkElement[0].getAttribute('href')).toEqual('https://github.com/afonsopacifer');
+ });
+
}); |
bb910f984edd8080e5fe1d1b34a7dfec7ac9d785 | lib/api/encodeSummary.js | lib/api/encodeSummary.js | var encodeSummaryArticle = require('../json/encodeSummaryArticle');
/**
Encode summary to provide an API to plugin
@param {Output} output
@param {Config} config
@return {Object}
*/
function encodeSummary(output, summary) {
var result = {
/**
Iterate over the summary
@param {Function} iter
*/
walk: function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
},
/**
Get an article by its level
@param {String} level
@return {Object}
*/
getArticleByLevel: function(level) {
var article = summary.getByLevel(level);
return (article? encodeSummaryArticle(article) : undefined);
},
/**
Get an article by its path
@param {String} level
@return {Object}
*/
getArticleByPath: function(level) {
var article = summary.getByPath(level);
return (article? encodeSummaryArticle(article) : undefined);
}
};
return result;
}
module.exports = encodeSummary;
| var encodeSummaryArticle = require('../json/encodeSummaryArticle');
/**
Encode summary to provide an API to plugin
@param {Output} output
@param {Config} config
@return {Object}
*/
function encodeSummary(output, summary) {
var result = {
/**
Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
*/
walk: function (iter) {
summary.getArticle(function(article) {
var jsonArticle = encodeSummaryArticle(article, false);
return iter(jsonArticle);
});
},
/**
Get an article by its level
@param {String} level
@return {Object}
*/
getArticleByLevel: function(level) {
var article = summary.getByLevel(level);
return (article? encodeSummaryArticle(article) : undefined);
},
/**
Get an article by its path
@param {String} level
@return {Object}
*/
getArticleByPath: function(level) {
var article = summary.getByPath(level);
return (article? encodeSummaryArticle(article) : undefined);
}
};
return result;
}
module.exports = encodeSummary;
| Improve comment for API summary.walk | Improve comment for API summary.walk
| JavaScript | apache-2.0 | gencer/gitbook,ryanswanson/gitbook,tshoper/gitbook,tshoper/gitbook,strawluffy/gitbook,GitbookIO/gitbook,gencer/gitbook | ---
+++
@@ -10,7 +10,7 @@
function encodeSummary(output, summary) {
var result = {
/**
- Iterate over the summary
+ Iterate over the summary, it stops when the "iter" returns false
@param {Function} iter
*/ |
3d0c696f418fa672231c32737d706a62e5c5d9af | src/react/inputs/input.js | src/react/inputs/input.js | import React from 'react';
import {Icon} from '../iconography';
import classnames from 'classnames';
import PropTypes from 'prop-types';
export class Input extends React.Component {
static propTypes = {
size: PropTypes.string,
icon: PropTypes.string
};
componentDidMount() {
require('../../css/inputs');
}
render() {
const {size, icon, ...props} = this.props;
const input = (<input {...{
...props,
className: classnames(props.className, {
'input-sm': ['sm', 'small'].indexOf(size) !== -1,
'input-lg': ['lg', 'large'].indexOf(size) !== -1
})
}} />);
if (!icon) return input;
return (
<div className="input-icon-container">
{input}
<Icon {...{src: icon}}/>
</div>
);
}
} | import React from 'react';
import {Icon} from '../iconography';
import classnames from 'classnames';
import PropTypes from 'prop-types';
export class Input extends React.Component {
static propTypes = {
size: PropTypes.string,
icon: PropTypes.string,
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
};
componentDidMount() {
require('../../css/inputs');
}
render() {
const {size, icon, innerRef, ...props} = this.props;
const input = (<input {...{
...props,
ref: innerRef,
className: classnames(props.className, {
'input-sm': ['sm', 'small'].indexOf(size) !== -1,
'input-lg': ['lg', 'large'].indexOf(size) !== -1
})
}} />);
if (!icon) return input;
return (
<div className="input-icon-container">
{input}
<Icon {...{src: icon}}/>
</div>
);
}
} | Add innerRef prop to Input component | Add innerRef prop to Input component
| JavaScript | mit | pivotal-cf/pivotal-ui,pivotal-cf/pivotal-ui,pivotal-cf/pivotal-ui | ---
+++
@@ -6,17 +6,20 @@
export class Input extends React.Component {
static propTypes = {
size: PropTypes.string,
- icon: PropTypes.string
+ icon: PropTypes.string,
+ innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object])
};
+
componentDidMount() {
require('../../css/inputs');
}
render() {
- const {size, icon, ...props} = this.props;
+ const {size, icon, innerRef, ...props} = this.props;
const input = (<input {...{
...props,
+ ref: innerRef,
className: classnames(props.className, {
'input-sm': ['sm', 'small'].indexOf(size) !== -1,
'input-lg': ['lg', 'large'].indexOf(size) !== -1 |
ed9a606f20b97646d23bd23f693f2fe630394422 | src/scripts/data_table.js | src/scripts/data_table.js | /*eslint-env node */
var m = require("mithril");
var tabs = require("./polythene_tabs");
tabs.onClick(function(newIndex, oldIndex) {
var h = require("./headers")[newIndex];
grid.setRef(require("./firebase_ref").child(h.field), h.columns);
});
var t = document.createElement("div");
m.mount(t, tabs.view);
var grid = require("./w2ui_grid");
grid.view.style.height = "calc(100% - 48px)";
var wrapper = document.createElement("div");
wrapper.appendChild(t);
wrapper.appendChild(grid.view);
module.exports = wrapper;
| /*eslint-env node */
var m = require("mithril");
var grid = require("./w2ui_grid");
grid.view.style.height = "calc(100% - 48px)";
var tabs = require("./polythene_tabs");
tabs.onClick(function(newIndex, oldIndex) {
var h = require("./headers")[newIndex];
grid.setRef(require("./firebase_ref").child(h.field), h.columns);
});
var t = document.createElement("div");
m.mount(t, tabs.view);
var wrapper = document.createElement("div");
wrapper.appendChild(t);
wrapper.appendChild(grid.view);
module.exports = wrapper;
| Define "grid" variable before it's used. | Define "grid" variable before it's used. | JavaScript | mit | 1stop-st/frame | ---
+++
@@ -1,6 +1,9 @@
/*eslint-env node */
var m = require("mithril");
+
+var grid = require("./w2ui_grid");
+grid.view.style.height = "calc(100% - 48px)";
var tabs = require("./polythene_tabs");
tabs.onClick(function(newIndex, oldIndex) {
@@ -11,9 +14,6 @@
var t = document.createElement("div");
m.mount(t, tabs.view);
-var grid = require("./w2ui_grid");
-grid.view.style.height = "calc(100% - 48px)";
-
var wrapper = document.createElement("div");
wrapper.appendChild(t);
wrapper.appendChild(grid.view); |
64d42211a279c8cfd56f4fad8c255b4e28c53721 | src/ui/app.js | src/ui/app.js | angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate'])
.config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) {
$urlRouterProvider.otherwise('/');
$translateProvider.useStaticFilesLoader({
prefix: 'ui/locale/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('de');
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
}]);
| angular.module('proxtop', ['ngMaterial', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate'])
.config(['$stateProvider', '$urlRouterProvider', '$translateProvider', function($stateProvider, $urlRouterProvider, $translateProvider) {
$urlRouterProvider.otherwise('/');
$translateProvider.useStaticFilesLoader({
prefix: 'ui/locale/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('de');
$translateProvider.useSanitizeValueStrategy('escape');
}]);
| Use sanitization method that doesn't require more dependencies. | Use sanitization method that doesn't require more dependencies.
| JavaScript | mit | kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop,kumpelblase2/proxtop | ---
+++
@@ -7,5 +7,5 @@
});
$translateProvider.preferredLanguage('de');
- $translateProvider.useSanitizeValueStrategy('sanitizeParameters');
+ $translateProvider.useSanitizeValueStrategy('escape');
}]); |
411c9404e0dedc5cd79a5b09d3afb6bfb7d69e0a | confirm.js | confirm.js | /**
* Show confirm popup, when user close tab with non-synchronized actions.
*
* @param {Syncable|Client} client Observed Client instance
* or object with `sync` property.
* @param {String} [warning] The text of the warning.
*
* @return {Function} Unbind confirm listener.
*
* @example
* import confirm from 'logux-status/confirm'
* confirm(client, 'Post does not saved to server. Are you sure to leave?')
*/
function confirm (client, warning) {
var sync = client.sync
warning = warning || 'Some data was not saved to server. ' +
'Are you sure to leave?'
function listen (e) {
if (typeof e === 'undefined') e = window.event
if (e) e.returnValue = warning
return warning
}
return sync.on('state', function () {
if (sync.state === 'wait' || sync.state === 'sending') {
window.addEventListener('beforeunload', listen, false)
} else {
window.removeEventListener('beforeunload', listen, false)
}
})
}
module.exports = confirm
| /**
* Show confirm popup, when user close tab with non-synchronized actions.
*
* @param {Syncable|Client} client Observed Client instance
* or object with `sync` property.
* @param {String} [warning] The text of the warning.
*
* @return {Function} Unbind confirm listener.
*
* @example
* import confirm from 'logux-status/confirm'
* confirm(client, 'Post does not saved to server. Are you sure to leave?')
*/
function confirm (client, warning) {
var sync = client.sync
warning = warning || 'Some data was not saved to server. ' +
'Are you sure to leave?'
function listen (e) {
if (typeof e === 'undefined') e = window.event
if (e) e.returnValue = warning
return warning
}
return sync.on('state', function () {
if (sync.state === 'wait' || sync.state === 'sending') {
window.addEventListener('beforeunload', listen)
} else {
window.removeEventListener('beforeunload', listen)
}
})
}
module.exports = confirm
| Remove default value for addEventListener | Remove default value for addEventListener
| JavaScript | mit | logux/logux-client,logux/logux-client | ---
+++
@@ -25,9 +25,9 @@
return sync.on('state', function () {
if (sync.state === 'wait' || sync.state === 'sending') {
- window.addEventListener('beforeunload', listen, false)
+ window.addEventListener('beforeunload', listen)
} else {
- window.removeEventListener('beforeunload', listen, false)
+ window.removeEventListener('beforeunload', listen)
}
})
} |
94d8fd7c76248223fad33e9b5c964b3824db722f | console.js | console.js | (function () {
var _console = window.console;
var _methods = {
log: window.console.log,
error: window.console.error,
info: window.console.info,
debug: window.console.debug,
clear: window.console.clear,
};
var $body = document.body;
function append (message) {
$body.append(message);
}
function clear () {
$body.innerHtml = "";
_methods.clear.call(_console);
};
function message (text, color, $message) {
$message = document.createElement('span');
$message.style.color = color || '#000000';
$message.innerText = text;
return $message;
}
function write (key, color) {
return function () {
Function.prototype.apply.call(_methods[key], _console, arguments);
append(message(Array.prototype.slice.call(arguments).join(' '), color));
};
}
window.console.clear = clear;
window.console.error = write('error', '#ff0000');
window.console.log = write('log');
window.console.info = write('info');
window.console.debug = write('debug');
function errorHandler (e) {
e.preventDefault();
console.error(e.message);
return true;
}
if (window.attachEvent) {
window.attachEvent('onerror', errorHandler);
}
else {
window.addEventListener('error', errorHandler, true);
}
}) ();
| (function () {
var _console = window.console;
var _methods = {
log: window.console.log,
error: window.console.error,
info: window.console.info,
debug: window.console.debug,
clear: window.console.clear,
};
function append (message) {
if (document.body) {
document.body.append(message);
}
else {
setTimeout(append, 100, message);
}
}
function clear () {
if (document.body) {
document.body.innerHtml = null;
}
_methods.clear.call(_console);
};
function message (text, color, $message) {
$message = document.createElement('span');
$message.style.color = color || '#000000';
$message.innerText = text;
return $message;
}
function write (key, color) {
return function () {
Function.prototype.apply.call(_methods[key], _console, arguments);
append(message(Array.prototype.slice.call(arguments).join(' '), color));
};
}
window.console.clear = clear;
window.console.error = write('error', '#ff0000');
window.console.log = write('log');
window.console.info = write('info');
window.console.debug = write('debug');
function errorHandler (e) {
e.preventDefault();
console.error(e.message);
return true;
}
if (window.attachEvent) {
window.attachEvent('onerror', errorHandler);
}
else {
window.addEventListener('error', errorHandler, true);
}
}) ();
| Fix to append when document body is ready | Fix to append when document body is ready
| JavaScript | mit | eu81273/jsfiddle-console | ---
+++
@@ -7,14 +7,20 @@
debug: window.console.debug,
clear: window.console.clear,
};
- var $body = document.body;
function append (message) {
- $body.append(message);
+ if (document.body) {
+ document.body.append(message);
+ }
+ else {
+ setTimeout(append, 100, message);
+ }
}
function clear () {
- $body.innerHtml = "";
+ if (document.body) {
+ document.body.innerHtml = null;
+ }
_methods.clear.call(_console);
};
|
0ec9d4ed2037fb68143bb9d816cf679ee099b2bd | tutorials/build-website.js | tutorials/build-website.js | var path = require('path');
var fs = require('fs-extra');
var pug = require('pug');
var buildUtils = require('../examples/build-utils');
// generate the tutorials
fs.ensureDirSync('website/source/tutorials');
var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source'));
tutorials.map(function (json) {
var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8');
pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug');
var fn = pug.compile(pugTemplate, {
pretty: false,
filename: path.relative('.', path.resolve(json.dir, 'index.pug'))
});
var html = fn(json);
html = `---
layout: tutorial
title: ${json.title}
about: ${json.about.text}
tutorialCss: ${JSON.stringify(json.tutorialCss)}
tutorialJs: ${JSON.stringify(json.tutorialJs)}
---
` + html;
fs.writeFileSync(path.resolve(json.output, 'index.html'), html);
});
// copy common files
fs.copySync('tutorials/common', 'website/source/tutorials/common');
buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
| var path = require('path');
var fs = require('fs-extra');
var pug = require('pug');
var buildUtils = require('../examples/build-utils');
// generate the tutorials
fs.ensureDirSync('website/source/tutorials');
var tutorials = buildUtils.getList('tutorials', 'tutorial', path.resolve('website', 'source'));
tutorials.map(function (json) {
var pugTemplate = fs.readFileSync(path.relative('.', path.resolve(json.dir, 'index.pug')), 'utf8');
pugTemplate = pugTemplate.replace('extends ../common/index.pug', 'extends ../common/index-website.pug');
var fn = pug.compile(pugTemplate, {
pretty: false,
filename: path.relative('.', path.resolve(json.dir, 'index.pug'))
});
var html = fn(json);
html = html.replace(/<=/g, '<=').replace(/>=/g, '>=');
html = `---
layout: tutorial
title: ${json.title}
about: ${json.about.text}
tutorialCss: ${JSON.stringify(json.tutorialCss)}
tutorialJs: ${JSON.stringify(json.tutorialJs)}
---
` + html;
fs.writeFileSync(path.resolve(json.output, 'index.html'), html);
});
// copy common files
fs.copySync('tutorials/common', 'website/source/tutorials/common');
buildUtils.writeYamlList(path.resolve('website', 'source', '_data'), 'tutorials.yml', tutorials);
| Fix the website tutorial build to escape <=. | Fix the website tutorial build to escape <=.
| JavaScript | apache-2.0 | Kitware/geojs,OpenGeoscience/geojs,OpenGeoscience/geojs,Kitware/geojs,Kitware/geojs,OpenGeoscience/geojs | ---
+++
@@ -17,6 +17,7 @@
filename: path.relative('.', path.resolve(json.dir, 'index.pug'))
});
var html = fn(json);
+ html = html.replace(/<=/g, '<=').replace(/>=/g, '>=');
html = `---
layout: tutorial
title: ${json.title} |
54181a9a43eddee7a19e8fd7ffb29a37ee8fd4d9 | src/popup/js/config/svgIcons.js | src/popup/js/config/svgIcons.js | angular.module('Shazam2Spotify')
.config(function() {
// Load SVG icons (dirty, should not use jQuery...)
$.ajax({
url: 'img/icons.svg',
method: 'GET',
dataType: 'html',
success: function(data) {
$("body").prepend(data);
}
});
}); | angular.module('Shazam2Spotify')
.run(function($http) {
// Load SVG icons (dirty, should not use jQuery...)
$http.get('img/icons.svg', {responseType: 'html'}).
success(function(data) {
angular.element('body').prepend(data);
});
}); | Load SVG icons with $http instead of jQuery | Load SVG icons with $http instead of jQuery
| JavaScript | mit | leeroybrun/chrome-shazify,leeroybrun/chrome-shazify | ---
+++
@@ -1,12 +1,8 @@
angular.module('Shazam2Spotify')
- .config(function() {
+ .run(function($http) {
// Load SVG icons (dirty, should not use jQuery...)
- $.ajax({
- url: 'img/icons.svg',
- method: 'GET',
- dataType: 'html',
- success: function(data) {
- $("body").prepend(data);
- }
- });
+ $http.get('img/icons.svg', {responseType: 'html'}).
+ success(function(data) {
+ angular.element('body').prepend(data);
+ });
}); |
69e7c35ed30ebeda6a5d701dad3abc10542d4088 | app/assets/javascripts/behaviors/toggle_disable_list_command.js | app/assets/javascripts/behaviors/toggle_disable_list_command.js | $(function() {
$(document).on("change", "[data-behavior~=toggle-disable-list-command]", function(e) {
var commandButtonsSelector = $(e.target).data("commands");
var commandButtons = $(e.target).closest(commandButtonsSelector);
console.log(commandButtons.length);
});
});
| $(function() {
$(document).on("change", "[data-behavior~=toggle-disable-list-command]", function(e) {
var commandButtonsSelector = $(e.target).data("commands");
var commandButtons = $(document).find(commandButtonsSelector);
var list = $(document).find("[name='" + $(e.target).attr("name") + "']:checked");
if (list.length > 0) {
commandButtons.removeClass("disabled").attr("disabled", false);
} else {
commandButtons.addClass("disabled").attr("disabled", true);
}
});
});
| Implement toggle behavior from checkbox change | Implement toggle behavior from checkbox change
| JavaScript | agpl-3.0 | UM-USElab/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development,UM-USElab/gradecraft-development,mkoon/gradecraft-development | ---
+++
@@ -1,7 +1,12 @@
$(function() {
$(document).on("change", "[data-behavior~=toggle-disable-list-command]", function(e) {
var commandButtonsSelector = $(e.target).data("commands");
- var commandButtons = $(e.target).closest(commandButtonsSelector);
- console.log(commandButtons.length);
+ var commandButtons = $(document).find(commandButtonsSelector);
+ var list = $(document).find("[name='" + $(e.target).attr("name") + "']:checked");
+ if (list.length > 0) {
+ commandButtons.removeClass("disabled").attr("disabled", false);
+ } else {
+ commandButtons.addClass("disabled").attr("disabled", true);
+ }
});
}); |
3c34ff5ce1b1dc7d609a458b7483762a88c87179 | build/serve.js | build/serve.js | var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 3000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
]
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
| var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 3000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
],
ignoreRequires: '^ol\\.'
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
| Use closure-util's ignoreRequires for the examples | Use closure-util's ignoreRequires for the examples
| JavaScript | bsd-2-clause | openlayers/ol3-cesium,gejgalis/ol3-cesium,phuree/ol-cesium,fredj/ol3-cesium,openlayers/ol-cesium,fredj/ol3-cesium,phuree/ol-cesium,ahocevar/ol3-cesium,gberaudo/ol3-cesium,oterral/ol3-cesium,thhomas/ol3-cesium,gberaudo/ol3-cesium,bartvde/ol3-cesium,camptocamp/ol3-cesium,openlayers/ol-cesium,thhomas/ol3-cesium,fredj/ol3-cesium,thhomas/ol3-cesium,epointal/ol3-cesium,camptocamp/ol3-cesium,GistdaDev/ol3-cesium,epointal/ol3-cesium,klokantech/ol3-cesium,gejgalis/ol3-cesium,GistdaDev/ol3-cesium,openlayers/ol3-cesium,bartvde/ol3-cesium,gejgalis/ol3-cesium,oterral/ol3-cesium | ---
+++
@@ -31,7 +31,8 @@
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
- ]
+ ],
+ ignoreRequires: '^ol\\.'
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message); |
1077451e514b05a4bf12d8032f55e403fa96c877 | js/src/index.js | js/src/index.js | // Load css
require('leaflet/dist/leaflet.css');
require('leaflet-draw/dist/leaflet.draw.css');
require('leaflet.markercluster/dist/MarkerCluster.css');
require('leaflet.markercluster/dist/MarkerCluster.Default.css');
require('leaflet-measure/dist/leaflet-measure.css');
require('leaflet-fullscreen/dist/leaflet.fullscreen.css');
require('./jupyter-leaflet.css');
// Forcibly load the marker icon images to be in the bundle.
require('leaflet/dist/images/marker-shadow.png');
require('leaflet/dist/images/marker-icon.png');
require('leaflet/dist/images/marker-icon-2x.png');
// Export everything from jupyter-leaflet and the npm package version number.
hasL = (typeof(window.L) != 'undefined');
module.exports = require('./jupyter-leaflet.js');
module.exports['version'] = require('../package.json').version;
if (hasL) {
console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`");
ipyL = L.noConflict();
}
| // Load css
require('leaflet/dist/leaflet.css');
require('leaflet-draw/dist/leaflet.draw.css');
require('leaflet.markercluster/dist/MarkerCluster.css');
require('leaflet.markercluster/dist/MarkerCluster.Default.css');
require('leaflet-measure/dist/leaflet-measure.css');
require('leaflet-fullscreen/dist/leaflet.fullscreen.css');
require('./jupyter-leaflet.css');
// Forcibly load the marker icon images to be in the bundle.
require('leaflet/dist/images/marker-shadow.png');
require('leaflet/dist/images/marker-icon.png');
require('leaflet/dist/images/marker-icon-2x.png');
// Export everything from jupyter-leaflet and the npm package version number.
var _oldL = window.L;
module.exports = require('./jupyter-leaflet.js');
module.exports['version'] = require('../package.json').version;
// if previous L existed and it got changed while loading this module
if (_oldL !== undefined && _oldL !== window.L) {
console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`");
ipyL = L.noConflict();
}
| Use more robust check before using noConflict() mode | Use more robust check before using noConflict() mode
Basically detect the case when L is already the same Leaflet library instance
that was loaded by some other extension, in which case there is no need to use
noConflict. This does not address the problem of plugins assuming single global
L when there are several different Leaflet libs, but it does address #337, since
other extension share the same Leaflet instance.
| JavaScript | mit | ellisonbg/leafletwidget,ellisonbg/leafletwidget | ---
+++
@@ -13,11 +13,12 @@
require('leaflet/dist/images/marker-icon-2x.png');
// Export everything from jupyter-leaflet and the npm package version number.
-hasL = (typeof(window.L) != 'undefined');
+var _oldL = window.L;
module.exports = require('./jupyter-leaflet.js');
module.exports['version'] = require('../package.json').version;
-if (hasL) {
+// if previous L existed and it got changed while loading this module
+if (_oldL !== undefined && _oldL !== window.L) {
console.log("Existing `L` detected, running ipyleaflet's Leaflet in no-conflict mode as `ipyL`");
ipyL = L.noConflict();
} |
1ae13b69aba04aefcdfc6ac5022db03945e96f96 | tests/web/casperjs/homepage.js | tests/web/casperjs/homepage.js | /**
* homepage.js - Homepage tests.
*/
var x = require('casper').selectXPath;
casper.options.viewportSize = {width: 1920, height: 961};
casper.on('page.error', function(msg, trace) {
this.echo('Error: ' + msg, 'ERROR');
for(var i=0; i<trace.length; i++) {
var step = trace[i];
this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR');
}
});
casper.on('remote.message', function(message) {
this.echo('Message: ' + message);
});
casper.test.begin('Tests homepage structure', function suite(test) {
casper.start('http://web', function() {
test.assertTitle("TestProject", "Title is correct");
casper.wait(2000);
test.assertVisible('h2');
});
casper.run(function() {
test.done();
});
}); | /**
* homepage.js - Homepage tests.
*/
var x = require('casper').selectXPath;
casper.options.viewportSize = {width: 1920, height: 961};
casper.on('page.error', function(msg, trace) {
this.echo('Error: ' + msg, 'ERROR');
for(var i=0; i<trace.length; i++) {
var step = trace[i];
this.echo(' ' + step.file + ' (line ' + step.line + ')', 'ERROR');
}
});
casper.on('remote.message', function(message) {
this.echo('Message: ' + message);
});
casper.test.begin('Tests homepage structure', function suite(test) {
casper.start('http://web', function() {
// This works because the title is set in the "parent" template.
test.assertTitle("TestProject", "Title is correct");
casper.wait(2000);
// This fails, I'm guessing because the h2 is only in the "child" template,
// it seems that CasperJS doesn't render the angular2 app correctly
// and the child route templates are not injected into the page correctly.
test.assertVisible('h2');
});
casper.run(function() {
test.done();
});
}); | Add more comments to the CasperJS test | Add more comments to the CasperJS test
| JavaScript | mit | emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app,emmetog/demo-docker-microservice-app | ---
+++
@@ -20,10 +20,14 @@
casper.start('http://web', function() {
+ // This works because the title is set in the "parent" template.
test.assertTitle("TestProject", "Title is correct");
casper.wait(2000);
+ // This fails, I'm guessing because the h2 is only in the "child" template,
+ // it seems that CasperJS doesn't render the angular2 app correctly
+ // and the child route templates are not injected into the page correctly.
test.assertVisible('h2');
});
|
e4748c49a296ceae8a2ecf2b91d8dd9bcb81abbd | app/assets/javascripts/helpers/languagesHelper.js | app/assets/javascripts/helpers/languagesHelper.js | define([], function() {
/**
* List of the key languages of the platform
*/
var languageList = {
en: 'English',
zh: '中文',
fr: 'Français',
id: 'Bahasa Indonesia',
pt_BR: 'Português (Brasil)',
es_MX: 'Español (Mexico)'
};
var languagesHelper = {
/**
* Returns the list of key languages
* @returns {Object} key languages list
*/
getList: function() {
return languageList;
},
/**
* Returns a list of the key languages
* with the selected option passed by param
* @param {string} selected language
* @returns {Array} list of languages with selection
*/
getListSelected: function(selectedLanguage) {
var langList = [];
for (var lang in languageList) {
langList.push({
key: lang,
name: languageList[lang],
selected: lang === selectedLanguage ? 'selected' : ''
});
}
return langList;
}
}
return languagesHelper;
});
| define([], function() {
/**
* List of the key languages of the platform
*/
var languageList = {
en: 'English',
zh: '中文',
fr: 'Français',
id: 'Bahasa Indonesia',
pt_BR: 'Português',
es_MX: 'Español'
};
var languagesHelper = {
/**
* Returns the list of key languages
* @returns {Object} key languages list
*/
getList: function() {
return languageList;
},
/**
* Returns a list of the key languages
* with the selected option passed by param
* @param {string} selected language
* @returns {Array} list of languages with selection
*/
getListSelected: function(selectedLanguage) {
var langList = [];
for (var lang in languageList) {
langList.push({
key: lang,
name: languageList[lang],
selected: lang === selectedLanguage ? 'selected' : ''
});
}
return langList;
}
}
return languagesHelper;
});
| Update languages literals in subscription selector | Update languages literals in subscription selector
| JavaScript | mit | Vizzuality/gfw,Vizzuality/gfw | ---
+++
@@ -9,8 +9,8 @@
zh: '中文',
fr: 'Français',
id: 'Bahasa Indonesia',
- pt_BR: 'Português (Brasil)',
- es_MX: 'Español (Mexico)'
+ pt_BR: 'Português',
+ es_MX: 'Español'
};
var languagesHelper = { |
5e0f5b68b4e085968544f9ff52eb3f7bc7558b81 | src/article/converter/r2t/DispQuoteConverter.js | src/article/converter/r2t/DispQuoteConverter.js | import { findChild, findAllChildren } from '../util/domHelpers'
/**
* A converter for JATS `<disp-quote>`.
* Our internal model deviates from the original one in that the the attribution is separated from
* the quote content by using a dedicated text property 'attrib'
*/
export default class DispQuoteConverter {
get type () { return 'disp-quote' }
get tagName () { return 'disp-quote' }
import (el, node, importer) {
let pEls = findAllChildren(el, 'p')
let attrib = findChild(el, 'attrib')
if (attrib) {
node.attrib = importer.annotatedText(attrib, [node.id, 'attrib'])
}
node._childNodes = pEls.map(p => {
return importer.convertElement(p).id
})
}
export (node, el, exporter) {
let $$ = exporter.$$
let children = node.getChildren()
el.append(
children.map(child => {
return exporter.convertNode(child)
})
)
if (node.attrib) {
el.append(
$$('attrib').append(
exporter.annotatedText([node.id, 'attrib'])
)
)
}
}
}
| import { findChild, findAllChildren } from '../util/domHelpers'
/**
* A converter for JATS `<disp-quote>`.
* Our internal model deviates from the original one in that the the attribution is separated from
* the quote content by using a dedicated text property 'attrib'
*/
export default class DispQuoteConverter {
get type () { return 'disp-quote' }
get tagName () { return 'disp-quote' }
import (el, node, importer) {
let $$ = el.createElement.bind(el.getOwnerDocument())
let pEls = findAllChildren(el, 'p')
if (pEls.length === 0) {
pEls.push($$('p'))
}
let attrib = findChild(el, 'attrib')
if (attrib) {
node.attrib = importer.annotatedText(attrib, [node.id, 'attrib'])
}
node._childNodes = pEls.map(p => {
return importer.convertElement(p).id
})
}
export (node, el, exporter) {
let $$ = exporter.$$
let children = node.getChildren()
el.append(
children.map(child => {
return exporter.convertNode(child)
})
)
if (node.attrib) {
el.append(
$$('attrib').append(
exporter.annotatedText([node.id, 'attrib'])
)
)
}
}
}
| Make a converter robust against missing paragraph. | Make a converter robust against missing paragraph.
| JavaScript | mit | substance/texture,substance/texture | ---
+++
@@ -11,7 +11,11 @@
get tagName () { return 'disp-quote' }
import (el, node, importer) {
+ let $$ = el.createElement.bind(el.getOwnerDocument())
let pEls = findAllChildren(el, 'p')
+ if (pEls.length === 0) {
+ pEls.push($$('p'))
+ }
let attrib = findChild(el, 'attrib')
if (attrib) {
node.attrib = importer.annotatedText(attrib, [node.id, 'attrib']) |
3a8a1f0d1f9fc7d5a38aba6e5bd042086c488adb | src/scripts/content/youtrack.js | src/scripts/content/youtrack.js | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {
var link, description,
numElem = $('a.issueId'),
titleElem = $(".issue-summary"),
projectElem = $('.fsi-properties .disabled.bold');
description = titleElem.textContent;
description = numElem.firstChild.textContent.trim() + " " + description.trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectElem ? projectElem.textContent : ''
});
elem.insertBefore(link, titleElem);
});
// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
var link,
container = $('.sb-task-title', elem),
description = $('.sb-task-summary', elem).textContent,
projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectName
});
container.appendChild(link);
}); | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {
var link, description,
numElem = $('a.issueId'),
titleElem = $(".issue-summary"),
projectElem = $('.fsi-properties a[title^="Project"], .fsi-properties .disabled.bold');
description = titleElem.textContent;
description = numElem.firstChild.textContent.trim() + " " + description.trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectElem ? projectElem.textContent : ''
});
elem.insertBefore(link, titleElem);
});
// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
var link,
container = $('.sb-task-title', elem),
description = $('.sb-task-summary', elem).textContent,
projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();
link = togglbutton.createTimerLink({
className: 'youtrack',
description: description,
projectName: projectName
});
container.appendChild(link);
});
| Fix project name fetch regression | [YouTrack] Fix project name fetch regression | JavaScript | bsd-3-clause | glensc/toggl-button,andreimoldo/toggl-button,eatskolnikov/toggl-button,eatskolnikov/toggl-button,andreimoldo/toggl-button,glensc/toggl-button,bitbull-team/toggl-button,glensc/toggl-button,bitbull-team/toggl-button | ---
+++
@@ -9,7 +9,7 @@
var link, description,
numElem = $('a.issueId'),
titleElem = $(".issue-summary"),
- projectElem = $('.fsi-properties .disabled.bold');
+ projectElem = $('.fsi-properties a[title^="Project"], .fsi-properties .disabled.bold');
description = titleElem.textContent;
description = numElem.firstChild.textContent.trim() + " " + description.trim(); |
d2d8ef7e882dcf28ae306780bb463e800b0ad15c | js/validation/validate.js | js/validation/validate.js | var _ = require('lodash');
var async = require('async');
var joy = require('./joy/joy.js');
var schemas = {
'basal-rate-segment': require('./basal'),
bolus: require('./bolus'),
cbg: require('./bg'),
common: require('./common'),
deviceMeta: joy(),
message: require('./message'),
settings: require('./settings'),
smbg: require('./bg'),
wizard: require('./wizard')
};
module.exports = {
validateOne: function(datum, cb) {
var handler = schemas[datum.type];
if (handler == null) {
datum.errorMessage = util.format('Unknown data.type[%s]', datum.type);
cb(new Error(datum.errorMessage), datum);
} else {
try {
handler(datum);
} catch (e) {
console.log('Oh noes! This is wrong:\n', datum);
console.log(util.format('Error Message: %s%s', datum.type, e.message));
datum.errorMessage = e.message;
result.invalid.push(datum);
return cb(e, datum);
}
cb(null, datum);
}
},
validateAll: function(data, cb) {
console.time('Pure');
async.map(data, this.validateOne.bind(this), function(err, results) {
console.timeEnd('Pure');
cb(err, results);
});
}
};
| var _ = require('lodash');
var async = require('async');
var util = require('util');
var joy = require('./joy/joy.js');
var schemas = {
'basal-rate-segment': require('./basal'),
bolus: require('./bolus'),
cbg: require('./bg'),
common: require('./common'),
deviceMeta: joy(),
message: require('./message'),
settings: require('./settings'),
smbg: require('./bg'),
wizard: require('./wizard')
};
module.exports = {
validateOne: function(datum, cb) {
var handler = schemas[datum.type];
if (handler == null) {
datum.errorMessage = util.format('Unknown data.type[%s]', datum.type);
cb(new Error(datum.errorMessage), datum);
} else {
try {
handler(datum);
} catch (e) {
console.log('Oh noes! This is wrong:\n', datum);
console.log(util.format('Error Message: %s%s', datum.type, e.message));
datum.errorMessage = e.message;
result.invalid.push(datum);
return cb(e, datum);
}
cb(null, datum);
}
},
validateAll: function(data, cb) {
console.time('Pure');
async.map(data, this.validateOne.bind(this), function(err, results) {
console.timeEnd('Pure');
cb(err, results);
});
}
};
| Fix "util not defined" error from merge conflict | Fix "util not defined" error from merge conflict
| JavaScript | bsd-2-clause | tidepool-org/tideline,tidepool-org/tideline | ---
+++
@@ -1,5 +1,6 @@
var _ = require('lodash');
var async = require('async');
+var util = require('util');
var joy = require('./joy/joy.js');
|
08d124de7b69cc5ff47f02230145c0a7b667cad6 | chrome-keys.js | chrome-keys.js | var util = require('util'),
webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
usingServer('http://localhost:4444/wd/hub').
withCapabilities({'browserName': 'chrome'}).
build();
// driver.get('http://juliemr.github.io/webdriver-bugs/');
driver.get('http://localhost:8111/button.html');
driver.findElement(webdriver.By.css('button')).click();
driver.actions().sendKeys(webdriver.Key.RIGHT).perform();
driver.sleep(4000);
driver.quit();
| var util = require('util'),
webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
usingServer('http://localhost:4444/wd/hub').
withCapabilities({'browserName': 'chrome'}).
build();
driver.get('http://juliemr.github.io/webdriver-bugs/button.html');
// driver.get('http://localhost:8111/button.html');
driver.findElement(webdriver.By.css('button')).click();
driver.actions().sendKeys(webdriver.Key.RIGHT).perform();
driver.sleep(4000);
driver.quit();
| Fix address to work online | Fix address to work online
| JavaScript | mit | juliemr/webdriver-bugs | ---
+++
@@ -6,8 +6,8 @@
withCapabilities({'browserName': 'chrome'}).
build();
-// driver.get('http://juliemr.github.io/webdriver-bugs/');
-driver.get('http://localhost:8111/button.html');
+driver.get('http://juliemr.github.io/webdriver-bugs/button.html');
+// driver.get('http://localhost:8111/button.html');
driver.findElement(webdriver.By.css('button')).click();
|
f3ceda6f44b63bbef13e11345722805054b537e5 | test/TestPermuteReduce.js | test/TestPermuteReduce.js | var expect = require('chai').expect;
var permuterFactory = require('../index').permuterFactory;
describe('permuter', function () {
it('should work stand-alone', function () {
var permuter = permuterFactory(['a','b']);
expect(permuter(['x'])).to.eql([
['x', 'a'],
['x', 'b']
]);
});
it('should work with reduce', function () {
var permuter = permuterFactory(['a', 'b']);
expect([['x']].reduce(permuter, [])).to.eql([
['x', 'a'],
['x', 'b']
]);
});
}); | var expect = require('chai').expect;
var permuterFactory = require('../index').permuterFactory;
describe('permuter', function () {
it('should work stand-alone', function () {
var permuter = permuterFactory(['a','b']);
expect(permuter(['x'])).to.eql([
['x', 'a'],
['x', 'b']
]);
});
it('should work with reduce', function () {
var permuter = permuterFactory(['a', 'b']);
expect([['x']].reduce(permuter, [])).to.eql([
['x', 'a'],
['x', 'b']
]);
});
it('can be used to compute swedish ancestor names', function () {
var parents = ['mor', 'far'];
var permuter = permuterFactory(parents);
expect([['']]
.reduce(permuter, [])
.reduce(permuter, [])
.map(function (cur) {return cur.join('');})).to.eql([
'mormor',
'morfar',
'farmor',
'farfar'
]);
});
}); | Add example for swedish grandparent names | Add example for swedish grandparent names
| JavaScript | mit | tylerpeterson/node-swiss-army-knife | ---
+++
@@ -16,4 +16,18 @@
['x', 'b']
]);
});
+ it('can be used to compute swedish ancestor names', function () {
+ var parents = ['mor', 'far'];
+ var permuter = permuterFactory(parents);
+
+ expect([['']]
+ .reduce(permuter, [])
+ .reduce(permuter, [])
+ .map(function (cur) {return cur.join('');})).to.eql([
+ 'mormor',
+ 'morfar',
+ 'farmor',
+ 'farfar'
+ ]);
+ });
}); |
3a06fc67796abb9c93a7c607e2d766dc065f1fd6 | example/index.js | example/index.js | // Dpeendencies
var EngineParserGen = require("../lib");
// "test-app" should be a valid Engine app in $ENGINE_APPS dir
var epg = new EngineParserGen("test-app");
//epg.parse(function (err, parsed) {
// debugger
//});
epg.renameInstance("layout", "another_layout", (err) => {
if (err) {
return console.log(err);
}
epg.save(function (err) {
console.log(err || "Saved");
});
});
| // Dpeendencies
var EngineParserGen = require("../lib");
// "test-app" should be a valid Engine app in $ENGINE_APPS dir
var epg = new EngineParserGen("test-app");
//epg.parse(function (err, parsed) {
// debugger
//});
epg.renameInstance("layout", "another_layout", (err, toBeSaved, toBeDeleted) => {
if (err) {
return console.log(err);
}
epg.save({
delete: toBeDeleted
, save: toBeSaved
}, function (err) {
console.log(err || "Saved");
});
});
| Send the data to the save method. | Send the data to the save method.
| JavaScript | mit | jillix/engine-parser | ---
+++
@@ -7,11 +7,14 @@
// debugger
//});
-epg.renameInstance("layout", "another_layout", (err) => {
+epg.renameInstance("layout", "another_layout", (err, toBeSaved, toBeDeleted) => {
if (err) {
return console.log(err);
}
- epg.save(function (err) {
+ epg.save({
+ delete: toBeDeleted
+ , save: toBeSaved
+ }, function (err) {
console.log(err || "Saved");
});
}); |
e7fae9c368829013857e03316af06ed511bbfbe8 | extendStorage.js | extendStorage.js | /*
Wonder how this works?
Storage is the Prototype of both localStorage and sessionStorage.
Got it?
*/
(function() {
'use strict';
Storage.prototype.set = function(key, obj) {
var t = typeof obj;
if (t==='undefined' || obj===null ) this.removeItem(key);
this.setItem(key, (t==='object')?JSON.stringify(obj):obj);
};
Storage.prototype.get = function(key) {
var obj = this.getItem(key);
try {
var j = JSON.parse(obj);
if (j && typeof j === "object") return j;
} catch (e) { }
return obj;
};
Storage.prototype.has = window.hasOwnProperty;
Storage.prototype.remove = window.removeItem;
Storage.prototype.keys = function(){
return Object.keys(this.valueOf());
};
})();
| /*
Wonder how this works?
Storage is the Prototype of both localStorage and sessionStorage.
Got it?
*/
(function() {
'use strict';
function extend(){
for(var i=1; i<arguments.length; i++)
for(var key in arguments[i])
if(arguments[i].hasOwnProperty(key)) {
if (typeof arguments[0][key] === 'object'
&& typeof arguments[i][key] === 'object')
extend(arguments[0][key], arguments[i][key]);
else
arguments[0][key] = arguments[i][key];
}
return arguments[0];
}
Storage.prototype.set = function(key, obj) {
var t = typeof obj;
if (t==='undefined' || obj===null ) this.removeItem(key);
this.setItem(key, (t==='object')?JSON.stringify(obj):obj);
};
Storage.prototype.get = function(key) {
var obj = this.getItem(key);
try {
var j = JSON.parse(obj);
if (j && typeof j === "object") return j;
} catch (e) { }
return obj;
};
Storage.prototype.extend = function(key, obj_merge) {
this.set(key,extend(this.get(key),obj_merge);
};
Storage.prototype.has = window.hasOwnProperty;
Storage.prototype.remove = window.removeItem;
Storage.prototype.keys = function(){
return Object.keys(this.valueOf());
};
})();
| Add localStorage.extend with recursive support (but no typechecking) | Add localStorage.extend with recursive support (but no typechecking) | JavaScript | mit | zevero/simpleWebstorage | ---
+++
@@ -7,6 +7,19 @@
(function() {
'use strict';
+ function extend(){
+ for(var i=1; i<arguments.length; i++)
+ for(var key in arguments[i])
+ if(arguments[i].hasOwnProperty(key)) {
+ if (typeof arguments[0][key] === 'object'
+ && typeof arguments[i][key] === 'object')
+ extend(arguments[0][key], arguments[i][key]);
+ else
+ arguments[0][key] = arguments[i][key];
+ }
+ return arguments[0];
+ }
+
Storage.prototype.set = function(key, obj) {
var t = typeof obj;
if (t==='undefined' || obj===null ) this.removeItem(key);
@@ -20,6 +33,10 @@
} catch (e) { }
return obj;
};
+ Storage.prototype.extend = function(key, obj_merge) {
+ this.set(key,extend(this.get(key),obj_merge);
+ };
+
Storage.prototype.has = window.hasOwnProperty;
Storage.prototype.remove = window.removeItem;
|
4e1b941dac03bca3acb0143ad91daa1f9a3e2936 | packages/react-server-cli/src/commands/compile.js | packages/react-server-cli/src/commands/compile.js | import compileClient from "../compileClient"
import handleCompilationErrors from "../handleCompilationErrors";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";
const logger = require("react-server").logging.getLogger(__LOGGER__);
export default function compile(options){
setupLogging(options);
logProductionWarnings(options);
const {compiler} = compileClient(options);
logger.notice("Starting compilation of client JavaScript...");
compiler.run((err, stats) => {
const error = handleCompilationErrors(err, stats);
if (!error) {
logger.notice("Successfully compiled client JavaScript.");
} else {
logger.error(error);
}
});
}
| import compileClient from "../compileClient"
import handleCompilationErrors from "../handleCompilationErrors";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";
import {logging} from "../react-server";
const logger = logging.getLogger(__LOGGER__);
export default function compile(options){
setupLogging(options);
logProductionWarnings(options);
const {compiler} = compileClient(options);
logger.notice("Starting compilation of client JavaScript...");
compiler.run((err, stats) => {
const error = handleCompilationErrors(err, stats);
if (!error) {
logger.notice("Successfully compiled client JavaScript.");
} else {
logger.error(error);
}
});
}
| Fix a weird logger instantiation | Fix a weird logger instantiation
| JavaScript | apache-2.0 | emecell/react-server,davidalber/react-server,redfin/react-server,lidawang/react-server,doug-wade/react-server,szhou8813/react-server,doug-wade/react-server,redfin/react-server,szhou8813/react-server,lidawang/react-server,davidalber/react-server,emecell/react-server | ---
+++
@@ -2,8 +2,9 @@
import handleCompilationErrors from "../handleCompilationErrors";
import setupLogging from "../setupLogging";
import logProductionWarnings from "../logProductionWarnings";
+import {logging} from "../react-server";
-const logger = require("react-server").logging.getLogger(__LOGGER__);
+const logger = logging.getLogger(__LOGGER__);
export default function compile(options){
setupLogging(options); |
4d0ee58f3adb7f9862c0000664989c40335f7abd | test/index.js | test/index.js | var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var rollupBabelLibBundler = require('../lib');
describe('rollup-babel-lib-bundler', function() {
it('is a function', function() {
expect(rollupBabelLibBundler).to.be.a('function');
});
it('returns a promise', function(done) {
var promise = rollupBabelLibBundler();
expect(promise).to.be.a('Promise');
expect(promise).to.eventually.be.rejected.and.notify(done);
});
it('creates new files', function(done) {
var promise = rollupBabelLibBundler({
entry: 'test/sample.js',
});
expect(promise).to.eventually.be.a('array').and.notify(done);
});
});
| var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var rollupBabelLibBundler = require('../lib');
describe('rollup-babel-lib-bundler', function() {
it('is a function', function() {
expect(rollupBabelLibBundler).to.be.a('function');
});
it('returns a promise', function(done) {
var promise = rollupBabelLibBundler();
// On Node 0.10, promise is shimmed
if (typeof promise !== 'object') {
expect(promise).to.be.a('Promise');
}
expect(promise).to.eventually.be.rejected.and.notify(done);
});
it('creates new files', function(done) {
var promise = rollupBabelLibBundler({
entry: 'test/sample.js',
});
expect(promise).to.eventually.be.a('array').and.notify(done);
});
});
| Update test for Node 0.10 | Update test for Node 0.10
| JavaScript | mit | frostney/rollup-babel-lib-bundler | ---
+++
@@ -14,7 +14,11 @@
it('returns a promise', function(done) {
var promise = rollupBabelLibBundler();
- expect(promise).to.be.a('Promise');
+ // On Node 0.10, promise is shimmed
+ if (typeof promise !== 'object') {
+ expect(promise).to.be.a('Promise');
+ }
+
expect(promise).to.eventually.be.rejected.and.notify(done);
});
|
6695b1260a4e325e1a9ace924f9d81d108178d37 | src/pexprs-toExpected.js | src/pexprs-toExpected.js | // --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require('./common.js');
var pexprs = require('./pexprs.js');
var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
pexprs.PExpr.prototype.toExpected = function(ruleDict) {
return undefined;
};
pexprs.anything.toExpected = function(ruleDict) {
return "any object";
};
pexprs.end.toExpected = function(ruleDict) {
return "end of input";
};
pexprs.Prim.prototype.toExpected = function(ruleDict) {
return printString(this.obj);
};
pexprs.Not.prototype.toExpected = function(ruleDict) {
return "no " + this.expr.toExpected();
};
// TODO: think about Listy and Obj
pexprs.Apply.prototype.toExpected = function(ruleDict) {
var description = ruleDict[this.ruleName].description;
if (description) {
return description;
} else {
var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
return article + " " + this.ruleName;
}
};
| // --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
var common = require('./common.js');
var pexprs = require('./pexprs.js');
var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
pexprs.PExpr.prototype.toExpected = function(ruleDict) {
return undefined;
};
pexprs.anything.toExpected = function(ruleDict) {
return "any object";
};
pexprs.end.toExpected = function(ruleDict) {
return "end of input";
};
pexprs.Prim.prototype.toExpected = function(ruleDict) {
return printString(this.obj);
};
pexprs.Not.prototype.toExpected = function(ruleDict) {
if (this.expr === pexprs.anything) {
return "nothing";
} else {
return "no " + this.expr.toExpected();
}
};
// TODO: think about Listy and Obj
pexprs.Apply.prototype.toExpected = function(ruleDict) {
var description = ruleDict[this.ruleName].description;
if (description) {
return description;
} else {
var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
return article + " " + this.ruleName;
}
};
| Print end as "nothing" instead of "no any object" | Print end as "nothing" instead of "no any object"
| JavaScript | mit | DanielTomlinson/ohm,cdglabs/ohm,DanielTomlinson/ohm,anfedorov/ohm,coopsource/ohm,anfedorov/ohm,coopsource/ohm,coopsource/ohm,cdglabs/ohm,anfedorov/ohm,harc/ohm,cdglabs/ohm,harc/ohm,harc/ohm,DanielTomlinson/ohm | ---
+++
@@ -30,7 +30,11 @@
};
pexprs.Not.prototype.toExpected = function(ruleDict) {
- return "no " + this.expr.toExpected();
+ if (this.expr === pexprs.anything) {
+ return "nothing";
+ } else {
+ return "no " + this.expr.toExpected();
+ }
};
// TODO: think about Listy and Obj |
1c6cfedaca2be22f1720b4f6cd64764199be173e | test/stores/Store.spec.js | test/stores/Store.spec.js | import store from "src/stores/Store.js";
describe("store", () => {
it("should exist", () => {
store.should.exist;
});
it("should have all API methods", () => {
store.dispatch.should.be.a.function;
store.getState.should.be.a.function;
store.replaceReducer.should.be.a.function;
store.subscribe.should.be.a.function;
});
});
| import store from "src/stores/Store.js";
import app from "src/reducers/App.js";
describe("store", () => {
it("should exist", () => {
store.should.exist;
});
it("should have all API methods", () => {
store.dispatch.should.be.a.function;
store.getState.should.be.a.function;
store.replaceReducer.should.be.a.function;
store.subscribe.should.be.a.function;
});
it("should use app reducer", () => {
var storeState = store.dispath({type: "bla-bla-bla"});
var defaultState = app(undefined, {type: "bla-bla-bla"});
storeState.should.be.eql(defaultState);
})
});
| Add test if store use app reducer | Refactor: Add test if store use app reducer
| JavaScript | mit | Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React,Lingvokot/Tic-Tac-Toe-React | ---
+++
@@ -1,4 +1,5 @@
import store from "src/stores/Store.js";
+import app from "src/reducers/App.js";
describe("store", () => {
@@ -13,4 +14,10 @@
store.subscribe.should.be.a.function;
});
+ it("should use app reducer", () => {
+ var storeState = store.dispath({type: "bla-bla-bla"});
+ var defaultState = app(undefined, {type: "bla-bla-bla"});
+ storeState.should.be.eql(defaultState);
+ })
+
}); |
18a90886ef4ea64a75ff0182af60dff5a308052e | app/components/vm-hover.js | app/components/vm-hover.js | import Ember from 'ember';
export default Ember.Component.extend({
isShowingHover: false,
commitTitle: function() {
if (this.get('vm.commit.title').match(/^Merge/)) {
return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,'');
}
return this.get('vm.commit.title');
}.property('vm.commit.title'),
setShowingHover: function() {
var access_level = this.get('session').get('data.authenticated.access_level');
if (access_level >= 20) {
this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id);
} else {
this.set('isShowingHover', false);
}
}.observes('isShowingHovers'),
// Return true if is running state
isRunning: function() {
if (parseInt(this.get('vm.status'), 10) > 0) { return true; }
return false;
}.property('vm.status'),
// Return true if user is a Dev or more
isDev: function() {
var access_level = this.get('session').get('data.authenticated.access_level');
if (access_level >= 30) { return true; }
return false;
}.property('session.data.authenticated.access_level'),
actions: {
// close the modal, reset showing variable
closeHover: function() {
this.set('isShowingHovers', -1);
}
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
isShowingHover: false,
commitTitle: function() {
if (this.get('vm.commit.title') && this.get('vm.commit.title').match(/^Merge/)) {
return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,'');
}
return this.get('vm.commit.title');
}.property('vm.commit.title'),
setShowingHover: function() {
var access_level = this.get('session').get('data.authenticated.access_level');
if (access_level >= 20) {
this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id);
} else {
this.set('isShowingHover', false);
}
}.observes('isShowingHovers'),
// Return true if is running state
isRunning: function() {
if (parseInt(this.get('vm.status'), 10) > 0) { return true; }
return false;
}.property('vm.status'),
// Return true if user is a Dev or more
isDev: function() {
var access_level = this.get('session').get('data.authenticated.access_level');
if (access_level >= 30) { return true; }
return false;
}.property('session.data.authenticated.access_level'),
actions: {
// close the modal, reset showing variable
closeHover: function() {
this.set('isShowingHovers', -1);
}
}
});
| Fix issue on match vm title | Fix issue on match vm title
| JavaScript | mit | ricofehr/nextdeploy-webui,ricofehr/nextdeploy-webui | ---
+++
@@ -4,7 +4,7 @@
isShowingHover: false,
commitTitle: function() {
- if (this.get('vm.commit.title').match(/^Merge/)) {
+ if (this.get('vm.commit.title') && this.get('vm.commit.title').match(/^Merge/)) {
return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,'');
}
return this.get('vm.commit.title'); |
5abc414fc9e8249a1a89f4c7d5aa9e9c4f821e7d | src/config.js | src/config.js | import DefaultConfig from 'anyware/lib/game-logic/config/default-config';
import GAMES from 'anyware/lib/game-logic/constants/games';
class Config extends DefaultConfig {
constructor() {
super();
this.CLIENT_CONNECTION_OPTIONS = {
protocol: "wss",
username: "anyware",
password: "anyware",
host: "broker.shiftr.io"
};
this.diskUrls = {
disk0: 'images/disk0.png',
disk1: 'images/disk1.png',
disk2: 'images/disk2.png'
};
this.projectionParameters = {
scale: 1,
translate: [0, 0],
};
// this.GAMES_SEQUENCE = [
// GAMES.DISK,
// GAMES.SIMON
// ];
}
// FIXME: Configure user colors here? How to communicate that to CSS?
}
export default new Config();
| import DefaultConfig from 'anyware/lib/game-logic/config/default-config';
import GAMES from 'anyware/lib/game-logic/constants/games';
class Config extends DefaultConfig {
constructor() {
super();
this.DEBUG.console = true;
this.CLIENT_CONNECTION_OPTIONS = {
protocol: "wss",
username: "anyware",
password: "anyware",
host: "broker.shiftr.io"
};
this.diskUrls = {
disk0: 'images/disk0.png',
disk1: 'images/disk1.png',
disk2: 'images/disk2.png'
};
this.projectionParameters = {
scale: 1,
translate: [0, 0],
};
// this.GAMES_SEQUENCE = [
// GAMES.DISK,
// GAMES.SIMON
// ];
}
// FIXME: Configure user colors here? How to communicate that to CSS?
}
export default new Config();
| Print console messages by default in the emulator | Print console messages by default in the emulator
| JavaScript | mit | anyWareSculpture/sculpture-emulator-client,anyWareSculpture/sculpture-emulator-client | ---
+++
@@ -4,6 +4,8 @@
class Config extends DefaultConfig {
constructor() {
super();
+
+ this.DEBUG.console = true;
this.CLIENT_CONNECTION_OPTIONS = {
protocol: "wss", |
399a94ec926e48935a9a2d7139c1ef477125bd25 | test/modules/version/program.js | test/modules/version/program.js | define(function (require) {
var a = require('./a.js?v=1.0');
var a2 = require('./a.js?v=2.0');
var test = require('../../test');
test.assert(a.foo === 1, 'module version.');
test.assert(a.foo === a2.foo, 'module version.');
test.done();
});
| define(function (require) {
var a = require('./a.js?v=1.0');
var a2 = require('./a.js?v=2.0');
var test = require('../../test');
test.assert(a.foo === 1, a.foo);
test.assert(a.foo === a2.foo, a2.foo);
test.done();
});
| Update the version test case | Update the version test case
| JavaScript | mit | zaoli/seajs,angelLYK/seajs,zwh6611/seajs,yuhualingfeng/seajs,zwh6611/seajs,imcys/seajs,tonny-zhang/seajs,lee-my/seajs,ysxlinux/seajs,lianggaolin/seajs,mosoft521/seajs,FrankElean/SeaJS,judastree/seajs,angelLYK/seajs,tonny-zhang/seajs,chinakids/seajs,lee-my/seajs,yuhualingfeng/seajs,tonny-zhang/seajs,jishichang/seajs,longze/seajs,PUSEN/seajs,baiduoduo/seajs,kuier/seajs,AlvinWei1024/seajs,angelLYK/seajs,coolyhx/seajs,liupeng110112/seajs,lovelykobe/seajs,kaijiemo/seajs,PUSEN/seajs,Lyfme/seajs,121595113/seajs,yern/seajs,JeffLi1993/seajs,mosoft521/seajs,eleanors/SeaJS,seajs/seajs,LzhElite/seajs,miusuncle/seajs,yuhualingfeng/seajs,treejames/seajs,LzhElite/seajs,seajs/seajs,zaoli/seajs,hbdrawn/seajs,lianggaolin/seajs,evilemon/seajs,yern/seajs,baiduoduo/seajs,PUSEN/seajs,kuier/seajs,sheldonzf/seajs,coolyhx/seajs,Lyfme/seajs,hbdrawn/seajs,JeffLi1993/seajs,twoubt/seajs,yern/seajs,lee-my/seajs,MrZhengliang/seajs,coolyhx/seajs,121595113/seajs,jishichang/seajs,imcys/seajs,uestcNaldo/seajs,sheldonzf/seajs,treejames/seajs,kuier/seajs,moccen/seajs,miusuncle/seajs,AlvinWei1024/seajs,FrankElean/SeaJS,ysxlinux/seajs,zaoli/seajs,eleanors/SeaJS,chinakids/seajs,twoubt/seajs,jishichang/seajs,seajs/seajs,uestcNaldo/seajs,judastree/seajs,LzhElite/seajs,sheldonzf/seajs,liupeng110112/seajs,ysxlinux/seajs,imcys/seajs,liupeng110112/seajs,evilemon/seajs,evilemon/seajs,longze/seajs,MrZhengliang/seajs,treejames/seajs,uestcNaldo/seajs,wenber/seajs,lovelykobe/seajs,lovelykobe/seajs,wenber/seajs,lianggaolin/seajs,Gatsbyy/seajs,judastree/seajs,kaijiemo/seajs,mosoft521/seajs,longze/seajs,FrankElean/SeaJS,zwh6611/seajs,AlvinWei1024/seajs,MrZhengliang/seajs,13693100472/seajs,Gatsbyy/seajs,kaijiemo/seajs,JeffLi1993/seajs,Gatsbyy/seajs,eleanors/SeaJS,baiduoduo/seajs,moccen/seajs,13693100472/seajs,miusuncle/seajs,wenber/seajs,Lyfme/seajs,twoubt/seajs,moccen/seajs | ---
+++
@@ -4,8 +4,8 @@
var a2 = require('./a.js?v=2.0');
var test = require('../../test');
- test.assert(a.foo === 1, 'module version.');
- test.assert(a.foo === a2.foo, 'module version.');
+ test.assert(a.foo === 1, a.foo);
+ test.assert(a.foo === a2.foo, a2.foo);
test.done();
|
c2179a52ea6c1a422061a25a83ee27428a5494fb | server.js | server.js | 'use strict';
var config = require('./server/config');
var express = require('express');
var handlebars = require('express-handlebars');
var app = express();
// Middlewares configuration
var oneWeek = 604800000;
app.use(express.static('build', { maxAge: oneWeek }));
app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] }));
// Handlebars configuration
app.set('views', 'client/views');
app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] }));
app.set('view engine', '.hbs');
// Starts application listening
app.listen(config.port, (err) => {
console.log('running on ' + config.port);
});
// Regsiters routes
var indexRoutes = require('./server/routes/indexRoutes');
app.use('/', indexRoutes); | 'use strict';
var config = require('./server/config');
var express = require('express');
var handlebars = require('express-handlebars');
var app = express();
// Middlewares configuration
var oneWeek = 604800000;
app.use(express.static('build'));
app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] }));
// Handlebars configuration
app.set('views', 'client/views');
app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] }));
app.set('view engine', '.hbs');
// Starts application listening
app.listen(config.port, (err) => {
console.log('running on ' + config.port);
});
// Regsiters routes
var indexRoutes = require('./server/routes/indexRoutes');
app.use('/', indexRoutes); | Remove cache on build folder | Remove cache on build folder
| JavaScript | apache-2.0 | Softcadbury/FootballDashboard,Softcadbury/football-peek,Softcadbury/FootballDashboard,Softcadbury/DashboardFootball,Softcadbury/DashboardFootball | ---
+++
@@ -7,7 +7,7 @@
// Middlewares configuration
var oneWeek = 604800000;
-app.use(express.static('build', { maxAge: oneWeek }));
+app.use(express.static('build'));
app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] }));
// Handlebars configuration |
5697e7eab5f1402a2e4ab7922e2f044429c8ac64 | lib/helpers/helpers.js | lib/helpers/helpers.js | 'use strict';
module.exports = {
getClassesFromSelector: function (selector) {
if (!selector) {
return [];
}
var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g;
return selector.match(classRegEx);
},
getSelectorLength: function (selector) {
var classes = this.getClassesFromSelector(selector);
return classes ? classes.length : 0;
}
};
| 'use strict';
module.exports = {
getClassesFromSelector: function (selector) {
if (!selector) {
return [];
}
var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g;
return selector.match(classRegEx) || [];
},
getSelectorLength: function (selector) {
var classes = this.getClassesFromSelector(selector);
return classes.length;
}
};
| Return empty list on non match | Return empty list on non match
| JavaScript | mit | timeinfeldt/grunt-csschecker,timeinfeldt/grunt-csschecker | ---
+++
@@ -6,10 +6,10 @@
return [];
}
var classRegEx = /[_a-zA-Z][_a-zA-Z0-9-]*/g;
- return selector.match(classRegEx);
+ return selector.match(classRegEx) || [];
},
getSelectorLength: function (selector) {
var classes = this.getClassesFromSelector(selector);
- return classes ? classes.length : 0;
+ return classes.length;
}
}; |
36829b9b66474d38de527f2d1457c32b86500402 | karma.conf.js | karma.conf.js | var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: process.env.CONTINUOUS_INTEGRATION === 'true',
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader?harmony' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('test')
})
]
},
webpackServer: {
noInfo: true
}
});
};
| var webpack = require('webpack');
module.exports = function (config) {
config.set({
browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ],
singleRun: process.env.CONTINUOUS_INTEGRATION === 'true',
frameworks: [ 'mocha' ],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
reporters: [ 'dots' ],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'jsx-loader?harmony' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('test')
})
]
},
webpackServer: {
noInfo: true
}
});
};
| Use "dots" karma reporter (for Travis CI web UI) | Use "dots" karma reporter (for Travis CI web UI)
| JavaScript | mit | careerlounge/react-router,yanivefraim/react-router,kelsadita/react-router,rkit/react-router,qimingweng/react-router,Nedomas/react-router,calebmichaelsanchez/react-router,Gazler/react-router,vic/react-router,amplii/react-router,Semora/react-router,mozillo/react-router,FredKSchott/react-router,dozoisch/react-router,tmbtech/react-router,knowbody/react-router,dyzhu12/react-router,johnochs/react-router,wushuyi/react-router,steffenmllr/react-router,dalexand/react-router,meraki/react-router,brenoc/react-router,leeric92/react-router,jamiehill/react-router,gdi2290/react-router,leeric92/react-router,chrisirhc/react-router,gilesbradshaw/react-router,moudy/react-router,iest/react-router,zeke/react-router,rafrex/react-router,dandean/react-router,asaf/react-router,robertniimi/react-router,gaearon/react-router,clloyd/react-router,alexlande/react-router,chf2/react-router,lingard/react-router,pjuke/react-router,gabrielalmeida/react-router,BowlingX/react-router,kirill-konshin/react-router,Duc-Ngo-CSSE/react-router,lrs/react-router,wesbos/react-router,thewillhuang/react-router,Jastrzebowski/react-router,chrisirhc/react-router,iNikNik/react-router,devmeyster/react-router,flocks/react-router,fanhc019/react-router,yanivefraim/react-router,tmbtech/react-router,mjw56/react-router,goblortikus/react-router,robertniimi/react-router,micahlmartin/react-router,ricca509/react-router,yongxu/react-router,elpete/react-router,laskos/react-router,omerts/react-router,rackt/react-router,santiagoaguiar/react-router,jflam/react-router,okcoker/react-router,nickaugust/react-router,birkmann/react-router,fiture/react-router,calebmichaelsanchez/react-router,darul75/react-router,SpainTrain/react-router,skevy/react-router,jeffreywescott/react-router,pjuke/react-router,opichals/react-router,ricca509/react-router,rkaneriya/react-router,fractal5/react-router,idolize/react-router,egobrightan/react-router,muffinresearch/react-router,edpaget/react-router,mattcreager/react-router,reapp/react-router,etiennetremel/react-router,iamdustan/react-router,jobcrackerbah/react-router,pherris/react-router,runlevelsix/react-router,adityapunjani/react-router,goblortikus/react-router,stonegithubs/react-router,taion/rrtr,egobrightan/react-router,prathamesh-sonpatki/react-router,gbaladi/react-router,singggum3b/react-router,freeyiyi1993/react-router,pheadra/react-router,yongxu/react-router,mikekidder/react-router,dalexand/react-router,iamdustan/react-router,justinwoo/react-router,gabrielalmeida/react-router,stevewillard/react-router,aastey/react-router,bmathews/react-router,fractal5/react-router,justinanastos/react-router,masterfung/react-router,migolo/react-router,gabrielalmeida/react-router,lyle/react-router,mulesoft/react-router,tsing/react-router,KamilSzot/react-router,ustccjw/react-router,jepezi/react-router,clloyd/react-router,upraised/react-router,mattkrick/react-router,robertniimi/react-router,navyxie/react-router,oliverwoodings/react-router,iNikNik/react-router,juampynr/react-router,camsong/react-router,chunwei/react-router,kittens/react-router,devmeyster/react-router,contra/react-router,careerlounge/react-router,eriknyk/react-router,nosnickid/react-router,arbas/react-router,acdlite/react-router,sugarshin/react-router,mhils/react-router,Takeno/react-router,darul75/react-router,wesbos/react-router,andreftavares/react-router,cgrossde/react-router,osnr/react-router,ReactTraining/react-router,Duc-Ngo-CSSE/react-router,arthurflachs/react-router,apoco/react-router,TylerLH/react-router,jwaltonmedia/react-router,amsardesai/react-router,sebmck/react-router,zhijiansha123/react-router,nauzethc/react-router,emmenko/react-router,omerts/react-router,taurose/react-router,chloeandisabel/react-router,FbF/react-router,phoenixbox/react-router,ArmendGashi/react-router,angus-c/react-router,Gazler/react-router,Nedomas/react-router,mhuggins7278/react-router,goblortikus/react-router,brenoc/react-router,benjie/react-router,juampynr/react-router,nkatsaros/react-router,steffenmllr/react-router,alexlande/react-router,carlosmontes/react-router,asaf/react-router,ryardley/react-router,RobertKielty/react-router,jflam/react-router,pekkis/react-router,xiaoking/react-router,FredKSchott/react-router,dyzhu12/react-router,ksivam/react-router,tkirda/react-router,careerlounge/react-router,Jastrzebowski/react-router,cold-brew-coding/react-router,barretts/react-router,birkmann/react-router,TylerLH/react-router,cgrossde/react-router,knowbody/react-router,ndreckshage/react-router,edpaget/react-router,artnez/react-router,santiagoaguiar/react-router,javawizard/react-router,pekkis/react-router,baillyje/react-router,jbbr/react-router,frostney/react-router,Takeno/react-router,arbas/react-router,opichals/react-router,gaearon/react-router,dandean/react-router,geminiyellow/react-router,acdlite/react-router,subpopular/react-router,nickaugust/react-router,nosnickid/react-router,laskos/react-router,lrs/react-router,darul75/react-router,flocks/react-router,dmitrigrabov/react-router,JohnyDays/react-router,buildo/react-router,phoenixbox/react-router,kurayama/react-router,herojobs/react-router,buildo/react-router,birendra-ideas2it/react-router,vic/react-router,stanleycyang/react-router,javawizard/react-router,FredKSchott/react-router,zipongo/react-router,eriknyk/react-router,andreftavares/react-router,CivBase/react-router,runlevelsix/react-router,AnSavvides/react-router,jobcrackerbah/react-router,OrganicSabra/react-router,steffenmllr/react-router,littlefoot32/react-router,dmitrigrabov/react-router,arthurflachs/react-router,BowlingX/react-router,daannijkamp/react-router,1000hz/react-router,benjie/react-router,grgur/react-router,rackt/react-router,jerrysu/react-router,MattSPalmer/react-router,Semora/react-router,dtschust/react-router,gdi2290/react-router,wmyers/react-router,subpopular/react-router,BerkeleyTrue/react-router,stshort/react-router,zenlambda/react-router,keathley/react-router,bs1180/react-router,OpenGov/react-router,RickyDan/react-router,kenwheeler/react-router,besarthoxhaj/react-router,acdlite/react-router,zhijiansha123/react-router,mhuggins7278/react-router,nottombrown/react-router,prathamesh-sonpatki/react-router,gbaladi/react-router,okcoker/react-router,stonegithubs/react-router,nauzethc/react-router,ReactTraining/react-router,AsaAyers/react-router,stevewillard/react-router,mozillo/react-router,buildo/react-router,ndreckshage/react-router,edpaget/react-router,sprjr/react-router,justinanastos/react-router,dontcallmedom/react-router,jayphelps/react-router,Sirlon/react-router,arasmussen/react-router,yanivefraim/react-router,malte-wessel/react-router,daannijkamp/react-router,qimingweng/react-router,albertolacework/react-router,davertron/react-router,jbbr/react-router,d-oliveros/react-router,besarthoxhaj/react-router,sugarshin/react-router,sebmck/react-router,chentsulin/react-router,elpete/react-router,masterfung/react-router,vic/react-router,RickyDan/react-router,jhta/react-router,9618211/react-router,justinwoo/react-router,OrganicSabra/react-router,wmyers/react-router,andrefarzat/react-router,rkit/react-router,juampynr/react-router,aastey/react-router,juliocanares/react-router,Reggino/react-router,reapp/react-router,mattydoincode/react-router,cpojer/react-router,baillyje/react-router,mattcreager/react-router,skevy/react-router,pherris/react-router,iest/react-router,justinwoo/react-router,9618211/react-router,amplii/react-router,kevinsimper/react-router,fiture/react-router,neebz/react-router,johnochs/react-router,ThibWeb/react-router,sebmck/react-router,reactjs/react-router,gilesbradshaw/react-router,whouses/react-router,sugarshin/react-router,collardeau/react-router,mikekidder/react-router,mjw56/react-router,1000hz/react-router,Jonekee/react-router,birkmann/react-router,mulesoft/react-router,MrBackKom/react-router,arusakov/react-router,malte-wessel/react-router,packetloop/react-router,natorojr/react-router,timuric/react-router,aldendaniels/react-router,jmeas/react-router,masterfung/react-router,ThibWeb/react-router,appspector/react-router,jmeas/react-router,albertolacework/react-router,oliverwoodings/react-router,trotzig/react-router,nhunzaker/react-router,RickyDan/react-router,jwaltonmedia/react-router,laskos/react-router,lvgunst/react-router,1000hz/react-router,johnochs/react-router,adityapunjani/react-router,claudiopro/react-router,grgur/react-router,wesbos/react-router,geminiyellow/react-router,juliocanares/react-router,upraised/react-router,jerrysu/react-router,fractal5/react-router,mulesoft/react-router,opichals/react-router,RobertKielty/react-router,cpojer/react-router,jepezi/react-router,OpenGov/react-router,JohnyDays/react-router,zeke/react-router,lazywei/react-router,packetloop/react-router,camsong/react-router,nottombrown/react-router,elpete/react-router,nvartolomei/react-router,moudy/react-router,birendra-ideas2it/react-router,goblortikus/react-router,lmtdit/react-router,sprjr/react-router,ksivam/react-router,Sirlon/react-router,stanleycyang/react-router,muffinresearch/react-router,angus-c/react-router,brigand/react-router,rdjpalmer/react-router,samidarko/react-router,tikotzky/react-router,kevinsimper/react-router,leeric92/react-router,9618211/react-router,mikepb/react-router,brownbathrobe/react-router,martypenner/react-router,rubengrill/react-router,timuric/react-router,KamilSzot/react-router,jeffreywescott/react-router,etiennetremel/react-router,jflam/react-router,lyle/react-router,dashed/react-router,singggum3b/react-router,nimi/react-router,mattkrick/react-router,chloeandisabel/react-router,juliocanares/react-router,JohnyDays/react-router,naoufal/react-router,devmeyster/react-router,collardeau/react-router,dozoisch/react-router,kelsadita/react-router,shunitoh/react-router,Dodelkin/react-router,grgur/react-router,aaron-goshine/react-router,brandonlilly/react-router,santiagoaguiar/react-router,tylermcginnis/react-router,kurayama/react-router,mattcreager/react-router,benjie/react-router,lvgunst/react-router,jerrysu/react-router,chunwei/react-router,chloeandisabel/react-router,kittens/react-router,cold-brew-coding/react-router,tmbtech/react-router,dozoisch/react-router,asaf/react-router,javawizard/react-router,matthewlehner/react-router,iNikNik/react-router,kittens/react-router,nimi/react-router,flocks/react-router,frostney/react-router,lyle/react-router,jdelight/react-router,mikekidder/react-router,zeke/react-router,batmanimal/react-router,apoco/react-router,chf2/react-router,brigand/react-router,natorojr/react-router,whouses/react-router,martypenner/react-router,navyxie/react-router,dtschust/react-router,osnr/react-router,Jastrzebowski/react-router,lingard/react-router,arusakov/react-router,ustccjw/react-router,thefringeninja/react-router,stanleycyang/react-router,SpainTrain/react-router,krawaller/react-router,zipongo/react-router,hgezim/react-router,DelvarWorld/react-router,chentsulin/react-router,navy235/react-router,Gazler/react-router,iamdustan/react-router,xiaoking/react-router,freeyiyi1993/react-router,OrganicSabra/react-router,stevewillard/react-router,FreedomBen/react-router,MrBackKom/react-router,tsing/react-router,OpenGov/react-router,kevinsimper/react-router,amsardesai/react-router,jbbr/react-router,jmeas/react-router,axross/react-router,batmanimal/react-router,taurose/react-router,nkatsaros/react-router,emmenko/react-router,jdelight/react-router,tylermcginnis/react-router,aldendaniels/react-router,appspector/react-router,d-oliveros/react-router,collardeau/react-router,stonegithubs/react-router,contra/react-router,mikepb/react-router,omerts/react-router,MrBackKom/react-router,tikotzky/react-router,schnerd/react-router,emmenko/react-router,martypenner/react-router,mikepb/react-router,hgezim/react-router,naoufal/react-router,mhuggins7278/react-router,nosnickid/react-router,eriknyk/react-router,zhijiansha123/react-router,prathamesh-sonpatki/react-router,maksad/react-router,amplii/react-router,wushuyi/react-router,gaearon/react-router,lrs/react-router,camsong/react-router,FbF/react-router,shunitoh/react-router,keathley/react-router,cojennin/react-router,Sirlon/react-router,andrefarzat/react-router,backendeveloper/react-router,reactjs/react-router,Dodelkin/react-router,sleexyz/react-router,BerkeleyTrue/react-router,DelvarWorld/react-router,claudiopro/react-router,rkit/react-router,CivBase/react-router,jobcrackerbah/react-router,micahlmartin/react-router,kirill-konshin/react-router,singggum3b/react-router,dashed/react-router,osnr/react-router,sleexyz/react-router,naoufal/react-router,joeyates/react-router,oliverwoodings/react-router,jamiehill/react-router,knowbody/react-router,chentsulin/react-router,apoco/react-router,mhils/react-router,joeyates/react-router,stshort/react-router,nhunzaker/react-router,jayphelps/react-router,thewillhuang/react-router,Jonekee/react-router,frankleng/react-router,ReactTraining/react-router,ReactTraining/react-router,lmtdit/react-router,trotzig/react-router,dandean/react-router,brandonlilly/react-router,dtschust/react-router,cpojer/react-router,buddhike/react-router,micahlmartin/react-router,dontcallmedom/react-router,navy235/react-router,sleexyz/react-router,jhta/react-router,littlefoot32/react-router,keathley/react-router,lingard/react-router,nimi/react-router,contra/react-router,herojobs/react-router,Reggino/react-router,phoenixbox/react-router,rafrex/react-router,backendeveloper/react-router,barretts/react-router,artnez/react-router,rdjpalmer/react-router,ryardley/react-router,ArmendGashi/react-router,bs1180/react-router,limarc/react-router,timuric/react-router,bmathews/react-router,dyzhu12/react-router,tikotzky/react-router,MattSPalmer/react-router,claudiopro/react-router,aaron-goshine/react-router,arthurflachs/react-router,Takeno/react-router,idolize/react-router,packetloop/react-router,Reggino/react-router,samidarko/react-router,RobertKielty/react-router,djkirby/react-router,jhnns/react-router,gbaladi/react-router,AnSavvides/react-router,nvartolomei/react-router,zenlambda/react-router,frostney/react-router,idolize/react-router,nkatsaros/react-router,qimingweng/react-router,krawaller/react-router,matthewlehner/react-router,FreedomBen/react-router,brownbathrobe/react-router,mattydoincode/react-router,andrefarzat/react-router,frankleng/react-router,tsing/react-router,backendeveloper/react-router,Semora/react-router,migolo/react-router,Duc-Ngo-CSSE/react-router,jeffreywescott/react-router,AsaAyers/react-router,thefringeninja/react-router,djkirby/react-router,artnez/react-router,davertron/react-router,kenwheeler/react-router,FbF/react-router,rubengrill/react-router,herojobs/react-router,levjj/react-router,jhnns/react-router,muffinresearch/react-router,geminiyellow/react-router,adityapunjani/react-router,gdi2290/react-router,BowlingX/react-router,wushuyi/react-router,FreedomBen/react-router,maksad/react-router,limarc/react-router,thefringeninja/react-router,carlosmontes/react-router,dontcallmedom/react-router,mhils/react-router,cojennin/react-router,meraki/react-router,lazywei/react-router,angus-c/react-router,dashed/react-router,subpopular/react-router,brigand/react-router,neebz/react-router,ricca509/react-router,AsaAyers/react-router,justinanastos/react-router,gilesbradshaw/react-router,schnerd/react-router,fanhc019/react-router,levjj/react-router,pherris/react-router,appspector/react-router,jayphelps/react-router,navy235/react-router,besarthoxhaj/react-router,arasmussen/react-router,baillyje/react-router,pheadra/react-router,jepezi/react-router,kirill-konshin/react-router,daannijkamp/react-router,OpenGov/react-router,kenwheeler/react-router,alexlande/react-router,wmyers/react-router,freeyiyi1993/react-router,bmathews/react-router,buddhike/react-router,amsardesai/react-router,rkaneriya/react-router,axross/react-router,pekkis/react-router,xiaoking/react-router,tkirda/react-router | ---
+++
@@ -16,6 +16,8 @@
preprocessors: {
'tests.webpack.js': [ 'webpack', 'sourcemap' ]
},
+
+ reporters: [ 'dots' ],
webpack: {
devtool: 'inline-source-map', |
abfe24acc0c7d37bd59f91b66c8479730b8dad27 | grammar.js | grammar.js | module.exports = grammar({
name: 'ruby',
rules: {
program: $ => $._compound_statement,
_compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)),
_statement: $ => choice($._expression),
_expression: $ => choice($._argument),
_argument: $ => choice($._primary),
_primary: $ => choice($._variable),
_variable: $ => choice($.identifier , 'nil', 'self'),
identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/),
_line_break: $ => '\n',
_terminator: $ => choice($._line_break, ';'),
}
});
| module.exports = grammar({
name: 'ruby',
rules: {
program: $ => $._compound_statement,
_compound_statement: $ => seq($._statement, rep(seq($._terminator, $._expression)), optional($._terminator)),
_statement: $ => choice($._expression),
_expression: $ => choice($._argument),
_argument: $ => choice($._primary),
_primary: $ => choice($._variable),
_variable: $ => choice($.identifier , 'nil', 'self'),
identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/),
comment: $ => seq('#', /.*/),
_line_break: $ => '\n',
_terminator: $ => choice($._line_break, ';'),
}
});
| Define a dubious comment rule. | Define a dubious comment rule.
| JavaScript | mit | tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby,tree-sitter/tree-sitter-ruby | ---
+++
@@ -17,6 +17,8 @@
identifier: $ => seq(rep(choice('@', '$')), /[a-zA-Z_][a-zA-Z0-9_]*/),
+ comment: $ => seq('#', /.*/),
+
_line_break: $ => '\n',
_terminator: $ => choice($._line_break, ';'),
} |
3c153d1b1ccdcbb4ce20d8c4f55af73adceccfbc | src/flexio.js | src/flexio.js | import _ from 'lodash'
import https from 'https'
import axios from 'axios'
import * as task from './task'
import pipe from './pipe'
import pipes from './pipes'
import connections from './connections'
var base_url = 'https://www.flex.io/api/v1'
var cfg = {
token: '',
baseUrl: 'https://www.flex.io/api/v1',
insecure: false,
debug: false
}
export default {
// see `../build/webpack.dist.js`
version: VERSION,
// allow all tasks exports from `./task/index.js`
task,
setup(token, params) {
cfg = _.assign({}, { token }, params)
this._createHttp()
return this
},
getConfig() {
return _.assign({}, cfg)
},
http() {
if (!this._http)
this._createHttp()
return this._http
},
pipe() { return pipe() },
pipes() { return pipes() },
connections() { return connections() },
_createHttp() {
// axios instance options with base url and auth token
var axios_opts = {
baseURL: cfg.baseUrl,
headers: { 'Authorization': 'Bearer ' + cfg.token }
}
// if the `insecure` flag is set, allow unauthorized HTTPS calls
if (cfg.insecure === true)
{
_.assign(axios_opts, {
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
})
}
this._http = axios.create(axios_opts)
}
}
| import _ from 'lodash'
import axios from 'axios'
import * as task from './task'
import pipe from './pipe'
import pipes from './pipes'
import connections from './connections'
var base_url = 'https://www.flex.io/api/v1'
var cfg = {
token: '',
baseUrl: 'https://www.flex.io/api/v1',
insecure: false,
debug: false
}
export default {
// see `../build/webpack.dist.js`
version: VERSION,
// allow all tasks exports from `./task/index.js`
task,
setup(token, params) {
cfg = _.assign({}, { token }, params)
this._createHttp()
return this
},
getConfig() {
return _.assign({}, cfg)
},
http() {
if (!this._http)
this._createHttp()
return this._http
},
pipe() { return pipe() },
pipes() { return pipes() },
connections() { return connections() },
_createHttp() {
// axios instance options with base url and auth token
var axios_opts = {
baseURL: cfg.baseUrl,
headers: { 'Authorization': 'Bearer ' + cfg.token }
}
// TODO: try to figure out a better way to do this...
// if the `insecure` flag is set, allow unauthorized HTTPS calls
if (cfg.insecure === true)
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
this._http = axios.create(axios_opts)
}
}
| Use `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to make insecure calls. | Use `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to make insecure calls.
| JavaScript | mit | flexiodata/flexio-sdk-js,flexiodata/flexio-sdk-js | ---
+++
@@ -1,5 +1,4 @@
import _ from 'lodash'
-import https from 'https'
import axios from 'axios'
import * as task from './task'
import pipe from './pipe'
@@ -51,15 +50,11 @@
headers: { 'Authorization': 'Bearer ' + cfg.token }
}
+ // TODO: try to figure out a better way to do this...
+
// if the `insecure` flag is set, allow unauthorized HTTPS calls
if (cfg.insecure === true)
- {
- _.assign(axios_opts, {
- httpsAgent: new https.Agent({
- rejectUnauthorized: false
- })
- })
- }
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
this._http = axios.create(axios_opts)
} |
a6a74ccf7f7b42844bf8f50dc5db18c914b7f61e | src/main/webapp/js/controller/ProtocolListController.js | src/main/webapp/js/controller/ProtocolListController.js | 'use strict';
indexApp.controller('ProtocolListController',
function ProtocolListController($scope, indexData, $location){
$scope.protocolList = indexData.getProtocolList();
$scope.deleteProtocol = function(protocol){
indexData.deleteProtocol(protocol);
$location.path('/');
}
}
);
| 'use strict';
indexApp.controller('ProtocolListController',
function ProtocolListController($scope, indexData, $location){
$scope.protocolList = indexData.getProtocolList();
$scope.deleteProtocol = function(protocol){
indexData.deleteProtocol(protocol);
$scope.protocolList = indexData.getProtocolList();
$location.path('/');
}
}
);
| Refresh protocol list after protocol removal | Refresh protocol list after protocol removal
| JavaScript | mit | GreyTeardrop/typeground,GreyTeardrop/typeground,GreyTeardrop/typeground | ---
+++
@@ -6,6 +6,7 @@
$scope.deleteProtocol = function(protocol){
indexData.deleteProtocol(protocol);
+ $scope.protocolList = indexData.getProtocolList();
$location.path('/');
}
} |
d24fe086319e786c18e9378178cbbfaca15978e6 | src/tests/jasmine/client/unit/sample/spec/PlayerSpec.js | src/tests/jasmine/client/unit/sample/spec/PlayerSpec.js | /* globals Player: false, Song: false */
describe('Player', function() {
var player;
var song;
beforeEach(function() {
player = new Player();
song = new Song();
});
it('should be able to play a Song', function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
describe('when song has been paused', function() {
beforeEach(function() {
player.play(song);
player.pause();
});
it('should indicate that the song is currently paused', function() {
expect(player.isPlaying).toBeFalsy();
// demonstrates use of 'not' with a custom matcher
expect(player).not.toBePlaying(song);
});
it('should be possible to resume', function() {
player.resume();
expect(player.isPlaying).toBeTruthy();
expect(player.currentlyPlayingSong).toEqual(song);
});
});
// demonstrates use of spies to intercept and test method calls
it('tells the current song if the user has made it a favorite', function() {
spyOn(song, 'persistFavoriteStatus');
player.play(song);
player.makeFavorite();
expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
});
});
| /* globals Player: false, Song: false */
describe('Player', function() {
var player;
var song;
beforeEach(function() {
player = new Player();
song = new Song();
});
it('should be able to play a Song', function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(0);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
describe('when song has been paused', function() {
beforeEach(function() {
player.play(song);
player.pause();
});
it('should indicate that the song is currently paused', function() {
expect(player.isPlaying).toBeFalsy();
// demonstrates use of 'not' with a custom matcher
expect(player).not.toBePlaying(song);
});
it('should be possible to resume', function() {
player.resume();
expect(player.isPlaying).toBeTruthy();
expect(player.currentlyPlayingSong).toEqual(song);
});
});
// demonstrates use of spies to intercept and test method calls
it('tells the current song if the user has made it a favorite', function() {
spyOn(song, 'persistFavoriteStatus');
player.play(song);
player.makeFavorite();
expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
});
});
| Build and tests work, now testing that it will actually fail if a test fails | Build and tests work, now testing that it will actually fail if a test fails
| JavaScript | mit | Zywave/Retrospectre,Zywave/Retrospectre,Zywave/Retrospectre | ---
+++
@@ -11,7 +11,7 @@
it('should be able to play a Song', function() {
player.play(song);
- expect(player.currentlyPlayingSong).toEqual(song);
+ expect(player.currentlyPlayingSong).toEqual(0);
//demonstrates use of custom matcher
expect(player).toBePlaying(song); |
63bfd706d40c35b14fd852ff1efa8e0eb6237f08 | RNTester/js/examples/XHR/XHRExampleAbortController.js | RNTester/js/examples/XHR/XHRExampleAbortController.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const {Alert, Button, View} = require('react-native');
class XHRExampleAbortController extends React.Component<{...}, {...}> {
_timeout: any;
_submit(abortDelay) {
clearTimeout(this._timeout);
// eslint-disable-next-line no-undef
const abortController = new AbortController();
fetch('https://facebook.github.io/react-native/', {
signal: abortController.signal,
})
.then(res => res.text())
.then(res => Alert.alert(res))
.catch(err => Alert.alert(err.message));
this._timeout = setTimeout(() => {
abortController.abort();
}, abortDelay);
}
componentWillUnmount() {
clearTimeout(this._timeout);
}
render(): React.Node {
return (
<View>
<Button
title="Abort before response"
onPress={() => {
this._submit(0);
}}
/>
<Button
title="Abort after response"
onPress={() => {
this._submit(5000);
}}
/>
</View>
);
}
}
module.exports = XHRExampleAbortController;
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const React = require('react');
const {Alert, Button, View} = require('react-native');
class XHRExampleAbortController extends React.Component<{...}, {...}> {
_timeout: any;
_submit(abortDelay) {
clearTimeout(this._timeout);
const abortController = new global.AbortController();
fetch('https://facebook.github.io/react-native/', {
signal: abortController.signal,
})
.then(res => res.text())
.then(res => Alert.alert(res))
.catch(err => Alert.alert(err.message));
this._timeout = setTimeout(() => {
abortController.abort();
}, abortDelay);
}
componentWillUnmount() {
clearTimeout(this._timeout);
}
render(): React.Node {
return (
<View>
<Button
title="Abort before response"
onPress={() => {
this._submit(0);
}}
/>
<Button
title="Abort after response"
onPress={() => {
this._submit(5000);
}}
/>
</View>
);
}
}
module.exports = XHRExampleAbortController;
| Move eslint-disable no-undef to a global comment | Move eslint-disable no-undef to a global comment
Summary:
Switch the only `// eslint-disable no-undef` to defined the global instead so that the new babel-eslint-no-undef compile time check doesn't need to understand inline eslint comments.
Changelog: [Internal]
Reviewed By: cpojer
Differential Revision: D18644590
fbshipit-source-id: ac9c6da3a5e63b285b5e1dde210613b5d893641b
| JavaScript | mit | facebook/react-native,facebook/react-native,hammerandchisel/react-native,arthuralee/react-native,janicduplessis/react-native,facebook/react-native,javache/react-native,exponent/react-native,myntra/react-native,javache/react-native,exponentjs/react-native,facebook/react-native,janicduplessis/react-native,janicduplessis/react-native,myntra/react-native,hammerandchisel/react-native,arthuralee/react-native,exponent/react-native,hoangpham95/react-native,janicduplessis/react-native,hoangpham95/react-native,pandiaraj44/react-native,facebook/react-native,exponent/react-native,exponent/react-native,facebook/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponent/react-native,arthuralee/react-native,hammerandchisel/react-native,exponentjs/react-native,myntra/react-native,hoangpham95/react-native,janicduplessis/react-native,hoangpham95/react-native,exponentjs/react-native,exponentjs/react-native,exponentjs/react-native,myntra/react-native,exponent/react-native,pandiaraj44/react-native,facebook/react-native,arthuralee/react-native,hoangpham95/react-native,hammerandchisel/react-native,javache/react-native,hammerandchisel/react-native,pandiaraj44/react-native,hoangpham95/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,facebook/react-native,javache/react-native,myntra/react-native,pandiaraj44/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,exponent/react-native,javache/react-native,myntra/react-native,pandiaraj44/react-native,exponentjs/react-native,javache/react-native,hammerandchisel/react-native,javache/react-native,facebook/react-native,myntra/react-native,exponentjs/react-native,exponent/react-native,hoangpham95/react-native,exponentjs/react-native,hammerandchisel/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,arthuralee/react-native | ---
+++
@@ -19,8 +19,7 @@
_submit(abortDelay) {
clearTimeout(this._timeout);
- // eslint-disable-next-line no-undef
- const abortController = new AbortController();
+ const abortController = new global.AbortController();
fetch('https://facebook.github.io/react-native/', {
signal: abortController.signal,
}) |
d38e1808a476d6783bf9ea0989e8dfb61ad6b731 | lib/name-formatter.js | lib/name-formatter.js | var _ = require('underscore');
module.exports = function(name) {
var nameConversions = [
firstInitialAndLastName = /^(\w).*\s(\w+)$/,
firstAndLastName = /^(\w+)\s(\w+)$/,
firstNameAndLastInitial = /^(\w+)\s(\w).+$/
];
var emailDelimiters = [
contiguous = "$1$2",
dot = "$1.$2",
dash = "$1-$2",
underscore = "$1_$2",
reversed = "$2$1",
reversedDot = "$2.$1",
reversedDash = "$2-$1",
reversedUnderscore = "$2_$1",
justLastName = "$2",
justFirstName = "$1",
];
return name.toLowerCase().replace(
_.shuffle(nameConversions)[0],
_.shuffle(emailDelimiters)[0]
) + randomSuffix();
};
// Generate the random chance that a random number will be affixed to the end
function randomSuffix() {
var randomChance = Math.round(Math.random());
if ( randomChance ) {
return Math.floor(Math.random()*1001);
} else {
return "";
}
} | var _ = require('underscore');
module.exports = function(name) {
var nameConversions = [
initials = /^(\w).*\s(\w).*$/
firstInitialAndLastName = /^(\w).*\s(\w+)$/,
firstAndLastName = /^(\w+)\s(\w+)$/,
firstNameAndLastInitial = /^(\w+)\s(\w).+$/
];
var emailDelimiters = [
contiguous = "$1$2",
dot = "$1.$2",
dash = "$1-$2",
underscore = "$1_$2",
reversed = "$2$1",
reversedDot = "$2.$1",
reversedDash = "$2-$1",
reversedUnderscore = "$2_$1",
justLastName = "$2",
justFirstName = "$1",
];
return name.toLowerCase().replace(
_.shuffle(nameConversions)[0],
_.shuffle(emailDelimiters)[0]
) + randomSuffix();
};
// Generate the random chance that a random number will be affixed to the end
function randomSuffix() {
var randomChance = Math.round(Math.random());
if ( randomChance ) {
return Math.floor(Math.random()*101);
} else {
return "";
}
} | Add initials and lower random number | Add initials and lower random number
| JavaScript | mit | stevekinney/node-fake-email | ---
+++
@@ -3,6 +3,7 @@
module.exports = function(name) {
var nameConversions = [
+ initials = /^(\w).*\s(\w).*$/
firstInitialAndLastName = /^(\w).*\s(\w+)$/,
firstAndLastName = /^(\w+)\s(\w+)$/,
firstNameAndLastInitial = /^(\w+)\s(\w).+$/
@@ -35,7 +36,7 @@
var randomChance = Math.round(Math.random());
if ( randomChance ) {
- return Math.floor(Math.random()*1001);
+ return Math.floor(Math.random()*101);
} else {
return "";
} |
cd4c98d937e07c4d7c7d0750509cac40e1f1ffc3 | src/components/videos/VideoView.js | src/components/videos/VideoView.js | import React from 'react'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { updateVideo } from '../../actions/videos'
import { withDatabaseSubscribe } from '../hocs'
import CommentList from '../CommentList'
import PerformanceFrame from '../PerformanceFrame'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.params.videoId}`),
(props) => (snapshot) => (
props.dispatch(updateVideo({
videoId: props.params.videoId,
videoSnapshot: snapshot.val()
}))
)
),
)
const styles = {
videoContainer: {
height: 'calc(100vh - 56px)',
display: 'flex',
flexWrap: 'wrap',
}
}
const VideoView = ({videos, params}) => (
<div style={styles.videoContainer}>
{(params.videoId in videos && videos[params.videoId] !== null) ?
<PerformanceFrame size={{width: 854, height: 480}} layout={{ videoStreams: [{videoId: params.videoId, z_index: 0, scale: 1.0}]}} /> :
<p>{"404 not found"}</p>
}
{videos[params.videoId] !== null ?
<CommentList videoId={params.videoId}/> :
<p>{"duh"}</p>
}
</div>
)
export default enhance(VideoView)
| import * as _ from 'lodash'
import React from 'react'
import {connect} from 'react-redux'
import {compose, withProps} from 'recompose'
import {updateVideo} from '../../actions/videos'
import CommentList from '../CommentList'
import {withDatabaseSubscribe} from '../hocs'
const mapStateToProps = ({videos}) => ({
videos
})
const enhance = compose(
connect(mapStateToProps),
withProps(({match}) => ({
videoId: match.params.videoId,
})),
withDatabaseSubscribe(
'value',
(props) => (`videos/${props.videoId}`),
(props) => (snapshot) => (
props.dispatch(updateVideo(
{
videoId: props.videoId,
videoSnapshot: snapshot.val()
}))
)
),
)
const styles = {
videoContainer: {
height: 'calc(100vh - 56px)',
display: 'flex',
flexWrap: 'wrap',
}
}
const VideoView = ({videos, videoId}) => (
<div style={styles.videoContainer}>
{JSON.stringify(_.get(videos, videoId, {}))}
<CommentList videoId={videoId}/>
</div>
)
export default enhance(VideoView)
| Fix video view and remove some sub components | Fix video view and remove some sub components
- Fixes #28
| JavaScript | mit | mg4tv/mg4tv-web,mg4tv/mg4tv-web | ---
+++
@@ -1,12 +1,12 @@
+import * as _ from 'lodash'
import React from 'react'
-import { connect } from 'react-redux'
-import { compose } from 'recompose'
+import {connect} from 'react-redux'
+import {compose, withProps} from 'recompose'
-import { updateVideo } from '../../actions/videos'
+import {updateVideo} from '../../actions/videos'
+import CommentList from '../CommentList'
-import { withDatabaseSubscribe } from '../hocs'
-import CommentList from '../CommentList'
-import PerformanceFrame from '../PerformanceFrame'
+import {withDatabaseSubscribe} from '../hocs'
const mapStateToProps = ({videos}) => ({
@@ -15,14 +15,18 @@
const enhance = compose(
connect(mapStateToProps),
+ withProps(({match}) => ({
+ videoId: match.params.videoId,
+ })),
withDatabaseSubscribe(
'value',
- (props) => (`videos/${props.params.videoId}`),
+ (props) => (`videos/${props.videoId}`),
(props) => (snapshot) => (
- props.dispatch(updateVideo({
- videoId: props.params.videoId,
- videoSnapshot: snapshot.val()
- }))
+ props.dispatch(updateVideo(
+ {
+ videoId: props.videoId,
+ videoSnapshot: snapshot.val()
+ }))
)
),
)
@@ -36,16 +40,10 @@
}
-const VideoView = ({videos, params}) => (
+const VideoView = ({videos, videoId}) => (
<div style={styles.videoContainer}>
- {(params.videoId in videos && videos[params.videoId] !== null) ?
- <PerformanceFrame size={{width: 854, height: 480}} layout={{ videoStreams: [{videoId: params.videoId, z_index: 0, scale: 1.0}]}} /> :
- <p>{"404 not found"}</p>
- }
- {videos[params.videoId] !== null ?
- <CommentList videoId={params.videoId}/> :
- <p>{"duh"}</p>
- }
+ {JSON.stringify(_.get(videos, videoId, {}))}
+ <CommentList videoId={videoId}/>
</div>
)
|
2d9fe3d781899e9d2a4fbe4d49c71fdcfeba3808 | Server/Models/usersModel.js | Server/Models/usersModel.js | const mongoose = require('mongoose');
const Schema = mongoose.Schema
var userSchema = new Schema({
name: {type: String, required: true},
photo: {type: String, required: true},
email: {type: String, required: true, unique: true},
fbId: {type: String},
fbAccessToken: {type: String},
googleId: {type: String},
createdPins: [{type: Schema.ObjectId, ref:'locations'}],
savedPins: [{type: Schema.ObjectId, ref: 'locations'}],
});
var User = mongoose.model('User', userSchema)
module.exports = User
| const mongoose = require('mongoose');
const Schema = mongoose.Schema
var userSchema = new Schema({
name: {type: String, required: true},
photo: {type: String, required: true},
email: {type: String, required: true, unique: true},
fbId: {type: String},
fbAccessToken: {type: String},
googleId: {type: String},
createdPins: [{type: Schema.ObjectId, ref:'Location'}],
savedPins: [{type: Schema.ObjectId, ref: 'Location'}],
});
var User = mongoose.model('User', userSchema)
module.exports = User
| Adjust user model to populate locations correctly | Adjust user model to populate locations correctly
| JavaScript | mit | JabroniZambonis/pLot | ---
+++
@@ -9,8 +9,8 @@
fbId: {type: String},
fbAccessToken: {type: String},
googleId: {type: String},
- createdPins: [{type: Schema.ObjectId, ref:'locations'}],
- savedPins: [{type: Schema.ObjectId, ref: 'locations'}],
+ createdPins: [{type: Schema.ObjectId, ref:'Location'}],
+ savedPins: [{type: Schema.ObjectId, ref: 'Location'}],
});
|
a4443b203db029fe5ee7df682ca372259b3e4f1c | models/index.js | models/index.js | 'use strict';
var mongoose = require('mongoose');
mongoose.model('User', require('./User'));
mongoose.connect("mongodb://localhost/passport-lesson");
module.exports = mongoose;
| 'use strict';
var mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.model('User', require('./User'));
mongoose.connect("mongodb://localhost/passport-lesson");
module.exports = mongoose;
| Set mongoose to use native promises | Set mongoose to use native promises
| JavaScript | mit | dhuddell/teachers-lounge-back-end | ---
+++
@@ -1,6 +1,7 @@
'use strict';
var mongoose = require('mongoose');
+mongoose.Promise = Promise;
mongoose.model('User', require('./User'));
|
e850a2ce6a17813c537f71807a26d42c4e0165db | 2015-03-MHVLUG/webapp/webapp.js | 2015-03-MHVLUG/webapp/webapp.js | // simple-todos.js
// TODO: Add tasks from console to populate collection
// On Server:
// db.tasks.insert({ text: "Hello world!", createdAt: new Date() });
// On Client:
// Tasks.insert({ text: "Hello world!", createdAt: new Date() });
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
return Tasks.find({});
}
});
// Inside the if (Meteor.isClient) block, right after Template.body.helpers:
Template.body.events({
"submit .new-task": function (event) {
// This function is called when the new task form is submitted
var text = event.target.text.value;
Tasks.insert({
text: text,
createdAt: new Date() // current time
});
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
}
});
}
| // simple-todos.js
// TODO: Add tasks from console to populate collection
// On Server:
// db.tasks.insert({ text: "Hello world!", createdAt: new Date() });
// On Client:
// Tasks.insert({ text: "Hello world!", createdAt: new Date() });
Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
// This code only runs on the client
Template.body.helpers({
tasks: function () {
// Show newest tasks first
return Tasks.find({}, {sort: {createdAt: -1}});
}
});
// Inside the if (Meteor.isClient) block, right after Template.body.helpers:
Template.body.events({
"submit .new-task": function (event) {
// This function is called when the new task form is submitted
var text = event.target.text.value;
Tasks.insert({
text: text,
createdAt: new Date() // current time
});
// Clear form
event.target.text.value = "";
// Prevent default form submit
return false;
}
});
}
| Sort tasks by createdAt timestamp | WebApp-4b: Sort tasks by createdAt timestamp
| JavaScript | apache-2.0 | MeteorHudsonValley/talks,MeteorHudsonValley/talks | ---
+++
@@ -12,7 +12,8 @@
// This code only runs on the client
Template.body.helpers({
tasks: function () {
- return Tasks.find({});
+ // Show newest tasks first
+ return Tasks.find({}, {sort: {createdAt: -1}});
}
});
|
687fcbb285430d6d4df0758ef2eab4a048ab7f07 | docs/config.js | docs/config.js | self.$config = {
landing: false,
debug: false,
repo: 'soruly/whatanime.ga',
twitter: 'soruly',
url: 'https://whatanime.ga',
sidebar: false,
disableSidebarToggle: true,
nav: {
default: []
},
icons: [],
plugins: []
}
| self.$config = {
landing: false,
debug: false,
repo: 'soruly/whatanime.ga',
twitter: 'soruly',
url: 'https://whatanime.ga',
sidebar: true,
disableSidebarToggle: false,
nav: {
default: []
},
icons: [],
plugins: []
}
| Enable sidebar on API docs | Enable sidebar on API docs
| JavaScript | mit | soruly/whatanime.ga,soruly/whatanime.ga,soruly/whatanime.ga | ---
+++
@@ -4,8 +4,8 @@
repo: 'soruly/whatanime.ga',
twitter: 'soruly',
url: 'https://whatanime.ga',
- sidebar: false,
- disableSidebarToggle: true,
+ sidebar: true,
+ disableSidebarToggle: false,
nav: {
default: []
}, |
07ec1f9de2c8a5233bdafbc0a16b606520ee1be8 | js/webpack.config.js | js/webpack.config.js | var loaders = [
{ test: /\.json$/, loader: "json-loader" },
];
module.exports = [
{// Notebook extension
entry: './src/extension.js',
output: {
filename: 'extension.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
}
},
{// bqplot bundle for the notebook
entry: './src/index.js',
output: {
filename: 'index.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
},
devtool: 'source-map',
module: {
loaders: loaders
},
externals: ['jupyter-js-widgets']
},
{// embeddable bqplot bundle
entry: './src/index.js',
output: {
filename: 'embed.js',
path: './dist/',
libraryTarget: 'amd'
},
devtool: 'source-map',
module: {
loaders: loaders
},
externals: ['jupyter-js-widgets']
}
];
| var loaders = [
{ test: /\.json$/, loader: "json-loader" },
];
module.exports = [
{// Notebook extension
entry: './src/extension.js',
output: {
filename: 'extension.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
}
},
{// bqplot bundle for the notebook
entry: './src/index.js',
output: {
filename: 'index.js',
path: '../pythreejs/static',
libraryTarget: 'amd'
},
devtool: 'source-map',
module: {
loaders: loaders
},
externals: ['jupyter-js-widgets']
},
{// embeddable bqplot bundle
entry: './src/index.js',
output: {
filename: 'index.js',
path: './dist/',
libraryTarget: 'amd'
},
devtool: 'source-map',
module: {
loaders: loaders
},
externals: ['jupyter-js-widgets']
}
];
| Use new scheme for npmcdn | Use new scheme for npmcdn
| JavaScript | bsd-3-clause | jasongrout/pythreejs,jasongrout/pythreejs | ---
+++
@@ -27,7 +27,7 @@
{// embeddable bqplot bundle
entry: './src/index.js',
output: {
- filename: 'embed.js',
+ filename: 'index.js',
path: './dist/',
libraryTarget: 'amd'
}, |
1887b3c7024779ebb8873277b2472dbe9141d0f5 | server/controllers/signup.js | server/controllers/signup.js | // SignupController
// ================
// Handles routing for signing up for the pp
'use strict';
let express = require('express'),
SignupController = express.Router(),
bcrypt = require('bcrypt'),
User = require(__dirname + '/../models/user');
SignupController.route('/?')
// GET /signup/
// -----------
// Render login page
.get(function(req, res, next) {
res.render('authentication/signup', {
csrf: req.csrfToken(),
scripts: ['/js/signup.min.js']
});
})
// POST /signup/
// ------------
// Registers a new user
.post(function(req, res, next) {
// Check if user exists in database
User
.where({ email: req.body.email })
.fetch()
.then(function(user) {
if (user) {
bcrypt.hash(req.body.password, 10, function(err, hash) {
if (err) return next(new Error('Could not hash password'));
// Create a new user
new User({
email: req.body.email,
password: hash
})
.save()
.then(function(user) {
res.send('User created');
})
.catch(function(err) {
res.send('username or email already taken');
});
});
} else {
res.send('could not create new user');
}
})
.catch(function(err) {
console.log(err, 'FETCH ERROR');
res.send('Could not run fetch query');
});
});
module.exports = SignupController;
| // SignupController
// ================
// Handles routing for signing up for the pp
'use strict';
let express = require('express'),
SignupController = express.Router(),
bcrypt = require('bcrypt'),
User = require(__dirname + '/../models/user');
SignupController.route('/?')
// GET /signup/
// -----------
// Render login page
.get(function(req, res, next) {
res.render('authentication/signup', {
csrf: req.csrfToken(),
scripts: ['/js/signup.min.js']
});
})
// POST /signup/
// ------------
// Registers a new user
.post(function(req, res, next) {
// Check if user exists in database
User.where({ email: req.body.email })
.fetchAll()
.then(function(user) {
if (user) {
bcrypt.hash(req.body.password, 10, function(err, hash) {
if (err) return next(new Error('Could not hash password'));
// Create a new user
new User({
email: req.body.email,
password: hash
})
.save()
.then(function(user) {
res.send('User created');
})
.catch(function(err) {
res.send('username or email already taken');
});
});
} else {
res.send('could not create new user');
}
})
.catch(function(err) {
console.log(err, 'FETCH ERROR');
res.send('Could not run fetch query');
});
});
module.exports = SignupController;
| Fix issue where users were not saving to the database. | Fix issue where users were not saving to the database.
We use .fetchAll() rather than .fetch() to find
all instances of a user. Added auto-timestamp
functionality so all create and update times are
automatically marked with no manual intervention needed.
| JavaScript | mit | billpatrianakos/coverage-web,billpatrianakos/coverage-web,billpatrianakos/coverage-web | ---
+++
@@ -24,35 +24,34 @@
// Registers a new user
.post(function(req, res, next) {
// Check if user exists in database
- User
- .where({ email: req.body.email })
- .fetch()
- .then(function(user) {
- if (user) {
- bcrypt.hash(req.body.password, 10, function(err, hash) {
- if (err) return next(new Error('Could not hash password'));
+ User.where({ email: req.body.email })
+ .fetchAll()
+ .then(function(user) {
+ if (user) {
+ bcrypt.hash(req.body.password, 10, function(err, hash) {
+ if (err) return next(new Error('Could not hash password'));
- // Create a new user
- new User({
- email: req.body.email,
- password: hash
- })
- .save()
- .then(function(user) {
- res.send('User created');
- })
- .catch(function(err) {
- res.send('username or email already taken');
- });
+ // Create a new user
+ new User({
+ email: req.body.email,
+ password: hash
+ })
+ .save()
+ .then(function(user) {
+ res.send('User created');
+ })
+ .catch(function(err) {
+ res.send('username or email already taken');
});
- } else {
- res.send('could not create new user');
- }
- })
- .catch(function(err) {
- console.log(err, 'FETCH ERROR');
- res.send('Could not run fetch query');
- });
+ });
+ } else {
+ res.send('could not create new user');
+ }
+ })
+ .catch(function(err) {
+ console.log(err, 'FETCH ERROR');
+ res.send('Could not run fetch query');
+ });
});
module.exports = SignupController; |
40350431927e12b74874ebf17b761535cccc76c5 | src/features/spellchecker/index.js | src/features/spellchecker/index.js | import { autorun, observable } from 'mobx';
import { DEFAULT_FEATURES_CONFIG } from '../../config';
const debug = require('debug')('Franz:feature:spellchecker');
export const config = observable({
isIncludedInCurrentPlan: DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan,
});
export default function init(stores) {
debug('Initializing `spellchecker` feature');
autorun(() => {
const { isSpellcheckerIncludedInCurrentPlan } = stores.features.features;
config.isIncludedInCurrentPlan = isSpellcheckerIncludedInCurrentPlan !== undefined ? isSpellcheckerIncludedInCurrentPlan : DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan;
if (!stores.user.data.isPremium && config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) {
debug('Override settings.spellcheckerEnabled flag to false');
Object.assign(stores.settings.app, {
enableSpellchecking: false,
});
}
});
}
| import { autorun, observable } from 'mobx';
import { DEFAULT_FEATURES_CONFIG } from '../../config';
const debug = require('debug')('Franz:feature:spellchecker');
export const config = observable({
isIncludedInCurrentPlan: DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan,
});
export default function init(stores) {
debug('Initializing `spellchecker` feature');
autorun(() => {
const { isSpellcheckerIncludedInCurrentPlan } = stores.features.features;
config.isIncludedInCurrentPlan = isSpellcheckerIncludedInCurrentPlan !== undefined ? isSpellcheckerIncludedInCurrentPlan : DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan;
if (!stores.user.data.isPremium && !config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) {
debug('Override settings.spellcheckerEnabled flag to false');
Object.assign(stores.settings.app, {
enableSpellchecking: false,
});
}
});
}
| Fix disabling spellchecker after app start | fix(Spellchecker): Fix disabling spellchecker after app start
| JavaScript | apache-2.0 | meetfranz/franz,meetfranz/franz,meetfranz/franz | ---
+++
@@ -16,7 +16,7 @@
config.isIncludedInCurrentPlan = isSpellcheckerIncludedInCurrentPlan !== undefined ? isSpellcheckerIncludedInCurrentPlan : DEFAULT_FEATURES_CONFIG.isSpellcheckerIncludedInCurrentPlan;
- if (!stores.user.data.isPremium && config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) {
+ if (!stores.user.data.isPremium && !config.isIncludedInCurrentPlan && stores.settings.app.enableSpellchecking) {
debug('Override settings.spellcheckerEnabled flag to false');
Object.assign(stores.settings.app, { |
c9ee70bdc817e010bd00468bac99daf236035e2e | src/frontend/pages/Logout/index.js | src/frontend/pages/Logout/index.js | // @flow
import * as React from 'react'
import { Redirect } from 'react-router-dom'
import performLogout from 'frontend/firebase/logout'
class Logout extends React.Component<*> {
componentDidMount() {
performLogout()
}
render() {
return <Redirect to="/" />
}
}
export default Logout
| // @flow
import * as React from 'react'
import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'
import { USER_LOGGED_OUT } from 'frontend/actions/types'
import performLogout from 'frontend/firebase/logout'
type Props = {
logout: Function
}
class Logout extends React.Component<Props> {
componentDidMount() {
performLogout()
this.props.logout()
}
render() {
return <Redirect to="/" />
}
}
const mapDispatchToProps = (dispatch: Function) => ({
logout: () => dispatch({ type: USER_LOGGED_OUT })
})
export default connect(null, mapDispatchToProps)(Logout)
| Clear user login state in Redux on logout. | Clear user login state in Redux on logout.
| JavaScript | mit | jsonnull/aleamancer,jsonnull/aleamancer | ---
+++
@@ -1,11 +1,17 @@
// @flow
import * as React from 'react'
+import { connect } from 'react-redux'
import { Redirect } from 'react-router-dom'
+import { USER_LOGGED_OUT } from 'frontend/actions/types'
import performLogout from 'frontend/firebase/logout'
-class Logout extends React.Component<*> {
+type Props = {
+ logout: Function
+}
+class Logout extends React.Component<Props> {
componentDidMount() {
performLogout()
+ this.props.logout()
}
render() {
@@ -13,4 +19,8 @@
}
}
-export default Logout
+const mapDispatchToProps = (dispatch: Function) => ({
+ logout: () => dispatch({ type: USER_LOGGED_OUT })
+})
+
+export default connect(null, mapDispatchToProps)(Logout) |
682c1bc6ec836f3a16543845444aafabafa788f9 | lib/unexpectedExif.js | lib/unexpectedExif.js | /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
version: require('../package.json').version,
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion(['string', 'Buffer'], 'to have (exif|EXIF) data satisfying', function (expect, subject, value) {
var title,
subjectUrl;
if (typeof subject === 'string') {
var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/);
if (matchDataUrl) {
subject = new Buffer(matchDataUrl[1], 'base64');
} else {
title = subject;
subjectUrl = subject;
subject = fs.readFileSync(subject);
}
} else if (subject instanceof Uint8Array) {
subject = new Buffer(subject);
}
this.subjectOutput = function () {
this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title });
};
var exifData = exifParser.create(subject).parse();
if (exifData && exifData.startMarker) {
delete exifData.startMarker;
}
return expect(exifData, 'to satisfy', value);
});
}
};
| /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
version: require('../package.json').version,
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion('<string|Buffer> to have (exif|EXIF) data satisfying <any>', function (expect, subject, value) {
var title,
subjectUrl;
if (typeof subject === 'string') {
var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/);
if (matchDataUrl) {
subject = new Buffer(matchDataUrl[1], 'base64');
} else {
title = subject;
subjectUrl = subject;
subject = fs.readFileSync(subject);
}
} else if (subject instanceof Uint8Array) {
subject = new Buffer(subject);
}
this.subjectOutput = function () {
this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title });
};
var exifData = exifParser.create(subject).parse();
if (exifData && exifData.startMarker) {
delete exifData.startMarker;
}
return expect(exifData, 'to satisfy', value);
});
}
};
| Update to unexpected v10's addAssertion syntax . | Update to unexpected v10's addAssertion syntax [ci skip].
| JavaScript | bsd-3-clause | unexpectedjs/unexpected-exif | ---
+++
@@ -8,7 +8,7 @@
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
- expect.addAssertion(['string', 'Buffer'], 'to have (exif|EXIF) data satisfying', function (expect, subject, value) {
+ expect.addAssertion('<string|Buffer> to have (exif|EXIF) data satisfying <any>', function (expect, subject, value) {
var title,
subjectUrl;
if (typeof subject === 'string') { |
5fc74d690fcf059940d7449bce11ec6b56b73eb2 | lib/process-manager.js | lib/process-manager.js | /** @babel */
import childProcess from 'child_process'
import kill from 'tree-kill'
import { Disposable } from 'atom'
export default class ProcessManager extends Disposable {
processes = new Set()
constructor () {
super(() => this.killChildProcesses())
}
executeChildProcess (command, options = {}) {
const { allowKill, showError, ...execOptions } = options
return new Promise(resolve => {
// Windows does not like \$ appearing in command lines so only escape
// if we need to.
if (process.platform !== 'win32') command = command.replace('$', '\\$')
const { pid } = childProcess.exec(command, execOptions, (error, stdout, stderr) => {
if (allowKill) {
this.processes.delete(pid)
}
if (error && showError) {
latex.log.error(`An error occurred while trying to run "${command}" (${error.code}).`)
}
resolve({
statusCode: error ? error.code : 0,
stdout,
stderr
})
})
if (allowKill) {
this.processes.add(pid)
}
})
}
killChildProcesses () {
for (const pid of this.processes.values()) {
kill(pid)
}
this.processes.clear()
}
}
| /** @babel */
import childProcess from 'child_process'
import kill from 'tree-kill'
import { Disposable } from 'atom'
export default class ProcessManager extends Disposable {
processes = new Set()
constructor () {
super(() => this.killChildProcesses())
}
executeChildProcess (command, options = {}) {
const { allowKill, showError, ...execOptions } = options
return new Promise(resolve => {
// Windows does not like \$ appearing in command lines so only escape
// if we need to.
if (process.platform !== 'win32') command = command.replace('$', '\\$')
const { pid } = childProcess.exec(command, execOptions, (error, stdout, stderr) => {
if (allowKill) {
this.processes.delete(pid)
}
if (error && showError && latex && latex.log) {
latex.log.error(`An error occurred while trying to run "${command}" (${error.code}).`)
}
resolve({
statusCode: error ? error.code : 0,
stdout,
stderr
})
})
if (allowKill) {
this.processes.add(pid)
}
})
}
killChildProcesses () {
for (const pid of this.processes.values()) {
kill(pid)
}
this.processes.clear()
}
}
| Add guard to process error log | Add guard to process error log
In case process is still running when package is disabled.
| JavaScript | mit | thomasjo/atom-latex,thomasjo/atom-latex,thomasjo/atom-latex | ---
+++
@@ -21,7 +21,7 @@
if (allowKill) {
this.processes.delete(pid)
}
- if (error && showError) {
+ if (error && showError && latex && latex.log) {
latex.log.error(`An error occurred while trying to run "${command}" (${error.code}).`)
}
resolve({ |
754eafc1736174f00d9d7b1ceb8df1b20af66417 | app/soc/content/js/templates/modules/gsoc/_survey.js | app/soc/content/js/templates/modules/gsoc/_survey.js | /* Copyright 2011 the Melange authors.
*
* 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.
*/
/**
* @author <a href="mailto:fadinlight@gmail.com">Mario Ferraro</a>
*/
(function() {
var template_name = "survey";
melange.template[template_name] = function(_self, context) {
};
melange.template[template_name].prototype = new melange.templates._baseTemplate();
melange.template[template_name].prototype.constructor = melange.template[template_name];
melange.template[template_name].apply(
melange.template[template_name],
[melange.template[template_name], melange.template[template_name].prototype.context]
);
}());
| /* Copyright 2011 the Melange authors.
*
* 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.
*/
/**
* @author <a href="mailto:fadinlight@gmail.com">Mario Ferraro</a>
*/
melange.templates.inherit(
function (_self, context) {
}
);
| Make the skeleton survey JS compatible with the new JS templates. | Make the skeleton survey JS compatible with the new JS templates.
| JavaScript | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -16,16 +16,7 @@
* @author <a href="mailto:fadinlight@gmail.com">Mario Ferraro</a>
*/
-(function() {
- var template_name = "survey";
-
- melange.template[template_name] = function(_self, context) {
- };
-
- melange.template[template_name].prototype = new melange.templates._baseTemplate();
- melange.template[template_name].prototype.constructor = melange.template[template_name];
- melange.template[template_name].apply(
- melange.template[template_name],
- [melange.template[template_name], melange.template[template_name].prototype.context]
- );
-}());
+melange.templates.inherit(
+ function (_self, context) {
+ }
+); |
f6e40afb28c93c3b537d73d2313fc2bf17e7548f | src/build.js | src/build.js | import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
return postcss([tailwind(), require('autoprefixer')])
.process(css, {
from: `./${filename}.css`,
to: `./dist/${filename}.css`,
map: { inline: false },
})
.then(result => {
fs.writeFileSync(`./dist/${filename}.css`, result.css)
if (result.map) {
fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
}
return result
})
.then(result => {
const minified = new CleanCSS().minify(result.css)
fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
})
.then(resolve)
.catch(error => {
console.log(error)
reject()
})
})
})
}
console.info('Building Tailwind!')
Promise.all([
buildDistFile('preflight'),
buildDistFile('components'),
buildDistFile('utilities'),
buildDistFile('tailwind'),
]).then(() => {
console.log('Finished Building Tailwind!')
})
| import fs from 'fs'
import postcss from 'postcss'
import tailwind from '..'
import CleanCSS from 'clean-css'
function buildDistFile(filename) {
return new Promise((resolve, reject) => {
console.log(`Processing ./${filename}.css...`)
fs.readFile(`./${filename}.css`, (err, css) => {
if (err) throw err
return postcss([tailwind(), require('autoprefixer')])
.process(css, {
from: `./${filename}.css`,
to: `./dist/${filename}.css`,
map: { inline: false },
})
.then(result => {
fs.writeFileSync(`./dist/${filename}.css`, result.css)
if (result.map) {
fs.writeFileSync(`./dist/${filename}.css.map`, result.map)
}
return result
})
.then(result => {
const minified = new CleanCSS().minify(result.css)
fs.writeFileSync(`./dist/${filename}.min.css`, minified.styles)
})
.then(resolve)
.catch(error => {
console.log(error)
reject()
})
})
})
}
console.info('Building Tailwind!')
Promise.all([
buildDistFile('base'),
buildDistFile('components'),
buildDistFile('utilities'),
buildDistFile('tailwind'),
]).then(() => {
console.log('Finished Building Tailwind!')
})
| Build base instead of preflight | Build base instead of preflight
| JavaScript | mit | tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss,tailwindlabs/tailwindcss | ---
+++
@@ -39,7 +39,7 @@
console.info('Building Tailwind!')
Promise.all([
- buildDistFile('preflight'),
+ buildDistFile('base'),
buildDistFile('components'),
buildDistFile('utilities'),
buildDistFile('tailwind'), |
6d0946dd4d0746486bc0290e65df86ead40337dd | lib/wait-for-socket.js | lib/wait-for-socket.js | 'use strict';
var net = require('net'),
utils = require('radiodan-client').utils,
logger = utils.logger(__filename);
function create(port, socket) {
var deferred = utils.promise.defer(),
retries = 0,
timeout = 1000;
socket = socket || new net.Socket();
socket.setTimeout(2500);
function addHandlers() {
socket.on('connect', handleConnect);
socket.on('error', handleError);
}
function handleConnect() {
logger.debug('Connected to', port);
deferred.resolve(port);
}
function handleError() {
logger.warn('Cannot connect, attempt #' + ++retries);
setTimeout(function () {
socket.connect(port);
}, timeout);
}
function connect() {
logger.debug('Connecting to port', port);
addHandlers();
socket.connect(port);
return deferred.promise;
}
return {
_addHandlers: addHandlers,
connect: connect
};
}
module.exports = {
create: create
};
| 'use strict';
var net = require('net'),
utils = require('radiodan-client').utils,
logger = utils.logger(__filename);
function create(port, socket) {
var deferred = utils.promise.defer(),
retries = 0,
timeout = 1000;
socket = socket || new net.Socket();
socket.setTimeout(2500);
function addHandlers() {
socket.on('connect', handleConnect);
socket.on('error', handleError);
}
function handleConnect() {
logger.debug('Connected to', port);
deferred.resolve(port);
}
function handleError() {
retries++;
logger.warn('Cannot connect, attempt #' + retries);
setTimeout(function () {
socket.connect(port);
}, timeout);
}
function connect() {
logger.debug('Connecting to port', port);
addHandlers();
socket.connect(port);
return deferred.promise;
}
return {
_addHandlers: addHandlers,
connect: connect
};
}
module.exports = {
create: create
};
| Increment `retries` variable in a way that pleases `jshint`. | Increment `retries` variable in a way that pleases `jshint`.
| JavaScript | apache-2.0 | radiodan/radiodan.js,radiodan/radiodan.js | ---
+++
@@ -24,7 +24,9 @@
}
function handleError() {
- logger.warn('Cannot connect, attempt #' + ++retries);
+ retries++;
+
+ logger.warn('Cannot connect, attempt #' + retries);
setTimeout(function () {
socket.connect(port); |
1e7ce40caa9255e40bfabfc8c9238cae159d562a | migrations/1_add_paths.js | migrations/1_add_paths.js | 'use strict';
exports.up = function(knex, Promise) {
return knex.schema.
createTable('paths', function (t) {
t.increments('id');
t.text('curator').notNullable();
t.text('curator_org');
t.specificType('collaborators', 'text[]');
t.text('name').notNullable();
t.text('description');
t.text('version').notNullable();
t.text('license');
t.text('image_url');
t.text('asset_urls');
t.text('keywords');
t.timestamp('created').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('paths');
};
| 'use strict';
exports.up = function(knex, Promise) {
return knex.schema.
createTable('paths', function (t) {
t.increments('id');
t.text('curator').notNullable();
t.text('curator_org');
t.specificType('collaborators', 'text[]');
t.text('name').notNullable();
t.text('description');
t.text('version').notNullable();
t.text('license');
t.text('image_url');
t.specificType('asset_urls', 'text[]');
t.specificType('keywords', 'text[]');
t.timestamp('created').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
});
};
exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('paths');
};
| Update keyword and asset_url fields to accept arrays. | Update keyword and asset_url fields to accept arrays.
Resolves #16
| JavaScript | mit | coding-the-humanities/unacademic_backend,coding-the-humanities/unacademic_backend | ---
+++
@@ -12,8 +12,8 @@
t.text('version').notNullable();
t.text('license');
t.text('image_url');
- t.text('asset_urls');
- t.text('keywords');
+ t.specificType('asset_urls', 'text[]');
+ t.specificType('keywords', 'text[]');
t.timestamp('created').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
});
}; |
3a7bad8761e57ec39100f780360908de036be3f2 | models/InternalNote.js | models/InternalNote.js | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
// Create fields
InternalNotes.add({
child: { type: Types.Relationship, label: 'child', ref: 'Child', initial: true, },
family: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
date: { type: Types.Text, label: 'note date', note: 'mm/dd/yyyy', required: true, noedit: true, initial: true, },
employee: { type: Types.Relationship, label: 'note creator', ref: 'User', required: true, noedit: true, initial: true, },
note: { type: Types.Textarea, label: 'note', required: true, initial: true, }
});
// Pre Save
InternalNotes.schema.pre('save', function(next) {
'use strict';
// generate an internal ID based on the current highest internal ID
// get the employee who is currently logged in and save ID to employee
// TODO: Assign a registration number if one isn't assigned
next();
});
// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date, child, family, note';
InternalNotes.register(); | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
track: true,
autokey: { path: 'key', from: 'slug', unique: true },
defaultSort: 'date'
});
// Create fields
InternalNotes.add({
child: { type: Types.Relationship, label: 'child', ref: 'Child', initial: true, },
prospectiveParentOrFamily: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
date: { type: Types.Text, label: 'note date', note: 'mm/dd/yyyy', required: true, noedit: true, initial: true, },
employee: { type: Types.Relationship, label: 'note creator', ref: 'User', required: true, noedit: true, initial: true, },
note: { type: Types.Textarea, label: 'note', required: true, initial: true, }
});
// Pre Save
InternalNotes.schema.pre('save', function(next) {
'use strict';
// generate an internal ID based on the current highest internal ID
// get the employee who is currently logged in and save ID to employee
// TODO: Assign a registration number if one isn't assigned
next();
});
// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date, child, family, note';
InternalNotes.register(); | Fix a bad reference value in the Internal Note model. | Fix a bad reference value in the Internal Note model.
| JavaScript | mit | autoboxer/MARE,autoboxer/MARE | ---
+++
@@ -12,7 +12,7 @@
InternalNotes.add({
child: { type: Types.Relationship, label: 'child', ref: 'Child', initial: true, },
- family: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
+ prospectiveParentOrFamily: { type: Types.Relationship, label: 'family', ref: 'Prospective Parent or Family', initial: true },
date: { type: Types.Text, label: 'note date', note: 'mm/dd/yyyy', required: true, noedit: true, initial: true, },
employee: { type: Types.Relationship, label: 'note creator', ref: 'User', required: true, noedit: true, initial: true, },
note: { type: Types.Textarea, label: 'note', required: true, initial: true, } |
2be619f254bf2794346c2482f16666b3670182ca | src/index.js | src/index.js | define([
"less!src/stylesheets/main.less"
], function() {
var manager = new codebox.tabs.Manager();
// Add tabs to grid
codebox.app.grid.addView(manager, {
width: 20
});
// Render the tabs manager
manager.render();
// Make the tab manager global
codebox.panels = manager;
}); | define([
"less!src/stylesheets/main.less"
], function() {
var manager = new codebox.tabs.Manager();
// Add tabs to grid
codebox.app.grid.addView(manager, {
width: 20,
at: 0
});
// Render the tabs manager
manager.render();
// Make the tab manager global
codebox.panels = manager;
}); | Add at first position in grid | Add at first position in grid
| JavaScript | apache-2.0 | CodeboxIDE/package-panels,etopian/codebox-package-panels | ---
+++
@@ -5,7 +5,8 @@
// Add tabs to grid
codebox.app.grid.addView(manager, {
- width: 20
+ width: 20,
+ at: 0
});
// Render the tabs manager |
2af8c1d2919d0cbe9dd92c28058d0bd199d08836 | src/index.js | src/index.js | #!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']
if (argv.length === 0 || argv[0] === 'help') {
console.log('abc [command]\n\nCommands:')
console.log(' build Compiles the source files from src/ into a build/ directory. ')
console.log(' run src/file.js Runs a specified file.')
console.log(' test Runs the test files in the tests/ directory.')
console.log(' lint Checks if your code is consistent and follows best practices. ')
console.log(' setup Creates the directories and files for the whole project to run.')
console.log(' help This help page you are looking at!')
process.exit(0)
}
if (whitelist.indexOf(argv[0]) === -1) {
log.error('Command `' + argv[0] + '` does not exist')
process.exit(1)
}
var callback = require('./' + argv[0] + '.js')
callback.apply(null, argv.splice(1))
| #!/usr/bin/env node
var argv = process.argv.splice(2)
var log = require('./helpers/log.js')
var whitelist = ['build', 'run', 'test', 'lint', 'setup']
if (argv.length === 0 || argv[0] === 'help') {
console.log('abc [command]')
console.log('')
console.log('Commands:')
console.log(' setup Creates the directories and files for the whole project to run.')
console.log(' build Compiles the source files from src/ into a build/ directory.')
console.log(' test Runs the test files in the tests/ directory.')
console.log(' lint Checks if your code is consistent and follows best practices.')
console.log(' run src/file.js Runs a specified file.')
console.log(' help This help page you are looking at!')
process.exit(0)
}
if (whitelist.indexOf(argv[0]) === -1) {
log.error('Command `' + argv[0] + '` does not exist')
process.exit(1)
}
var callback = require('./' + argv[0] + '.js')
callback.apply(null, argv.splice(1))
| Remove whitespace & use same order as in readme | Remove whitespace & use same order as in readme
| JavaScript | mit | queicherius/abc-environment,queicherius/abc-environment | ---
+++
@@ -4,12 +4,14 @@
var whitelist = ['build', 'run', 'test', 'lint', 'setup']
if (argv.length === 0 || argv[0] === 'help') {
- console.log('abc [command]\n\nCommands:')
- console.log(' build Compiles the source files from src/ into a build/ directory. ')
+ console.log('abc [command]')
+ console.log('')
+ console.log('Commands:')
+ console.log(' setup Creates the directories and files for the whole project to run.')
+ console.log(' build Compiles the source files from src/ into a build/ directory.')
+ console.log(' test Runs the test files in the tests/ directory.')
+ console.log(' lint Checks if your code is consistent and follows best practices.')
console.log(' run src/file.js Runs a specified file.')
- console.log(' test Runs the test files in the tests/ directory.')
- console.log(' lint Checks if your code is consistent and follows best practices. ')
- console.log(' setup Creates the directories and files for the whole project to run.')
console.log(' help This help page you are looking at!')
process.exit(0)
} |
b390a49f0ff94cb6944623e467383af4d0f436b7 | src/index.js | src/index.js | module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => {
const patched = [mutableTarget].concat(...args.slice(1));
return mutableHandler[property].apply(null, patched);
};
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(() => {}, handler)
};
};
| module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(() => {}, handler)
};
};
| Revert proxy handler change for coverage | Revert proxy handler change for coverage
| JavaScript | mit | Griffingj/mutable-proxy | ---
+++
@@ -33,10 +33,7 @@
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
- return (...args) => {
- const patched = [mutableTarget].concat(...args.slice(1));
- return mutableHandler[property].apply(null, patched);
- };
+ return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
}
});
|
f215aeb4e0ff59d2028088349e965e6207f08228 | mysite/ct/static/js/ct.js | mysite/ct/static/js/ct.js | function setInterest(targeturl, state, csrftoken)
{
$.post(targeturl,
{
csrfmiddlewaretoken:csrftoken,
state:state
});
}
function toggleInterest(o, targeturl, csrftoken)
{
if (o.value == "1")
{
o.value="0";
}
else
{
o.value="1";
}
setInterest(targeturl, o.value, csrftoken);
}
$(document).ready(function(){
var GRADEABLE_SUB_KINDS = ['numbers', 'equation'];
var elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_precision,#div_id_enable_auto_grading");
var sub_kind_field = $('#id_sub_kind');
if ($.inArray($(sub_kind_field).val(), GRADEABLE_SUB_KINDS) == -1 ) {
elements.hide();
}
sub_kind_field.on('change', function(e){
// show and hide numbers related fields
if ($.inArray($(this).val(), GRADEABLE_SUB_KINDS) != -1 ) {
elements.show();
} else {
elements.hide();
$("#id_enable_auto_grading").prop('checked', false);
}
})
});
| function setInterest(targeturl, state, csrftoken)
{
$.post(targeturl,
{
csrfmiddlewaretoken:csrftoken,
state:state
});
}
function toggleInterest(o, targeturl, csrftoken)
{
if (o.value == "1")
{
o.value="0";
}
else
{
o.value="1";
}
setInterest(targeturl, o.value, csrftoken);
}
$(document).ready(function(){
var GRADEABLE_SUB_KINDS = ['numbers', 'equation'];
var number_elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_value");
var grading_elements = $("#div_id_enable_auto_grading");
var sub_kind_field = $('#id_sub_kind');
if (sub_kind_field.val() !== 'numbers') {
number_elements.hide();
}
if ($.inArray(sub_kind_field.val(), GRADEABLE_SUB_KINDS) == -1 ) {
grading_elements.hide();
}
sub_kind_field.on('change', function(e){
// show and hide numbers related fields
if ($.inArray($(this).val(), GRADEABLE_SUB_KINDS) != -1 ) {
grading_elements.show();
} else {
grading_elements.hide();
$("#id_enable_auto_grading").prop('checked', false);
}
})
});
| Fix for nnumbers to show\hide fields | Fix for nnumbers to show\hide fields
| JavaScript | apache-2.0 | raccoongang/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2,raccoongang/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2,cjlee112/socraticqs2,cjlee112/socraticqs2 | ---
+++
@@ -23,19 +23,25 @@
$(document).ready(function(){
var GRADEABLE_SUB_KINDS = ['numbers', 'equation'];
- var elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_precision,#div_id_enable_auto_grading");
+ var number_elements = $("#div_id_number_max_value,#div_id_number_min_value,#div_id_number_value");
+ var grading_elements = $("#div_id_enable_auto_grading");
var sub_kind_field = $('#id_sub_kind');
- if ($.inArray($(sub_kind_field).val(), GRADEABLE_SUB_KINDS) == -1 ) {
- elements.hide();
+ if (sub_kind_field.val() !== 'numbers') {
+ number_elements.hide();
+ }
+
+
+ if ($.inArray(sub_kind_field.val(), GRADEABLE_SUB_KINDS) == -1 ) {
+ grading_elements.hide();
}
sub_kind_field.on('change', function(e){
// show and hide numbers related fields
if ($.inArray($(this).val(), GRADEABLE_SUB_KINDS) != -1 ) {
- elements.show();
+ grading_elements.show();
} else {
- elements.hide();
+ grading_elements.hide();
$("#id_enable_auto_grading").prop('checked', false);
}
}) |
9002c6ea6bf1137afb67d2449e67d63c9cf83c3e | js/models/tag.js | js/models/tag.js | ds.models.tag = function(data) {
"use strict";
var storage = {}
, self = {}
limivorous.observable(self, storage)
.property(self, 'id', storage)
.property(self, 'href', storage)
.property(self, 'name', storage)
.property(self, 'description', storage)
.property(self, 'color', storage)
.property(self, 'count', storage)
Object.defineProperty(self, 'is_tag', {value: true});
if (data) {
if (data.is_tag) {
return data
} else if (typeof data === 'string') {
self.name = data
} else {
self.id = data.id
self.href = data.href
self.name = data.name
self.description = data.description
self.color = data.color
self.count = data.count
}
}
self.toJSON = function() {
return {
id: self.id,
href: self.href,
name: self.name,
description: self.description,
color: self.color,
count: self.count
}
}
return self
}
| ds.models.tag = function(data) {
"use strict";
var storage = {}
, self = {}
limivorous.observable(self, storage)
.property(self, 'id', storage)
.property(self, 'href', storage)
.property(self, 'name', storage)
.property(self, 'description', storage)
.property(self, 'color', storage)
.property(self, 'count', storage)
Object.defineProperty(self, 'is_tag', {value: true});
if (data) {
if (data.is_tag) {
return data
} else if (typeof data === 'string') {
self.name = data
} else {
self.id = data.id
self.href = data.href
self.name = data.name
self.description = data.description
self.color = data.color
self.count = data.count
}
}
self.toJSON = function() {
var json = {}
if (self.id)
json.id = self.id
if (self.href)
json.href = self.href
if (self.name)
json.name = self.name
if (self.description)
json.description = self.description
if (self.color)
json.color = self.color
if (self.count)
json.count = self.count
return json
}
return self
}
| Rewrite toJSON to eliminate null values | Rewrite toJSON to eliminate null values
| JavaScript | apache-2.0 | urbanairship/tessera,section-io/tessera,jmptrader/tessera,tessera-metrics/tessera,jmptrader/tessera,jmptrader/tessera,filippog/tessera,urbanairship/tessera,urbanairship/tessera,urbanairship/tessera,aalpern/tessera,filippog/tessera,tessera-metrics/tessera,filippog/tessera,section-io/tessera,jmptrader/tessera,section-io/tessera,Slach/tessera,aalpern/tessera,Slach/tessera,tessera-metrics/tessera,aalpern/tessera,aalpern/tessera,aalpern/tessera,urbanairship/tessera,Slach/tessera,Slach/tessera,tessera-metrics/tessera,tessera-metrics/tessera,section-io/tessera,jmptrader/tessera | ---
+++
@@ -29,14 +29,20 @@
}
self.toJSON = function() {
- return {
- id: self.id,
- href: self.href,
- name: self.name,
- description: self.description,
- color: self.color,
- count: self.count
- }
+ var json = {}
+ if (self.id)
+ json.id = self.id
+ if (self.href)
+ json.href = self.href
+ if (self.name)
+ json.name = self.name
+ if (self.description)
+ json.description = self.description
+ if (self.color)
+ json.color = self.color
+ if (self.count)
+ json.count = self.count
+ return json
}
return self |
2567834bb6ae44d6b2834a7d36709d97e166b790 | lib/commands/lint.js | lib/commands/lint.js | 'use strict'
module.exports = function (dep) {
let cmd = {}
cmd.command = 'lint'
cmd.desc = 'Run linters and fix possible code'
cmd.handler = function (argv) {
let { join, log, process, __rootdirname, gherkinLinter } = dep
// Linters
const configPath = join(__rootdirname, '/lib/sdk/cucumber/gherkin-lint-rules.json')
const featureDirs = [join(process.cwd(), '/features/**/*.')]
log.log('Checking files:', featureDirs.toString())
if (gherkinLinter.run(configPath, featureDirs) !== 0) {
log.exit('There are errors to fix on the feature files')
} else {
log.log('All feature files look correct!')
}
}
return cmd
}
| 'use strict'
module.exports = function (dep) {
function validate () {
let {validation, help} = dep
if (!validation.isPatataRootDir()) {
help.errorDueRootPath()
}
}
let cmd = {}
cmd.command = 'lint'
cmd.desc = 'Run linters and fix possible code'
cmd.handler = function (argv) {
let { join, log, process, __rootdirname, gherkinLinter } = dep
validate()
// Linters
const configPath = join(__rootdirname, '/lib/sdk/cucumber/gherkin-lint-rules.json')
const featureDirs = [join(process.cwd(), '/features/**/*.')]
log.log('Checking files:', featureDirs.toString())
if (gherkinLinter.run(configPath, featureDirs) !== 0) {
log.exit('There are errors to fix on the feature files')
} else {
log.log('All feature files look correct!')
}
}
return cmd
}
| Fix bug checking root of project. | Linter: Fix bug checking root of project.
| JavaScript | mit | eridem/patata,appersonlabs/patata | ---
+++
@@ -1,11 +1,19 @@
'use strict'
module.exports = function (dep) {
+ function validate () {
+ let {validation, help} = dep
+ if (!validation.isPatataRootDir()) {
+ help.errorDueRootPath()
+ }
+ }
+
let cmd = {}
cmd.command = 'lint'
cmd.desc = 'Run linters and fix possible code'
cmd.handler = function (argv) {
let { join, log, process, __rootdirname, gherkinLinter } = dep
+ validate()
// Linters
const configPath = join(__rootdirname, '/lib/sdk/cucumber/gherkin-lint-rules.json') |
6578d26b06121f1e1e87fea267d1e6696b1ddb34 | js/scrollback.js | js/scrollback.js | document.addEventListener("wheel", function(e) {
if (e.shiftKey && e.deltaX != 0) {
window.history.go(-Math.sign(e.deltaX));
return e.preventDefault();
}
});
| document.addEventListener("wheel", function(e) {
if (e.shiftKey && (e.deltaX != 0 || e.deltaY != 0)) {
window.history.go(-Math.sign(e.deltaX ? e.deltaX : e.deltaY));
return e.preventDefault();
}
});
| Fix a problem of deltaX and deltaY | Fix a problem of deltaX and deltaY
Signed-off-by: Dongyun Jin <25d657a5cae33e06b1c3348113f358ba8b6c833f@gmail.com>
| JavaScript | mit | jezcope/chrome-scroll-back | ---
+++
@@ -1,6 +1,6 @@
document.addEventListener("wheel", function(e) {
- if (e.shiftKey && e.deltaX != 0) {
- window.history.go(-Math.sign(e.deltaX));
+ if (e.shiftKey && (e.deltaX != 0 || e.deltaY != 0)) {
+ window.history.go(-Math.sign(e.deltaX ? e.deltaX : e.deltaY));
return e.preventDefault();
}
}); |
70785353a9526b56a11f71df0f6f8d40591aeaa4 | api/controllers/requests.js | api/controllers/requests.js | var OwerRequestModel = require('../models/requests/owerRequest.js')
, error = require('../utils/error.js');
var allOwerRequests = function(req, res) {
var facebookId = req.user.facebookId
, type = req.query.type;
if (type) {
if (type === 'received') {
conditions.to = facebookId;
} else if (type === 'sent') {
conditions.from = facebookId;
} else {
return error.badRequest(res, 'Invalid parameter: type must be either "received" or "sent"');
}
}
OwerRequestModel.findAsync(conditions)
.then(function(owerRequests) {
res.json(owerRequests);
})
.catch(error.serverHandler(res));
};
exports.owers = {
all: allOwerRequests
};
| var OwerRequestModel = require('../models/requests/owerRequest.js')
, error = require('../utils/error.js');
var allOwerRequests = function(req, res) {
var type = req.query.type;
var facebookId;
if (req.user && req.user.facebookId) {
facebookId = req.user.facebookId;
}
if (type && facebookId) {
if (type === 'received') {
conditions.to = facebookId;
} else if (type === 'sent') {
conditions.from = facebookId;
} else {
return error.badRequest(res, 'Invalid parameter: type must be either "received" or "sent"');
}
}
OwerRequestModel.findAsync(conditions)
.then(function(owerRequests) {
res.json(owerRequests);
})
.catch(error.serverHandler(res));
};
exports.owers = {
all: allOwerRequests
};
| Fix admin not being able to access reqs | Fix admin not being able to access reqs
| JavaScript | mit | justinsacbibit/omi,justinsacbibit/omi,justinsacbibit/omi | ---
+++
@@ -2,10 +2,14 @@
, error = require('../utils/error.js');
var allOwerRequests = function(req, res) {
- var facebookId = req.user.facebookId
- , type = req.query.type;
+ var type = req.query.type;
+ var facebookId;
- if (type) {
+ if (req.user && req.user.facebookId) {
+ facebookId = req.user.facebookId;
+ }
+
+ if (type && facebookId) {
if (type === 'received') {
conditions.to = facebookId;
} else if (type === 'sent') { |
421f01a63ce4446abf5ce8927122fca20e7c6505 | app/adapters/application.js | app/adapters/application.js | import LFAdapter from 'ember-localforage-adapter/adapters/localforage';
export default LFAdapter.extend({
namespace: 'expenses',
caching: 'model'
});
| import LFAdapter from 'ember-localforage-adapter/adapters/localforage';
export default LFAdapter.extend({
namespace: 'api',
caching: 'model'
});
| Change adapter namespace to api | refactor: Change adapter namespace to api
| JavaScript | mit | pe1te3son/spendings-tracker,pe1te3son/spendings-tracker | ---
+++
@@ -1,6 +1,6 @@
import LFAdapter from 'ember-localforage-adapter/adapters/localforage';
export default LFAdapter.extend({
- namespace: 'expenses',
+ namespace: 'api',
caching: 'model'
}); |
347ec3d58a8d30303575d8ac7e5d6bf2ba47dfc6 | test/unit.js | test/unit.js | describe('skatejs-web-components', () => {
});
| import '../src/index';
describe('skatejs-web-components', () => {
it('should create a custom element with a shadow root', () => {
const Elem = class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
};
window.customElements.define('x-test', Elem);
const elem = new Elem();
expect(!!elem.shadowRoot).to.equal(true);
});
});
| Add test that ensures all V1 APIs exist when the library is imported. | test: Add test that ensures all V1 APIs exist when the library is imported.
| JavaScript | mit | skatejs/web-components | ---
+++
@@ -1,3 +1,15 @@
+import '../src/index';
+
describe('skatejs-web-components', () => {
-
+ it('should create a custom element with a shadow root', () => {
+ const Elem = class extends HTMLElement {
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+ }
+ };
+ window.customElements.define('x-test', Elem);
+ const elem = new Elem();
+ expect(!!elem.shadowRoot).to.equal(true);
+ });
}); |
86c36fd831a8cacd988ce1b56288200960dd84c1 | src/OData.js | src/OData.js | import React, { Component } from 'react';
import Fetch, { renderChildren } from 'react-fetch-component';
import buildQuery from 'odata-query';
function buildUrl(baseUrl, query) {
return query !== false && baseUrl + buildQuery(query);
}
class OData extends Component {
render() {
const { baseUrl, query, children, ...rest } = this.props;
const url = buildUrl(baseUrl, query);
return (
<Fetch url={url} {...rest}>
{({ fetch, ...props }) => {
return renderChildren(children, {
...props,
fetch: (query, options, updateOptions) =>
fetch(
buildUrl(baseUrl, query || this.props.query),
options || this.props.options,
updateOptions
)
});
}}
</Fetch>
);
}
}
export { buildQuery, renderChildren };
export default OData;
| import React, { Component } from 'react';
import Fetch, { renderChildren } from 'react-fetch-component';
import buildQuery from 'odata-query';
function buildUrl(baseUrl, query) {
return query !== false && baseUrl + buildQuery(query);
}
class OData extends Component {
render() {
const { baseUrl, query = {}, ...rest } = this.props;
return (
<Fetch
url={query}
fetchFunction={(query, options, updateOptions) => {
const url = buildUrl(baseUrl, query);
return fetch(url, options, updateOptions);
}}
{...rest}
/>
);
}
}
export { buildQuery, renderChildren };
export default OData;
| Use fetchFunction instead of currying functions | Use fetchFunction instead of currying functions
| JavaScript | mit | techniq/react-odata | ---
+++
@@ -8,23 +8,17 @@
class OData extends Component {
render() {
- const { baseUrl, query, children, ...rest } = this.props;
- const url = buildUrl(baseUrl, query);
+ const { baseUrl, query = {}, ...rest } = this.props;
return (
- <Fetch url={url} {...rest}>
- {({ fetch, ...props }) => {
- return renderChildren(children, {
- ...props,
- fetch: (query, options, updateOptions) =>
- fetch(
- buildUrl(baseUrl, query || this.props.query),
- options || this.props.options,
- updateOptions
- )
- });
+ <Fetch
+ url={query}
+ fetchFunction={(query, options, updateOptions) => {
+ const url = buildUrl(baseUrl, query);
+ return fetch(url, options, updateOptions);
}}
- </Fetch>
+ {...rest}
+ />
);
}
} |
29c1630e2c6597bd5ab9e923ffb0e091f0934bb8 | test/bitgo.js | test/bitgo.js | //
// Tests for BitGo Object
//
// Copyright 2014, BitGo, Inc. All Rights Reserved.
//
var assert = require('assert');
var should = require('should');
var BitGoJS = require('../src/index');
describe('BitGo', function() {
describe('methods', function() {
it('includes version', function() {
var bitgo = new BitGoJS.BitGo();
bitgo.should.have.property('version');
var version = bitgo.version();
assert.equal(typeof(version), 'string');
});
it('includes market', function(done) {
var bitgo = new BitGoJS.BitGo();
bitgo.should.have.property('market');
bitgo.market(function(marketData) {
marketData.should.have.property('last');
marketData.should.have.property('bid');
marketData.should.have.property('ask');
marketData.should.have.property('volume');
marketData.should.have.property('high');
marketData.should.have.property('low');
done();
});
});
});
});
| //
// Tests for BitGo Object
//
// Copyright 2014, BitGo, Inc. All Rights Reserved.
//
var assert = require('assert');
var should = require('should');
var BitGoJS = require('../src/index');
describe('BitGo', function() {
describe('methods', function() {
it('includes version', function() {
var bitgo = new BitGoJS.BitGo();
bitgo.should.have.property('version');
var version = bitgo.version();
assert.equal(typeof(version), 'string');
});
it('includes market', function(done) {
var bitgo = new BitGoJS.BitGo();
bitgo.should.have.property('market');
bitgo.market(function(marketData) {
marketData.should.have.property('last');
marketData.should.have.property('bid');
marketData.should.have.property('ask');
marketData.should.have.property('volume');
marketData.should.have.property('high');
marketData.should.have.property('low');
marketData.should.have.property('updateTime');
done();
});
});
});
});
| Add updateTime check to test. | Add updateTime check to test.
| JavaScript | apache-2.0 | BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS,BitGo/BitGoJS | ---
+++
@@ -29,6 +29,7 @@
marketData.should.have.property('volume');
marketData.should.have.property('high');
marketData.should.have.property('low');
+ marketData.should.have.property('updateTime');
done();
});
}); |
1eaf541f9c88d135ddb5bf6828937a4e6505f688 | test/index.js | test/index.js | 'use strict';
/* global describe it */
var assert = require('assert');
var flattenObjectStrict = require('../lib');
describe('flatten-object-strict', function() {
it('an empty object produces an empty object', function() {
assert.deepEqual(flattenObjectStrict({}), {});
});
});
| 'use strict';
/* global describe it */
var assert = require('assert');
var flattenObjectStrict = require('../lib');
describe('flatten-object-strict', function() {
it('an empty object produces an empty object', function() {
assert.deepEqual(flattenObjectStrict({}), {});
});
it('a object that\'s already flat doesn\'t change', function() {
[
{ a: 'a', b: [1, 2, 3], c: function() {} },
{ foo: 'bar', baz: 'boom' },
{ one: 'one', two: 'two', three: 'three', four: 'four', five: 'five' }
].forEach(function(flatObject) {
assert.deepEqual(flattenObjectStrict(flatObject), flatObject);
});
});
});
| Add test for flat objects | Add test for flat objects
| JavaScript | mit | voltrevo/flatten-object-strict | ---
+++
@@ -10,4 +10,14 @@
it('an empty object produces an empty object', function() {
assert.deepEqual(flattenObjectStrict({}), {});
});
+
+ it('a object that\'s already flat doesn\'t change', function() {
+ [
+ { a: 'a', b: [1, 2, 3], c: function() {} },
+ { foo: 'bar', baz: 'boom' },
+ { one: 'one', two: 'two', three: 'three', four: 'four', five: 'five' }
+ ].forEach(function(flatObject) {
+ assert.deepEqual(flattenObjectStrict(flatObject), flatObject);
+ });
+ });
}); |
5fe20444cef17cd889803ecbcb3a7c96b47c47e3 | lib/assets/javascripts/cartodb/new_dashboard/entry.js | lib/assets/javascripts/cartodb/new_dashboard/entry.js | var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');
/**
* The Holy Dashboard
*/
$(function() {
cdb.init(function() {
cdb.templates.namespace = 'cartodb/';
cdb.config.set(config); // import config
if (cdb.config.isOrganizationUrl()) {
cdb.config.set('url_prefix', cdb.config.organizationUrl());
}
var router = new Router();
// Mixpanel test
if (window.mixpanel) {
new cdb.common.Mixpanel({
user: user_data,
token: mixpanel_token
});
}
// Store JS errors
new cdb.admin.ErrorStats({ user_data: user_data });
// Main view
var dashboard = new MainView({
el: document.body,
user_data: user_data,
upgrade_url: upgrade_url,
config: config,
router: router
});
window.dashboard = dashboard;
// History
Backbone.history.start({
pushState: true,
root: cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
});
});
});
| var Router = require('new_dashboard/router');
var $ = require('jquery');
var cdb = require('cartodb.js');
var MainView = require('new_dashboard/main_view');
/**
* The Holy Dashboard
*/
$(function() {
cdb.init(function() {
cdb.templates.namespace = 'cartodb/';
cdb.config.set(window.config); // import config
if (cdb.config.isOrganizationUrl()) {
cdb.config.set('url_prefix', cdb.config.organizationUrl());
}
var router = new Router();
// Mixpanel test
if (window.mixpanel) {
new cdb.common.Mixpanel({
user: user_data,
token: mixpanel_token
});
}
// Store JS errors
new cdb.admin.ErrorStats({ user_data: user_data });
// Main view
var dashboard = new MainView({
el: document.body,
user_data: user_data,
upgrade_url: upgrade_url,
config: config,
router: router
});
window.dashboard = dashboard;
// History
Backbone.history.start({
pushState: true,
root: cdb.config.prefixUrl() + '/' //cdb.config.prefixUrl() + '/dashboard/'
});
});
});
| Make the config dependency's origin | Make the config dependency's origin
Set in global namespace from a script tag rendered by Rails app
| JavaScript | bsd-3-clause | splashblot/dronedb,codeandtheory/cartodb,splashblot/dronedb,dbirchak/cartodb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,raquel-ucl/cartodb,CartoDB/cartodb,thorncp/cartodb,nuxcode/cartodb,splashblot/dronedb,dbirchak/cartodb,bloomberg/cartodb,splashblot/dronedb,nuxcode/cartodb,UCL-ShippingGroup/cartodb-1,nyimbi/cartodb,future-analytics/cartodb,nyimbi/cartodb,thorncp/cartodb,future-analytics/cartodb,nuxcode/cartodb,CartoDB/cartodb,bloomberg/cartodb,DigitalCoder/cartodb,thorncp/cartodb,CartoDB/cartodb,codeandtheory/cartodb,nyimbi/cartodb,DigitalCoder/cartodb,future-analytics/cartodb,UCL-ShippingGroup/cartodb-1,splashblot/dronedb,nyimbi/cartodb,UCL-ShippingGroup/cartodb-1,UCL-ShippingGroup/cartodb-1,future-analytics/cartodb,codeandtheory/cartodb,thorncp/cartodb,DigitalCoder/cartodb,dbirchak/cartodb,thorncp/cartodb,DigitalCoder/cartodb,DigitalCoder/cartodb,bloomberg/cartodb,bloomberg/cartodb,CartoDB/cartodb,raquel-ucl/cartodb,future-analytics/cartodb,dbirchak/cartodb,codeandtheory/cartodb,dbirchak/cartodb,nyimbi/cartodb,nuxcode/cartodb,raquel-ucl/cartodb,CartoDB/cartodb,raquel-ucl/cartodb,codeandtheory/cartodb,bloomberg/cartodb,raquel-ucl/cartodb | ---
+++
@@ -11,7 +11,7 @@
cdb.init(function() {
cdb.templates.namespace = 'cartodb/';
- cdb.config.set(config); // import config
+ cdb.config.set(window.config); // import config
if (cdb.config.isOrganizationUrl()) {
cdb.config.set('url_prefix', cdb.config.organizationUrl());
} |
df8210287256f88244996a4a905c3be2197829bf | aura-impl/src/main/resources/aura/model/Model.js | aura-impl/src/main/resources/aura/model/Model.js | /*
* Copyright (C) 2012 salesforce.com, 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.
*/
/*jslint sub: true */
/**
* @namespace Creates a Model instance.
* @constructor
* @param {Object} def
* @param {Object} data
* @param {Component} component
* @returns {Function}
*/
function Model(def, data, component){
/** BEGIN HACK--MUST BE REMOVED **/
if (def.getDescriptor().getQualifiedName() === "java://ui.aura.components.forceProto.FilterListModel") {
for (var i in data["rowTemplate"]) {
data["rowTemplate"][i] = new SimpleValue(data["rowTemplate"][i], def, component);
}
}
if (def.getDescriptor().getQualifiedName() === "java://org.auraframework.component.ui.DataTableModel") {
for (var j in data["itemTemplate"]) {
data["itemTemplate"][j] = new SimpleValue(data["itemTemplate"][j], def, component);
}
}
/** END HACK**/
return new MapValue(data, def, component);
}
| /*
* Copyright (C) 2012 salesforce.com, 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.
*/
/*jslint sub: true */
/**
* @namespace Creates a Model instance.
* @constructor
* @param {Object} def
* @param {Object} data
* @param {Component} component
* @returns {Function}
*/
function Model(def, data, component){
return new MapValue(data, def, component);
}
| Remove model hack--no longer needed for lists | Remove model hack--no longer needed for lists
| JavaScript | apache-2.0 | lhong375/aura,badlogicmanpreet/aura,DebalinaDey/AuraDevelopDeb,navyliu/aura,madmax983/aura,forcedotcom/aura,lhong375/aura,forcedotcom/aura,TribeMedia/aura,DebalinaDey/AuraDevelopDeb,badlogicmanpreet/aura,TribeMedia/aura,igor-sfdc/aura,DebalinaDey/AuraDevelopDeb,TribeMedia/aura,lcnbala/aura,SalesforceSFDC/aura,madmax983/aura,SalesforceSFDC/aura,badlogicmanpreet/aura,madmax983/aura,DebalinaDey/AuraDevelopDeb,madmax983/aura,SalesforceSFDC/aura,igor-sfdc/aura,SalesforceSFDC/aura,badlogicmanpreet/aura,igor-sfdc/aura,TribeMedia/aura,forcedotcom/aura,badlogicmanpreet/aura,navyliu/aura,madmax983/aura,navyliu/aura,lhong375/aura,navyliu/aura,lcnbala/aura,DebalinaDey/AuraDevelopDeb,igor-sfdc/aura,lcnbala/aura,SalesforceSFDC/aura,forcedotcom/aura,badlogicmanpreet/aura,navyliu/aura,DebalinaDey/AuraDevelopDeb,SalesforceSFDC/aura,madmax983/aura,lcnbala/aura,TribeMedia/aura,lcnbala/aura,navyliu/aura,TribeMedia/aura,lcnbala/aura,igor-sfdc/aura,lhong375/aura,forcedotcom/aura | ---
+++
@@ -23,22 +23,5 @@
* @returns {Function}
*/
function Model(def, data, component){
-
- /** BEGIN HACK--MUST BE REMOVED **/
- if (def.getDescriptor().getQualifiedName() === "java://ui.aura.components.forceProto.FilterListModel") {
-
- for (var i in data["rowTemplate"]) {
- data["rowTemplate"][i] = new SimpleValue(data["rowTemplate"][i], def, component);
- }
-
- }
-
- if (def.getDescriptor().getQualifiedName() === "java://org.auraframework.component.ui.DataTableModel") {
- for (var j in data["itemTemplate"]) {
- data["itemTemplate"][j] = new SimpleValue(data["itemTemplate"][j], def, component);
- }
- }
- /** END HACK**/
-
return new MapValue(data, def, component);
} |
a864bc226ec204bc2083e2abd98a4493afa2da04 | karma.component.config.js | karma.component.config.js | module.exports = function(config) {
config.set({
basePath: process.env['INIT_CWD'],
frameworks: ['mocha', 'chai', 'karma-typescript', 'sinon'],
browsers: ['ChromeHeadless', 'FirefoxHeadless'],
files: [
'./node_modules/@webcomponents/webcomponentsjs/webcomponents-sd-ce.js',
{ pattern: 'dist/*.bundled.js' },
{ pattern: 'test/*.test.ts' },
{ pattern: 'test/**/*.json', watched: true, served: true, included: false },
],
reporters: ['progress', 'karma-typescript'],
singleRun: true,
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
concurrency: Infinity,
preprocessors: {
'**/*.ts': ['karma-typescript'],
},
karmaTypescriptConfig: {
compilerOptions: {
target: 'es2015',
},
bundlerOptions: {
transforms: [require('karma-typescript-es6-transform')({ presets: 'env' })],
},
},
});
}
| module.exports = function(config) {
config.set({
basePath: process.env['INIT_CWD'],
frameworks: ['mocha', 'chai', 'karma-typescript', 'sinon'],
browsers: ['ChromeHeadless'],
files: [
'./node_modules/@webcomponents/webcomponentsjs/webcomponents-sd-ce.js',
{ pattern: 'dist/*.bundled.js' },
{ pattern: 'test/*.test.ts' },
{ pattern: 'test/**/*.json', watched: true, served: true, included: false },
],
reporters: ['progress', 'karma-typescript'],
singleRun: true,
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
concurrency: Infinity,
preprocessors: {
'**/*.ts': ['karma-typescript'],
},
karmaTypescriptConfig: {
compilerOptions: {
target: 'es2015',
},
bundlerOptions: {
transforms: [require('karma-typescript-es6-transform')({ presets: 'env' })],
},
},
});
}
| Disable Firefox until their ShadowDOM is in place | Disable Firefox until their ShadowDOM is in place
| JavaScript | mit | abraham/nutmeg-cli,abraham/nutmeg-cli,abraham/nutmeg-cli | ---
+++
@@ -2,7 +2,7 @@
config.set({
basePath: process.env['INIT_CWD'],
frameworks: ['mocha', 'chai', 'karma-typescript', 'sinon'],
- browsers: ['ChromeHeadless', 'FirefoxHeadless'],
+ browsers: ['ChromeHeadless'],
files: [
'./node_modules/@webcomponents/webcomponentsjs/webcomponents-sd-ce.js',
{ pattern: 'dist/*.bundled.js' }, |
d48b188b3ebe03ccbe9dfd57bb267261de962178 | samples/VanillaJSTestApp2.0/app/b2c/authConfig.js | samples/VanillaJSTestApp2.0/app/b2c/authConfig.js | // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "e3b9ad76-9763-4827-b088-80c7a7888f79",
authority: "https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_SISOPolicy/",
knownAuthorities: ["login.microsoftonline.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
telemetry: {
applicationName: 'msalVanillaTestApp',
applicationVersion: 'test1.0',
telemetryEmitter: (events) => {
console.log("Telemetry Events", events);
}
}
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}; | // Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "e3b9ad76-9763-4827-b088-80c7a7888f79",
authority: "https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_SISOPolicy/",
knownAuthorities: ["login.microsoftonline.com"]
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
// Add here scopes for id token to be used at MS Identity Platform endpoints.
const loginRequest = {
scopes: ["https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read"],
forceRefresh: false // Set this to "true" to skip a cached token and go to the server to get a new token
}; | Remove telemetry config from 2.0 sample | Remove telemetry config from 2.0 sample
| JavaScript | mit | AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js,AzureAD/microsoft-authentication-library-for-js | ---
+++
@@ -8,15 +8,6 @@
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
- },
- system: {
- telemetry: {
- applicationName: 'msalVanillaTestApp',
- applicationVersion: 'test1.0',
- telemetryEmitter: (events) => {
- console.log("Telemetry Events", events);
- }
- }
}
};
|
5ea58b636d98ef0bb9294c241ee588d2a065c551 | scripts/postinstall.js | scripts/postinstall.js | require("es6-shim");
var exec = require("child_process").exec;
var os = require("os");
var useMraa = (function() {
var release = os.release();
return release.includes("yocto") ||
release.includes("edison");
})();
if (useMraa) {
exec("npm install mraa@0.6.1-36-gbe4312e");
}
| require("es6-shim");
var exec = require("child_process").exec;
var os = require("os");
var useMraa = (function() {
var release = os.release();
return release.includes("yocto") ||
release.includes("edison");
})();
var safeBuild = "0.6.1+git0+805d22f0b1-r0";
var safeVersion = "0.6.1-36-gbe4312e";
if (useMraa) {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(" Do not quit the program until npm completes the installation process. ");
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
exec("opkg info libmraa0", function(error, stdout, stderr) {
if (!stdout.includes(safeBuild)) {
console.log("");
console.log(" Galileo-IO needs to install a trusted version of libmraa0.");
console.log(" This process takes approximately one minute.");
console.log(" Thanks for your patience.");
exec("npm install mraa@" + safeVersion, function() {
console.log(" Completed!");
console.log("");
});
}
});
}
| Check for safe version of libmraa0 before installing own copy. | Check for safe version of libmraa0 before installing own copy.
- Displays information during postinstall to help user understand the process
| JavaScript | mit | ashishdatta/galileo-io,kimathijs/galileo-io,julianduque/galileo-io,vj-ug/galileo-io,rwaldron/galileo-io | ---
+++
@@ -8,6 +8,25 @@
release.includes("edison");
})();
+var safeBuild = "0.6.1+git0+805d22f0b1-r0";
+var safeVersion = "0.6.1-36-gbe4312e";
+
if (useMraa) {
- exec("npm install mraa@0.6.1-36-gbe4312e");
+ console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+ console.log(" Do not quit the program until npm completes the installation process. ");
+ console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+
+ exec("opkg info libmraa0", function(error, stdout, stderr) {
+ if (!stdout.includes(safeBuild)) {
+ console.log("");
+ console.log(" Galileo-IO needs to install a trusted version of libmraa0.");
+ console.log(" This process takes approximately one minute.");
+ console.log(" Thanks for your patience.");
+
+ exec("npm install mraa@" + safeVersion, function() {
+ console.log(" Completed!");
+ console.log("");
+ });
+ }
+ });
} |
c6a12035debea100fcce7e2078a5ecd7be95a974 | tests/test_middleware.js | tests/test_middleware.js | var async = require('async');
var request = require('request');
var sugar = require('object-sugar');
var rest = require('../lib/rest-sugar');
var serve = require('./serve');
var conf = require('./conf');
var models = require('./models');
var utils = require('./utils');
var queries = require('./queries');
function tests(done) {
var port = conf.port + 1;
var resource = conf.host + ':' + port + conf.prefix + 'authors';
var app = serve(conf);
var api = rest.init(app, conf.prefix, {
authors: models.Author
}, sugar);
api.pre(function() {
api.use(rest.only('GET'));
api.use(function(req, res, next) {
next();
});
});
api.post(function() {
api.use(function(data, next) {
next();
});
});
// TODO: figure out how to spawn servers and close them. alternatively
// move this handling to higher level
app.listen(port, function(err) {
if(err) return console.error(err);
utils.runTests([
queries.get(resource),
queries.create(resource, utils.forbidden),
queries.createViaGet(resource, utils.forbidden)
], done);
});
}
module.exports = tests;
| var assert = require('assert');
var async = require('async');
var request = require('request');
var sugar = require('object-sugar');
var rest = require('../lib/rest-sugar');
var serve = require('./serve');
var conf = require('./conf');
var models = require('./models');
var utils = require('./utils');
var queries = require('./queries');
function tests(done) {
var port = conf.port + 1;
var resource = conf.host + ':' + port + conf.prefix + 'authors';
var app = serve(conf);
var api = rest.init(app, conf.prefix, {
authors: models.Author
}, sugar);
var preTriggered, postTriggered;
api.pre(function() {
api.use(rest.only('GET'));
api.use(function(req, res, next) {
preTriggered = true;
next();
});
});
api.post(function() {
api.use(function(data, next) {
postTriggered = true;
next();
});
});
// TODO: figure out how to spawn servers and close them. alternatively
// move this handling to higher level
app.listen(port, function(err) {
if(err) return console.error(err);
utils.runTests([
queries.get(resource),
queries.create(resource, utils.forbidden),
queries.createViaGet(resource, utils.forbidden)
], function() {
assert.ok(preTriggered);
assert.ok(postTriggered);
done();
});
});
}
module.exports = tests;
| Check that middlewares get triggered properly | Check that middlewares get triggered properly
| JavaScript | mit | sugarjs/rest-sugar | ---
+++
@@ -1,3 +1,5 @@
+var assert = require('assert');
+
var async = require('async');
var request = require('request');
var sugar = require('object-sugar');
@@ -17,16 +19,21 @@
var api = rest.init(app, conf.prefix, {
authors: models.Author
}, sugar);
+ var preTriggered, postTriggered;
api.pre(function() {
api.use(rest.only('GET'));
api.use(function(req, res, next) {
+ preTriggered = true;
+
next();
});
});
api.post(function() {
api.use(function(data, next) {
+ postTriggered = true;
+
next();
});
});
@@ -40,7 +47,12 @@
queries.get(resource),
queries.create(resource, utils.forbidden),
queries.createViaGet(resource, utils.forbidden)
- ], done);
+ ], function() {
+ assert.ok(preTriggered);
+ assert.ok(postTriggered);
+
+ done();
+ });
});
}
module.exports = tests; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.