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 |
|---|---|---|---|---|---|---|---|---|---|---|
2a146bcf5e104d9d35874858380c5ae29cfcd845 | business-processes/index.js | business-processes/index.js | // Collection of all business processes which where made online
'use strict';
module.exports = require('./resolve')(require('../db').BusinessProcess);
| // Collection of all business processes which where made online
'use strict';
var isFalsy = require('../utils/is-falsy');
module.exports = require('../db').BusinessProcess.instances
.filter(function (obj) {
if (obj.master !== obj) return false;
return (obj.constructor.prototype !== obj);
})
.filterByKey('isFromEregistrations', true)
.filterByKey('isDemo', isFalsy);
| Update up to changes in resolver | Update up to changes in resolver
| JavaScript | mit | egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations | ---
+++
@@ -2,4 +2,12 @@
'use strict';
-module.exports = require('./resolve')(require('../db').BusinessProcess);
+var isFalsy = require('../utils/is-falsy');
+
+module.exports = require('../db').BusinessProcess.instances
+ .filter(function (obj) {
+ if (obj.master !== obj) return false;
+ return (obj.constructor.prototype !== obj);
+ })
+ .filterByKey('isFromEregistrations', true)
+ .filterByKey('isDemo', isFalsy); |
e6080452d70ad2b16ab3fac3a93f1816549b57c1 | test/featherlight_test.js | test/featherlight_test.js | if(!this.chai) { chai = require("chai"); }
var expect = chai.expect;
(function($) {
var cleanupDom = function(){
$('body >:not(#mocha)').remove()
};
describe('Featherlight', function() {
afterEach(cleanupDom);
it ('works on items with data-featherlight by default', function(done) {
var $bound = $('#auto-bound')
expect($('img').length).to.equal(0);
$bound.click();
setTimeout(function() {
expect($('.featherlight img')).to.be.visible;
expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg');
$('.featherlight').click();
}, 500 );
setTimeout(function() {
expect($('img')).to.not.be.visible;
done();
}, 1000 );
});
describe('jQuery#featherlight', function() {
it('is chainable', function() {
// Not a bad test to run on collection methods.
var $all_links = $('a')
expect($all_links.featherlight()).to.equal($all_links);
});
});
describe('jQuery.featherlight', function() {
it('opens a dialog box', function() {
$.featherlight('<p class="testing">This is a test<p>');
expect($('.featherlight p.testing')).to.be.visible;
});
});
});
}(jQuery));
| if(!this.chai) { chai = require("chai"); }
var expect = chai.expect;
(function($) {
var cleanupDom = function(){
$('body >:not(#mocha)').remove()
};
$.fx.off = true;
describe('Featherlight', function() {
afterEach(cleanupDom);
it ('works on items with data-featherlight by default', function() {
var $bound = $('#auto-bound')
expect($('img').length).to.equal(0);
$bound.click();
expect($('.featherlight img')).to.be.visible;
expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg');
$('.featherlight').click();
expect($('img')).to.not.be.visible;
});
describe('jQuery#featherlight', function() {
it('is chainable', function() {
// Not a bad test to run on collection methods.
var $all_links = $('a')
expect($all_links.featherlight()).to.equal($all_links);
});
});
describe('jQuery.featherlight', function() {
it('opens a dialog box', function() {
$.featherlight('<p class="testing">This is a test<p>');
expect($('.featherlight p.testing')).to.be.visible;
});
});
});
}(jQuery));
| Simplify tests by turning off effects | Simplify tests by turning off effects
| JavaScript | mit | xStrom/featherlight,danielchikaka/featherlight,noelboss/featherlight,noelboss/featherlight,danielchikaka/featherlight,getprodigy/featherlight,xStrom/featherlight,hnkent/featherlight,minervaproject/featherlight,beeseenmedia/featherlight,n7best/featherlight,n7best/featherlight,minervaproject/featherlight,hnkent/featherlight,beeseenmedia/featherlight,getprodigy/featherlight,shannonshsu/featherlight,shannonshsu/featherlight | ---
+++
@@ -5,23 +5,18 @@
var cleanupDom = function(){
$('body >:not(#mocha)').remove()
};
-
+ $.fx.off = true;
describe('Featherlight', function() {
afterEach(cleanupDom);
- it ('works on items with data-featherlight by default', function(done) {
+ it ('works on items with data-featherlight by default', function() {
var $bound = $('#auto-bound')
expect($('img').length).to.equal(0);
$bound.click();
- setTimeout(function() {
- expect($('.featherlight img')).to.be.visible;
- expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg');
- $('.featherlight').click();
- }, 500 );
- setTimeout(function() {
- expect($('img')).to.not.be.visible;
- done();
- }, 1000 );
+ expect($('.featherlight img')).to.be.visible;
+ expect($('.featherlight img')).to.have.attr('src').equal('fixtures/photo.jpeg');
+ $('.featherlight').click();
+ expect($('img')).to.not.be.visible;
});
describe('jQuery#featherlight', function() { |
f77d3a06aa7fe7413296f91c7c6ae82c74b4c807 | src/constants/actionTypes.js | src/constants/actionTypes.js | import constanst from 'flux-constants'
export default constants([
'ON_CLICK_MENU_BUTTON',
'POSTS_REQUEST',
'POSTS_SUCCESS',
'POSTS_FAILURE',
]) | Create action types for Redux | Create action types for Redux
| JavaScript | mit | nomkhonwaan/nomkhonwaan.github.io | ---
+++
@@ -0,0 +1,11 @@
+import constanst from 'flux-constants'
+
+export default constants([
+
+ 'ON_CLICK_MENU_BUTTON',
+
+ 'POSTS_REQUEST',
+ 'POSTS_SUCCESS',
+ 'POSTS_FAILURE',
+
+]) | |
0f309adcd9742f4d2a7c4f85cdaf852f19552436 | test/onPort.test.js | test/onPort.test.js | 'use strict'
const t = require('tap')
const spawn = require('child_process').spawn
const split = require('split2')
const autocannon = require.resolve('../autocannon')
const target = require.resolve('./targetProcess')
const lines = [
/Running 1s test @ .*$/,
/10 connections.*$/,
/$/,
/Stat.*Avg.*Stdev.*Max.*$/,
/Latency \(ms\).*$/,
/Req\/Sec.*$/,
/Bytes\/Sec.*$/,
/$/,
// Ensure that there are more than 0 successful requests
/[1-9]\d+.* requests in \d+s, .* read/
]
t.plan(lines.length * 2)
const child = spawn(autocannon, [
'-c', '10',
'-d', '1',
'--on-port', '/',
'--', 'node', target
], {
cwd: __dirname,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false
})
t.tearDown(() => {
child.kill()
})
child
.stderr
.pipe(split())
.on('data', (line) => {
const regexp = lines.shift()
t.ok(regexp, 'we are expecting this line')
console.error(line)
t.ok(regexp.test(line), 'line matches ' + regexp)
})
| 'use strict'
const t = require('tap')
const spawn = require('child_process').spawn
const split = require('split2')
const autocannon = require.resolve('../autocannon')
const target = require.resolve('./targetProcess')
const lines = [
/Running 1s test @ .*$/,
/10 connections.*$/,
/$/,
/Stat.*Avg.*Stdev.*Max.*$/,
/Latency \(ms\).*$/,
/Req\/Sec.*$/,
/Bytes\/Sec.*$/,
/$/,
// Ensure that there are more than 0 successful requests
/[1-9]\d+.* requests in \d+s, .* read/
]
t.plan(lines.length * 2)
const child = spawn(autocannon, [
'-c', '10',
'-d', '1',
'--on-port', '/',
'--', 'node', target
], {
cwd: __dirname,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false
})
t.tearDown(() => {
child.kill()
})
child
.stderr
.pipe(split())
.on('data', (line) => {
const regexp = lines.shift()
t.ok(regexp, 'we are expecting this line')
t.ok(regexp.test(line), 'line matches ' + regexp)
})
| Revert "add debug line for travis bc this is passing locally" | Revert "add debug line for travis bc this is passing locally"
This reverts commit c930369362fa9c68e8f44296617695fc804e141d.
| JavaScript | mit | mcollina/autocannon | ---
+++
@@ -43,6 +43,5 @@
.on('data', (line) => {
const regexp = lines.shift()
t.ok(regexp, 'we are expecting this line')
- console.error(line)
t.ok(regexp.test(line), 'line matches ' + regexp)
}) |
1dec88178c4a0c939cd21045d3584a9429d702bf | app/main/plugins/hain-plugin-math/index.js | app/main/plugins/hain-plugin-math/index.js | 'use strict';
const lo_isNumber = require('lodash.isnumber');
const lo_isString = require('lodash.isstring');
const lo_isObject = require('lodash.isobject');
const lo_has = require('lodash.has');
const math = require('mathjs');
module.exports = ({ app }) => {
function search(query, res) {
try {
const ans = math.eval(query);
if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
res.add({
title: `${query.trim()} = ${ans.toString()}`,
group: 'Math',
payload: ans.toString()
});
}
} catch (e) {
}
}
function execute(id, payload) {
app.setInput(`=${payload}`);
}
return { search, execute };
};
| 'use strict';
const lo_isNumber = require('lodash.isnumber');
const lo_isString = require('lodash.isstring');
const lo_isObject = require('lodash.isobject');
const lo_has = require('lodash.has');
const math = require('mathjs');
module.exports = (context) => {
const app = context.app;
const clipboard = context.clipboard;
const toast = context.toast;
function search(query, res) {
try {
const ans = math.eval(query);
if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
res.add({
title: `${query.trim()} = ${ans.toString()}`,
group: 'Math',
payload: ans.toString()
});
}
} catch (e) {
}
}
function execute(id, payload) {
app.setQuery(`=${payload}`);
clipboard.writeText(payload);
toast.enqueue(`${payload} has copied into clipboard`);
}
return { search, execute };
};
| Copy result into clipboard on execute equation | hain-plugin-math: Copy result into clipboard on execute equation
| JavaScript | mit | appetizermonster/hain,hainproject/hain,hainproject/hain,hainproject/hain,appetizermonster/hain,hainproject/hain,appetizermonster/hain,appetizermonster/hain | ---
+++
@@ -7,7 +7,10 @@
const math = require('mathjs');
-module.exports = ({ app }) => {
+module.exports = (context) => {
+ const app = context.app;
+ const clipboard = context.clipboard;
+ const toast = context.toast;
function search(query, res) {
try {
@@ -24,7 +27,9 @@
}
function execute(id, payload) {
- app.setInput(`=${payload}`);
+ app.setQuery(`=${payload}`);
+ clipboard.writeText(payload);
+ toast.enqueue(`${payload} has copied into clipboard`);
}
return { search, execute }; |
6d505a32934e0cadf929accb8cebfce40ef63b68 | test/stories/frontPage.js | test/stories/frontPage.js | var basePage = require('../pages/Base');
describe('Main page', function() {
basePage.go();
it('should be at the correct URL', function() {
expect(basePage.currentUrl).toEqual(browser.baseUrl + basePage.url);
});
});
| var basePage = require('../pages/Base');
var expect = require('./setupExpect').expect;
describe('Main page', function() {
basePage.go();
it('should be at the correct URL', function() {
expect(basePage.currentUrl).to.eventually.equal(browser.baseUrl + basePage.url);
});
});
| Use mocha in spec files. | Use mocha in spec files.
| JavaScript | mit | Droogans/ProtractorPageObjects | ---
+++
@@ -1,11 +1,12 @@
var basePage = require('../pages/Base');
+var expect = require('./setupExpect').expect;
describe('Main page', function() {
basePage.go();
it('should be at the correct URL', function() {
- expect(basePage.currentUrl).toEqual(browser.baseUrl + basePage.url);
+ expect(basePage.currentUrl).to.eventually.equal(browser.baseUrl + basePage.url);
});
}); |
8048e4007edd44d2299945fc4802a7cb525bf053 | app/javascript/packs/components/dashboard/Header.js | app/javascript/packs/components/dashboard/Header.js | import React from 'react';
import styles from './Header.sass';
import classNames from 'classnames';
import { Link } from 'react-router-dom';
export default function Head() {
const button = classNames('waves-effect', 'waves-light', 'btn', styles.button);
return (
<div className={styles.container}>
<div className={styles.logoWrapper}>
<img src="icon_blue_transport.png" />
</div>
<p className={styles.bigTitle}>薫陶 - Kunto -</p>
<p className={styles.description}>ダイエットに挫折したあなた</p>
<p className={styles.description}>筋トレが継続できないあなた</p>
<p className={styles.description}>運動不足のあなた</p>
<p className={styles.subTitle}>
薫陶で筋トレを始めませんか?
</p>
<div className={styles.buttonGroup}>
<Link
to="signup"
className={button}
>
新規登録して薫陶をはじめる
</Link>
<Link
to="login"
className={button}
>
ログインはこちら
</Link>
</div>
</div>
);
}
| import { isEmpty } from 'lodash';
import React from 'react';
import classNames from 'classnames';
import { Link } from 'react-router-dom';
import styles from './Header.sass';
import User from '../../models/user';
export default function Head() {
const button = classNames('waves-effect', 'waves-light', 'btn', styles.button);
const isAuthenticated = !isEmpty(User.currentUserToken());
return (
<div className={styles.container}>
<div className={styles.logoWrapper}>
<img src="icon_blue_transport.png" />
</div>
<p className={styles.bigTitle}>薫陶 - Kunto -</p>
<p className={styles.description}>ダイエットに挫折したあなた</p>
<p className={styles.description}>筋トレが継続できないあなた</p>
<p className={styles.description}>運動不足のあなた</p>
<p className={styles.subTitle}>
薫陶で筋トレを始めませんか?
</p>
{
(() => {
if (isAuthenticated) {
const primaryButton = classNames(button, 'teal', 'darken-1');
return (
<div className={styles.buttonGroup}>
<Link
to="my"
className={primaryButton}
>
マイページに行く
</Link>
</div>
);
}
return (
<div className={styles.buttonGroup}>
<Link
to="signup"
className={button}
>
新規登録して薫陶をはじめる
</Link>
<Link
to="login"
className={button}
>
ログインはこちら
</Link>
</div>
);
})()
}
</div>
);
}
| Hide links for sign in and sign up if already exists user token. | Hide links for sign in and sign up if already exists user token.
| JavaScript | agpl-3.0 | GuHoo/Kunto-Backend,GuHoo/Kunto-Backend,GuHoo/Kunto-Backend | ---
+++
@@ -1,10 +1,13 @@
+import { isEmpty } from 'lodash';
import React from 'react';
-import styles from './Header.sass';
import classNames from 'classnames';
import { Link } from 'react-router-dom';
+import styles from './Header.sass';
+import User from '../../models/user';
export default function Head() {
const button = classNames('waves-effect', 'waves-light', 'btn', styles.button);
+ const isAuthenticated = !isEmpty(User.currentUserToken());
return (
<div className={styles.container}>
<div className={styles.logoWrapper}>
@@ -17,20 +20,39 @@
<p className={styles.subTitle}>
薫陶で筋トレを始めませんか?
</p>
- <div className={styles.buttonGroup}>
- <Link
- to="signup"
- className={button}
- >
- 新規登録して薫陶をはじめる
- </Link>
- <Link
- to="login"
- className={button}
- >
- ログインはこちら
- </Link>
- </div>
+ {
+ (() => {
+ if (isAuthenticated) {
+ const primaryButton = classNames(button, 'teal', 'darken-1');
+ return (
+ <div className={styles.buttonGroup}>
+ <Link
+ to="my"
+ className={primaryButton}
+ >
+ マイページに行く
+ </Link>
+ </div>
+ );
+ }
+ return (
+ <div className={styles.buttonGroup}>
+ <Link
+ to="signup"
+ className={button}
+ >
+ 新規登録して薫陶をはじめる
+ </Link>
+ <Link
+ to="login"
+ className={button}
+ >
+ ログインはこちら
+ </Link>
+ </div>
+ );
+ })()
+ }
</div>
);
} |
a72de95ffbd59cc74a6dd9607f28a8ec04b3315f | src/encoded/static/server.js | src/encoded/static/server.js | // Entry point for server rendering subprocess
/* jshint strict: false */
if (process.env.NODE_ENV === undefined) {
require("babel-core/register")({
only: ['react-forms', 'src/encoded/static'],
});
} else {
require('source-map-support').install();
}
require('./libs/react-patches');
var argv = process.argv.slice(process.execArgv.length + 2);
var debug = (argv[0] === '--debug');
var app = require('./libs/react-middleware').build(require('./components'));
var http_stream = require('subprocess-middleware').HTTPStream({app: app, captureConsole: !debug});
http_stream.pipe(process.stdout);
if (debug) {
var value = argv[1] || '{}';
http_stream.end('HTTP/1.1 200 OK\r\nX-Request-URL: http://localhost/\r\nContent-Length: ' + value.length + '\r\n\r\n' + value);
} else {
process.stdin.pipe(http_stream);
process.stdin.resume();
}
| // Entry point for server rendering subprocess
/* jshint strict: false */
if (process.env.NODE_ENV === undefined) {
require("babel-core/register")({
only: ['react-forms', 'src/encoded/static'],
});
} else {
require('source-map-support').install();
}
require('./libs/react-patches');
var argv = process.argv.slice(2);
var debug = (argv[0] === '--debug');
var app = require('./libs/react-middleware').build(require('./components'));
var http_stream = require('subprocess-middleware').HTTPStream({app: app, captureConsole: !debug});
http_stream.pipe(process.stdout);
if (debug) {
var value = argv[1] || '{}';
if (value.slice(0, 5) === 'file:') {
value = require('fs').readFileSync(value.slice(5));
} else {
value = new Buffer(value, 'utf8');
}
http_stream.write('HTTP/1.1 200 OK\r\nX-Request-URL: http://localhost/\r\nContent-Length: ' + value.length + '\r\n\r\n');
http_stream.write(value);
http_stream.end();
} else {
process.stdin.pipe(http_stream);
process.stdin.resume();
}
| Add ability to specify input from file for debugging. | Add ability to specify input from file for debugging.
| JavaScript | mit | ENCODE-DCC/snovault,4dn-dcic/fourfront,ENCODE-DCC/encoded,4dn-dcic/fourfront,hms-dbmi/fourfront,ENCODE-DCC/snovault,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,hms-dbmi/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,hms-dbmi/fourfront,ENCODE-DCC/snovault,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/encoded | ---
+++
@@ -12,7 +12,7 @@
require('./libs/react-patches');
-var argv = process.argv.slice(process.execArgv.length + 2);
+var argv = process.argv.slice(2);
var debug = (argv[0] === '--debug');
var app = require('./libs/react-middleware').build(require('./components'));
@@ -20,7 +20,14 @@
http_stream.pipe(process.stdout);
if (debug) {
var value = argv[1] || '{}';
- http_stream.end('HTTP/1.1 200 OK\r\nX-Request-URL: http://localhost/\r\nContent-Length: ' + value.length + '\r\n\r\n' + value);
+ if (value.slice(0, 5) === 'file:') {
+ value = require('fs').readFileSync(value.slice(5));
+ } else {
+ value = new Buffer(value, 'utf8');
+ }
+ http_stream.write('HTTP/1.1 200 OK\r\nX-Request-URL: http://localhost/\r\nContent-Length: ' + value.length + '\r\n\r\n');
+ http_stream.write(value);
+ http_stream.end();
} else {
process.stdin.pipe(http_stream);
process.stdin.resume(); |
9aa3a785ca1dd35c4402e6d1e655f9be30288383 | src/endpoints/auth/accept.js | src/endpoints/auth/accept.js | 'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
import AuthSess from '../../models/auth-session';
import Userkey from '../../models/userkey';
/**
* Accept
*
* @param {Object} params
* @param {Object} user
* @return {Promise<object>}
*/
module.exports = (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'token' parameter
const token = params.token;
if (token == null) {
return rej('token is required');
}
// Fetch token
const session = await AuthSess
.findOne({ token: token });
if (session === null) {
return rej('session not found');
}
// Generate userkey
const key = rndstr('a-zA-Z0-9', 32);
// Insert userkey doc
await Userkey.insert({
created_at: new Date(),
app: session.app,
user: user._id,
key: key
});
// Response
res();
}
| 'use strict';
/**
* Module dependencies
*/
import rndstr from 'rndstr';
import AuthSess from '../../models/auth-session';
import Userkey from '../../models/userkey';
/**
* Accept
*
* @param {Object} params
* @param {Object} user
* @return {Promise<object>}
*/
module.exports = (params, user) =>
new Promise(async (res, rej) =>
{
// Get 'token' parameter
const token = params.token;
if (token == null) {
return rej('token is required');
}
// Fetch token
const session = await AuthSess
.findOne({ token: token });
if (session === null) {
return rej('session not found');
}
// Generate userkey
const key = rndstr('a-zA-Z0-9', 32);
// Insert userkey doc
await Userkey.insert({
created_at: new Date(),
app: session.app,
user: user._id,
key: key
});
// Response
res();
});
| Add missing semicolon and bracket | Add missing semicolon and bracket | JavaScript | mit | syuilo/misskey-core,syuilo/misskey-core,syuilo/misskey-core,syuilo/misskey-core | ---
+++
@@ -44,4 +44,4 @@
// Response
res();
-}
+}); |
7c333b1ea5ffa23334d81e125a87841c91c719ae | config/front.prod.config.js | config/front.prod.config.js | const merge = require('webpack-merge');
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const baseConfig = require('./base.config');
const frontConfig = require('./front.config');
const paths = require('./paths');
const devConfig = merge(baseConfig, frontConfig, {
output: {
filename: '[name].[chunkhash].js',
},
plugins: [
new ExtractTextPlugin({
filename: '/css/[name].[chunkhash].css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
sourceMap: true,
}),
new OptimizeCSSPlugin(),
new ManifestPlugin({
fileName: paths.manifest,
basePath: paths.assets,
}),
],
devtool: '#source-map',
});
module.exports = devConfig;
| const merge = require('webpack-merge');
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const frontConfig = require('./front.config');
const devConfig = merge(frontConfig, {
output: {
filename: 'js/[name].[chunkhash].js',
},
plugins: [
new ExtractTextPlugin({
filename: 'css/[name].[chunkhash].css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
sourceMap: true,
}),
new OptimizeCSSPlugin(),
],
devtool: '#source-map',
});
module.exports = devConfig;
| Update paths and remove dupl. plugins from front prod | Update paths and remove dupl. plugins from front prod
| JavaScript | mit | tuelsch/bolg,tuelsch/bolg | ---
+++
@@ -2,18 +2,15 @@
const webpack = require('webpack');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
-const ManifestPlugin = require('webpack-manifest-plugin');
-const baseConfig = require('./base.config');
const frontConfig = require('./front.config');
-const paths = require('./paths');
-const devConfig = merge(baseConfig, frontConfig, {
+const devConfig = merge(frontConfig, {
output: {
- filename: '[name].[chunkhash].js',
+ filename: 'js/[name].[chunkhash].js',
},
plugins: [
new ExtractTextPlugin({
- filename: '/css/[name].[chunkhash].css',
+ filename: 'css/[name].[chunkhash].css',
allChunks: true,
}),
new webpack.optimize.UglifyJsPlugin({
@@ -23,10 +20,6 @@
sourceMap: true,
}),
new OptimizeCSSPlugin(),
- new ManifestPlugin({
- fileName: paths.manifest,
- basePath: paths.assets,
- }),
],
devtool: '#source-map',
}); |
172ec0b4c753fc6a99eb7912cf9fca06d71103fa | test/api/getLanguage.js | test/api/getLanguage.js | 'use strict';
var hljs = require('../../build');
describe('.getLanguage', function() {
it('should get an existing language', function() {
var result = hljs.getLanguage('python');
result.should.be.instanceOf(Object);
});
it('should be case insensitive', function() {
var result = hljs.getLanguage('pYTHOn');
result.should.be.instanceOf(Object);
});
it('should return undefined', function() {
var result = hljs.getLanguage('-impossible-');
(result === undefined).should.be.true;
});
it('should not break on undefined', function() {
var result = hljs.getLanguage(undefined);
(result === undefined).should.be.true;
});
});
| 'use strict';
var hljs = require('../../build');
var should = require('should');
describe('.getLanguage', function() {
it('should get an existing language', function() {
var result = hljs.getLanguage('python');
result.should.be.instanceOf(Object);
});
it('should be case insensitive', function() {
var result = hljs.getLanguage('pYTHOn');
result.should.be.instanceOf(Object);
});
it('should return undefined', function() {
var result = hljs.getLanguage('-impossible-');
should.strictEqual(result, undefined);
});
it('should not break on undefined', function() {
var result = hljs.getLanguage(undefined);
should.strictEqual(result, undefined);
});
});
| Make testing for undefined more clear | Make testing for undefined more clear
| JavaScript | bsd-3-clause | Sannis/highlight.js,dbkaplun/highlight.js,sourrust/highlight.js,bluepichu/highlight.js,bluepichu/highlight.js,isagalaev/highlight.js,palmin/highlight.js,palmin/highlight.js,StanislawSwierc/highlight.js,carlokok/highlight.js,teambition/highlight.js,teambition/highlight.js,dbkaplun/highlight.js,Sannis/highlight.js,highlightjs/highlight.js,aurusov/highlight.js,Sannis/highlight.js,tenbits/highlight.js,sourrust/highlight.js,sourrust/highlight.js,MakeNowJust/highlight.js,carlokok/highlight.js,teambition/highlight.js,bluepichu/highlight.js,aurusov/highlight.js,carlokok/highlight.js,tenbits/highlight.js,StanislawSwierc/highlight.js,tenbits/highlight.js,MakeNowJust/highlight.js,lead-auth/highlight.js,highlightjs/highlight.js,isagalaev/highlight.js,highlightjs/highlight.js,palmin/highlight.js,carlokok/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,dbkaplun/highlight.js,MakeNowJust/highlight.js | ---
+++
@@ -1,6 +1,7 @@
'use strict';
-var hljs = require('../../build');
+var hljs = require('../../build');
+var should = require('should');
describe('.getLanguage', function() {
it('should get an existing language', function() {
@@ -18,14 +19,12 @@
it('should return undefined', function() {
var result = hljs.getLanguage('-impossible-');
- (result === undefined).should.be.true;
+ should.strictEqual(result, undefined);
});
it('should not break on undefined', function() {
var result = hljs.getLanguage(undefined);
- (result === undefined).should.be.true;
+ should.strictEqual(result, undefined);
});
-
-
}); |
587dc3f78c3b100ed84476849de7fc9d59a2a865 | src/app/constants/index.js | src/app/constants/index.js | // Workflow State
export const WORKFLOW_STATE_RUNNING = 'running';
export const WORKFLOW_STATE_PAUSED = 'paused';
export const WORKFLOW_STATE_IDLE = 'idle';
| // Workflow State
export const WORKFLOW_STATE_RUNNING = 'running';
export const WORKFLOW_STATE_PAUSED = 'paused';
export const WORKFLOW_STATE_IDLE = 'idle';
// Macro action
export const MACRO_ACTION_START = 'start';
export const MACRO_ACTION_STOP = 'stop';
| Define constants for macro actions | Define constants for macro actions
| JavaScript | mit | cheton/cnc.js,cheton/cnc,cncjs/cncjs,cheton/cnc.js,cheton/piduino-grbl,cheton/cnc.js,cncjs/cncjs,cncjs/cncjs,cheton/piduino-grbl,cheton/piduino-grbl,cheton/cnc,cheton/cnc | ---
+++
@@ -2,3 +2,7 @@
export const WORKFLOW_STATE_RUNNING = 'running';
export const WORKFLOW_STATE_PAUSED = 'paused';
export const WORKFLOW_STATE_IDLE = 'idle';
+
+// Macro action
+export const MACRO_ACTION_START = 'start';
+export const MACRO_ACTION_STOP = 'stop'; |
60248caad30d984b8879d260b0a3d1c2a1105565 | server/api.js | server/api.js | var express = require('express');
var app = express();
var fb = require("./firebaselogin.js");
var db = fb.database();
var ref = db.ref();
var glob = require('glob');
exports.test = function(req, res) {
ref.on("value", function(snapshot) {
res.send(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};
exports.create = function(req, res) {
var username = req.query.username;
var userRef = ref.child("user/"+username);
userRef.set({
date_of_birth: "Jan 24 1993",
full_name: "Alan Turting"
});
};
exports.include = function(req, res) {
if (req.query.files) {
glob(req.query.files, function( err, files ) {
var html = '';
for (var f in files) {
var path = files[f];
html = html + 'document.write(\'<script src="' + path + '"></script>\\n\');\n';
}
res.send(html);
});
}
else {
res.send("alert('Missing (files) input');");
}
};
| var express = require('express');
var app = express();
var fb = require("./firebaselogin.js");
var db = fb.database();
var ref = db.ref();
var glob = require('glob');
exports.test = function(req, res) {
ref.on("value", function(snapshot) {
res.send(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};
exports.create = function(req, res) {
var username = req.query.username;
var userRef = ref.child("user/"+username);
userRef.set({
date_of_birth: "Jan 24 1993",
full_name: "Alan Turting"
});
};
exports.include = function(req, res) {
if (req.query.files &&
req.query.files.match(/^src\//) &&
!req.query.files.match(/\.\./)) {
glob(req.query.files, function( err, files ) {
var html = '';
for (var f in files) {
var path = files[f];
html = html + 'document.write(\'<script src="' + path + '"></script>\\n\');\n';
}
res.send(html);
});
}
else {
res.send("alert('Broken (files) input');");
}
};
| Make sure only files below src/ are included with glob. | Security: Make sure only files below src/ are included with glob.
| JavaScript | mit | hookbot/multi-player,hookbot/multi-player | ---
+++
@@ -23,7 +23,9 @@
};
exports.include = function(req, res) {
- if (req.query.files) {
+ if (req.query.files &&
+ req.query.files.match(/^src\//) &&
+ !req.query.files.match(/\.\./)) {
glob(req.query.files, function( err, files ) {
var html = '';
for (var f in files) {
@@ -34,6 +36,6 @@
});
}
else {
- res.send("alert('Missing (files) input');");
+ res.send("alert('Broken (files) input');");
}
}; |
26f807c3687ceac296280c2918f0e7b67526da38 | test/functional/user.js | test/functional/user.js | user_pref("media.peerconnection.default_iceservers", "[]");
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("social.activeProviders", "{\"http://localhost:3000\":1}");
user_pref("social.enabled", true);
user_pref("social.manifest.tests", "{\"name\":\"Talkilla Functional tests\",\"iconURL\":\"http://localhost:3000/icon.png\",\"sidebarURL\":\"http://localhost:3000/sidebar.html\",\"workerURL\":\"http://localhost:3000/js/worker.js\",\"origin\":\"http://localhost:3000\",\"enabled\":true,\"last_modified\":135101330568}");
user_pref("social.provider.current", "http://localhost:3000");
| user_pref("browser.dom.window.dump.enabled", true);
user_pref("media.peerconnection.default_iceservers", "[]");
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("social.activeProviders", "{\"http://localhost:3000\":1}");
user_pref("social.enabled", true);
user_pref("social.manifest.tests", "{\"name\":\"Talkilla Functional tests\",\"iconURL\":\"http://localhost:3000/icon.png\",\"sidebarURL\":\"http://localhost:3000/sidebar.html\",\"workerURL\":\"http://localhost:3000/js/worker.js\",\"origin\":\"http://localhost:3000\",\"enabled\":true,\"last_modified\":135101330568}");
user_pref("social.provider.current", "http://localhost:3000");
| Enable console output of dump by default in selenium tests | Enable console output of dump by default in selenium tests
| JavaScript | mpl-2.0 | mozilla/talkilla,mozilla/talkilla,mozilla/talkilla | ---
+++
@@ -1,3 +1,4 @@
+user_pref("browser.dom.window.dump.enabled", true);
user_pref("media.peerconnection.default_iceservers", "[]");
user_pref("media.peerconnection.use_document_iceservers", false);
user_pref("social.activeProviders", "{\"http://localhost:3000\":1}"); |
54dbeb7bef3f31244dc4ca6f5b0ab5ff71c2bb3e | src/patch/operators/array.js | src/patch/operators/array.js | 'use strict';
const ANY_ARRAY = [
'boolean[]',
'integer[]',
'number[]',
'string[]',
'object[]',
'null[]',
];
// `_slice` patch operator
const sliceOperator = {
attribute: ANY_ARRAY,
argument: ['integer[]'],
check (opVal) {
if (opVal.length <= 2) { return; }
return 'the argument must be an array with one integer (the index) and an optional additional integer (the length)';
},
apply (attrVal, [index, length]) {
return attrVal.slice(index, length);
},
};
// `_insert` patch operator
const insertOperator = {
attribute: ANY_ARRAY,
argument: ANY_ARRAY,
check ([index]) {
const isValid = Number.isInteger(index);
if (isValid) { return; }
return 'the argument\'s first value must be an integer (the index)';
},
apply (attrVal, [index, ...values]) {
const beginning = attrVal.slice(0, index);
const end = attrVal.slice(index);
return [...beginning, ...values, ...end];
},
};
module.exports = {
_slice: sliceOperator,
_insert: insertOperator,
};
| 'use strict';
const ANY_ARRAY = [
'boolean[]',
'integer[]',
'number[]',
'string[]',
'object[]',
'null[]',
];
// `_push` patch operator
const pushOperator = {
attribute: ANY_ARRAY,
argument: ANY_ARRAY,
apply (attrVal, opVal) {
return [...attrVal, ...opVal];
},
};
// `_unshift` patch operator
const unshiftOperator = {
attribute: ANY_ARRAY,
argument: ANY_ARRAY,
apply (attrVal, opVal) {
return [...opVal, ...attrVal];
},
};
// `_slice` patch operator
const sliceOperator = {
attribute: ANY_ARRAY,
argument: ['integer[]'],
check (opVal) {
if (opVal.length <= 2) { return; }
return 'the argument must be an array with one integer (the index) and an optional additional integer (the length)';
},
apply (attrVal, [index, length]) {
return attrVal.slice(index, length);
},
};
// `_insert` patch operator
const insertOperator = {
attribute: ANY_ARRAY,
argument: ANY_ARRAY,
check ([index]) {
const isValid = Number.isInteger(index);
if (isValid) { return; }
return 'the argument\'s first value must be an integer (the index)';
},
apply (attrVal, [index, ...values]) {
const beginning = attrVal.slice(0, index);
const end = attrVal.slice(index);
return [...beginning, ...values, ...end];
},
};
module.exports = {
_push: pushOperator,
_unshift: unshiftOperator,
_slice: sliceOperator,
_insert: insertOperator,
};
| Add _push and _unshift patch operators | Add _push and _unshift patch operators
| JavaScript | apache-2.0 | autoserver-org/autoserver,autoserver-org/autoserver | ---
+++
@@ -8,6 +8,28 @@
'object[]',
'null[]',
];
+
+// `_push` patch operator
+const pushOperator = {
+ attribute: ANY_ARRAY,
+
+ argument: ANY_ARRAY,
+
+ apply (attrVal, opVal) {
+ return [...attrVal, ...opVal];
+ },
+};
+
+// `_unshift` patch operator
+const unshiftOperator = {
+ attribute: ANY_ARRAY,
+
+ argument: ANY_ARRAY,
+
+ apply (attrVal, opVal) {
+ return [...opVal, ...attrVal];
+ },
+};
// `_slice` patch operator
const sliceOperator = {
@@ -47,6 +69,8 @@
};
module.exports = {
+ _push: pushOperator,
+ _unshift: unshiftOperator,
_slice: sliceOperator,
_insert: insertOperator,
}; |
22ba78f09327a540e3d5f49509906989aeb6ce4a | app/bootstrap.js | app/bootstrap.js | module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
| module.exports = (function() {
var Router = require('router'),
Connection = require('lib/connection');
// App namespace.
window.Boards = {
Models: {},
Collections: {}
};
// Load helpers.
require('lib/helpers');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'JWT ' + _.getModel('User').get('token'));
}
});
// Register Swag Helpers.
Swag.registerHelpers();
// Initialize Router.
Boards.Router = new Router();
// Create a Connection object to communicate with the server through web sockets.
// The `connection` object will be added to the `Application` object so it's available through
// `window.Application.connection`.
Boards.Connection = new Connection({
type: APPLICATION_CONNECTION,
httpUrl: APPLICATION_HTTP_URL,
socketUrl: APPLICATION_WEBSOCKET_URL
});
// Connect to the server.
Boards.Connection.create().done(function() {
Boards.Router.start();
}).fail(function() {
console.log('Connection Error', arguments);
});
})();
| Send JWT auth token on the as an authorization header of every HTTP request. | Send JWT auth token on the as an authorization header of every HTTP request.
| JavaScript | agpl-3.0 | GetBlimp/boards-web,jessamynsmith/boards-web,jessamynsmith/boards-web | ---
+++
@@ -10,6 +10,12 @@
// Load helpers.
require('lib/helpers');
+
+ $.ajaxSetup({
+ beforeSend: function(xhr, settings) {
+ xhr.setRequestHeader('Authorization', 'JWT ' + _.getModel('User').get('token'));
+ }
+ });
// Register Swag Helpers.
Swag.registerHelpers(); |
b5e9d9134e49a3e467921c07f967e0c7e5e6ab0b | test/unit/views/base.js | test/unit/views/base.js | import {createContainer} from 'stardux'
import View from '../../../src/dragon/views/base'
describe('Unit: View', function() {
/*
TODO: what happens if:
- there is no container?
- there is no template?
*/
it.skip('should initialize', function(done) {
var view = new View({
})
expect(view).to.be.an('object')
done()
})
it('should create view from container (string reference)', function(done) {
var view = new View({
container: '#app',
template: 'Hello World'
})
expect(view).to.be.an('object')
done()
})
it.skip('should create view from container', function(done) {
var view = new View({
container: createContainer(document.querySelector('#app'))
})
expect(view).to.be.an('object')
done()
})
it('should manually attach to DOM', function(done) {
var view = new View({
attachOnInit: false,
container: '#app',
template: 'Hello World'
})
view.on('addedToDOM', function() {
done()
})
view.attach()
})
})
| import {createContainer} from 'stardux'
import View from '../../../src/dragon/views/base'
describe('Unit: View', function() {
/*
TODO: what happens if:
- there is no container?
- there is no template?
*/
it.skip('should initialize', function(done) {
var view = new View({
})
expect(view).to.be.an('object')
done()
})
it('should create view from container (string reference)', function(done) {
var view = new View({
container: '#app',
template: 'Hello World'
})
expect(view).to.be.an('object')
done()
})
it.skip('should create view from container', function(done) {
var view = new View({
container: createContainer(document.querySelector('#app'))
})
expect(view).to.be.an('object')
done()
})
it('should manually attach to DOM', function(done) {
var view = new View({
attachOnInit: false,
container: '#app',
template: 'Hello World'
})
view.on('addedToDOM', function() {
done()
})
view.attach()
})
it('should have a tagName <nav>', function(done) {
var view = new View({
container: '#app',
tagName: 'nav',
template: 'Hello World'
})
expect(view.tagName).to.equal('nav')
done()
})
})
| Add unit test for tagName | Add unit test for tagName
| JavaScript | mit | chrisabrams/dragon,chrisabrams/dragon | ---
+++
@@ -61,4 +61,18 @@
})
+ it('should have a tagName <nav>', function(done) {
+
+ var view = new View({
+ container: '#app',
+ tagName: 'nav',
+ template: 'Hello World'
+ })
+
+ expect(view.tagName).to.equal('nav')
+
+ done()
+
+ })
+
}) |
9673596b7c313b8544c51f0053131008909de6dc | server/middleware/requireEmailWithDomains.js | server/middleware/requireEmailWithDomains.js | module.exports = (req, res, next, {
/**
* @param acceptableDomains
*
* List of fully qualified accceptable domain names.
* Should be for example 'safaricom.co.ke', not just 'safaricom' or 'co.ke'
*
* IMPORTANT!!
* If you use this middleware and add other acceptableDomains, make sure to
* add 'safaricom.co.ke' in your list as well. It's added here as a default
* and will be overridden if other values are passed.
*
* Not going to validate that you didn't override 'safaricom.co.ke', I trust
* that you're a developer and you what you're doing. ¯\_(ツ)_/¯
*/
acceptableDomains = ['safaricom.co.ke']
} = {}) => {
if (req.body.email) { // Only try to validate if we have an email.
for (const domain of acceptableDomains) {
if (new RegExp(`${domain}$`, 'i').test(req.body.email)) {
return next();
}
}
return res.status(400).send({
email: 'This email is invalid.'
});
}
return next();
};
| let acceptableDomainsFromEnv = process.env.ACCEPTABLE_DOMAINS;
if (acceptableDomainsFromEnv) {
acceptableDomainsFromEnv = acceptableDomainsFromEnv.split(',').filter(
domain => !!domain // Remove any empty items from the list.
);
}
module.exports = (req, res, next, {
/**
* @param acceptableDomains
*
* List of fully qualified accceptable domain names.
* Should be for example 'safaricom.co.ke', not just 'safaricom' or 'co.ke'
*
* IMPORTANT!!
* If you use this middleware and add other acceptableDomains, make sure to
* add 'safaricom.co.ke' in your list as well. It's added here as a default
* and will be overridden if other values are passed.
* It's HIGHLY recommended that you don't edit the code to add domains
* into the list, rather, add them into your environment as a comma
* separated list in an env variable named ACCEPTABLE_DOMAINS.
*
* Not going to validate that you didn't override 'safaricom.co.ke', I trust
* that you're a developer and you what you're doing. ¯\_(ツ)_/¯
*/
acceptableDomains = ['safaricom.co.ke']
} = {}) => {
let domains = acceptableDomains;
if (acceptableDomainsFromEnv) {
domains = domains.concat(acceptableDomainsFromEnv);
}
if (req.body.email) { // Only try to validate if we have an email.
for (const domain of domains) {
if (new RegExp(`${domain}$`, 'i').test(req.body.email)) {
return next();
}
}
return res.status(400).send({
email: 'This email is invalid.'
});
}
return next();
};
| Make `acceptableDomains` configurable without editing source code. | Make `acceptableDomains` configurable without editing source code.
A list of available domains is now being read in from the env and
added to the default list.
| JavaScript | mit | Waiyaki/provisioning-scheduler,Waiyaki/provisioning-scheduler,Waiyaki/provisioning-scheduler | ---
+++
@@ -1,3 +1,11 @@
+let acceptableDomainsFromEnv = process.env.ACCEPTABLE_DOMAINS;
+
+if (acceptableDomainsFromEnv) {
+ acceptableDomainsFromEnv = acceptableDomainsFromEnv.split(',').filter(
+ domain => !!domain // Remove any empty items from the list.
+ );
+}
+
module.exports = (req, res, next, {
/**
* @param acceptableDomains
@@ -9,14 +17,22 @@
* If you use this middleware and add other acceptableDomains, make sure to
* add 'safaricom.co.ke' in your list as well. It's added here as a default
* and will be overridden if other values are passed.
+ * It's HIGHLY recommended that you don't edit the code to add domains
+ * into the list, rather, add them into your environment as a comma
+ * separated list in an env variable named ACCEPTABLE_DOMAINS.
*
* Not going to validate that you didn't override 'safaricom.co.ke', I trust
* that you're a developer and you what you're doing. ¯\_(ツ)_/¯
*/
acceptableDomains = ['safaricom.co.ke']
} = {}) => {
+ let domains = acceptableDomains;
+
+ if (acceptableDomainsFromEnv) {
+ domains = domains.concat(acceptableDomainsFromEnv);
+ }
if (req.body.email) { // Only try to validate if we have an email.
- for (const domain of acceptableDomains) {
+ for (const domain of domains) {
if (new RegExp(`${domain}$`, 'i').test(req.body.email)) {
return next();
} |
14213152b43a4b9d6be88e161b0d9fb2e56d9a0c | src/mist/io/static/js/app/views/delete_tag.js | src/mist/io/static/js/app/views/delete_tag.js | define('app/views/delete_tag', [
'ember',
'jquery'
],
/**
*
* Delete tag view
*
* @returns Class
*/
function() {
return Ember.View.extend({
tagName: false,
didInsertElement: function(e){
$("a.tagButton").button();
},
deleteTag: function() {
var tag = this.tag;
var machine = Mist.machine;
machine.tags.removeObject(this.tag.toString());
log("tag to delete: " + tag);
var payload = {
'tag': tag.toString()
};
machine.set('pendingDeleteTag', true);
$.ajax({
url: 'backends/' + machine.backend.id + '/machines/' + machine.id + '/metadata',
type: 'DELETE',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function(data) {
info('Successfully deleted tag from machine', machine.name);
machine.set('pendingDeleteTag', false);
},
error: function(jqXHR, textstate, errorThrown) {
Mist.notificationController.notify('Error while deleting tag from machine ' +
machine.name);
error(textstate, errorThrown, 'while deleting tag from machine machine', machine.name);
machine.tags.addObject(tag.toString());
machine.set('pendingDeleteTag', false);
}
});
}
});
}
);
| define('app/views/delete_tag', [
'ember',
'jquery'
],
/**
*
* Delete tag view
*
* @returns Class
*/
function() {
return Ember.View.extend({
tagName: false,
didInsertElement: function(e){
$("a.tagButton").button();
},
deleteTag: function() {
var tag = this.tag;
var machine = Mist.machine;
log("tag to delete: " + tag);
var payload = {
'tag': tag.toString()
};
machine.set('pendingDeleteTag', true);
$.ajax({
url: 'backends/' + machine.backend.id + '/machines/' + machine.id + '/metadata',
type: 'DELETE',
contentType: 'application/json',
data: JSON.stringify(payload),
success: function(data) {
info('Successfully deleted tag from machine', machine.name);
machine.tags.removeObject(this.tag.toString());
machine.set('pendingDeleteTag', false);
},
error: function(jqXHR, textstate, errorThrown) {
Mist.notificationController.notify('Error while deleting tag from machine ' +
machine.name);
error(textstate, errorThrown, 'while deleting tag from machine machine', machine.name);
machine.set('pendingDeleteTag', false);
}
});
}
});
}
);
| Delete tag only on success | Delete tag only on success
| JavaScript | agpl-3.0 | Lao-liu/mist.io,munkiat/mist.io,DimensionDataCBUSydney/mist.io,afivos/mist.io,kelonye/mist.io,johnnyWalnut/mist.io,zBMNForks/mist.io,johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,munkiat/mist.io,munkiat/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,afivos/mist.io,munkiat/mist.io,johnnyWalnut/mist.io,Lao-liu/mist.io,afivos/mist.io,kelonye/mist.io,kelonye/mist.io | ---
+++
@@ -20,8 +20,6 @@
var tag = this.tag;
var machine = Mist.machine;
- machine.tags.removeObject(this.tag.toString());
-
log("tag to delete: " + tag);
var payload = {
@@ -36,13 +34,13 @@
data: JSON.stringify(payload),
success: function(data) {
info('Successfully deleted tag from machine', machine.name);
+ machine.tags.removeObject(this.tag.toString());
machine.set('pendingDeleteTag', false);
},
error: function(jqXHR, textstate, errorThrown) {
Mist.notificationController.notify('Error while deleting tag from machine ' +
machine.name);
error(textstate, errorThrown, 'while deleting tag from machine machine', machine.name);
- machine.tags.addObject(tag.toString());
machine.set('pendingDeleteTag', false);
}
}); |
fc7023dcefd21b3e376e63facdb94d3dde8b3bf0 | evently/finder/loggedIn/data.js | evently/finder/loggedIn/data.js | function(resp) {
var flights = resp.rows.map(function(r) {
return {
flight : r.key[0]
};
});
flights.unshift({"flight": "All"});
return {flights:flights};
}
//@ sourceURL=/finder/data.js
| function(resp) {
var flights = resp.rows.map(function(r) {
return {
flight : r.key[1]
};
});
flights.unshift({"flight": "All"});
return {flights:flights};
}
//@ sourceURL=/finder/data.js
| Fix index in flight filter. | Fix index in flight filter.
| JavaScript | apache-2.0 | shmakes/hf-basic,shmakes/hf-basic | ---
+++
@@ -1,7 +1,7 @@
function(resp) {
var flights = resp.rows.map(function(r) {
return {
- flight : r.key[0]
+ flight : r.key[1]
};
});
flights.unshift({"flight": "All"}); |
20fa652bb202bd6d0b02e0fe56ccdff2b47ba29d | cordova/scripts/replace-config-env-vars.js | cordova/scripts/replace-config-env-vars.js | module.exports = function(context) {
const fs = context.requireCordovaModule('fs');
const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util');
let projectRoot = cordova_util.isCordova();
let configXML = cordova_util.projectConfig(projectRoot);
let data = fs.readFileSync(configXML, 'utf8');
for (var envVar in process.env) {
data = data.replace('$' + envVar, process.env[envVar]);
}
fs.writeFileSync(configXML, data, 'utf8');
}; | module.exports = function(context) {
const fs = require('fs');
const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util');
let projectRoot = cordova_util.isCordova();
let configXML = cordova_util.projectConfig(projectRoot);
let data = fs.readFileSync(configXML, 'utf8');
for (var envVar in process.env) {
data = data.replace('$' + envVar, process.env[envVar]);
}
fs.writeFileSync(configXML, data, 'utf8');
};
| Fix loading non-cordova modules in scripts | Fix loading non-cordova modules in scripts
Loading non-cordova modules with `requireCordovaModule` is not
supported. | JavaScript | epl-1.0 | eclipsesource/tabris-js-hello-world,eclipsesource/tabris-js-hello-world,eclipsesource/tabris-js-hello-world | ---
+++
@@ -1,6 +1,6 @@
module.exports = function(context) {
- const fs = context.requireCordovaModule('fs');
+ const fs = require('fs');
const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util');
let projectRoot = cordova_util.isCordova(); |
d87ae0303852f1021f76200c062a0bf666a645e3 | examples/sources/ImageSource.js | examples/sources/ImageSource.js | import PropTypes from 'prop-types';
import React from 'react';
import { AtomicBlockUtils } from 'draft-js';
class ImageSource extends React.Component {
componentDidMount() {
const { editorState, options, onUpdate } = this.props;
const url = window.prompt('Link URL');
if (url) {
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
options.type,
'IMMUTABLE',
{
alt: '',
alignment: 'left',
src: url,
},
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const nextState = AtomicBlockUtils.insertAtomicBlock(
editorState,
entityKey,
' ',
);
onUpdate(nextState);
} else {
onUpdate(editorState);
}
}
render() {
return null;
}
}
ImageSource.propTypes = {
editorState: PropTypes.object.isRequired,
options: PropTypes.object.isRequired,
onUpdate: PropTypes.func.isRequired,
};
export default ImageSource;
| import PropTypes from 'prop-types';
import React from 'react';
import { AtomicBlockUtils } from 'draft-js';
class ImageSource extends React.Component {
componentDidMount() {
const { editorState, options, onUpdate } = this.props;
const url = window.prompt('Link URL');
if (url) {
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
options.type,
'MUTABLE',
{
alt: '',
alignment: 'left',
src: url,
},
);
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const nextState = AtomicBlockUtils.insertAtomicBlock(
editorState,
entityKey,
' ',
);
onUpdate(nextState);
} else {
onUpdate(editorState);
}
}
render() {
return null;
}
}
ImageSource.propTypes = {
editorState: PropTypes.object.isRequired,
options: PropTypes.object.isRequired,
onUpdate: PropTypes.func.isRequired,
};
export default ImageSource;
| Create images as MUTABLE, like a paste would | Create images as MUTABLE, like a paste would
| JavaScript | mit | springload/draftail,springload/draftail,springload/draftail,springload/draftail | ---
+++
@@ -12,7 +12,7 @@
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
options.type,
- 'IMMUTABLE',
+ 'MUTABLE',
{
alt: '',
alignment: 'left', |
9cbfc459fd163d79d7e8e99e339a05f04377cb66 | src/classes/modifiers/outlets-receivable.js | src/classes/modifiers/outlets-receivable.js | class OutletsReceivable {
static transform(modified, ...names) {
modified.outlets = names;
modified._argsTransformFns.push(this.filterOutlets.bind(null, modified));
}
static filterOutlets(modified, opts, ...args) {
let names = modified.outlets;
let outlets = opts.outlets || {};
let newOpts = {};
for (let prop in opts) {
if (opts.hasOwnProperty(prop)) {
newOpts[prop] = opts[prop];
}
}
newOpts.outlets = {};
for (let name of names) {
if (outlets.hasOwnProperty(name)) {
newOpts.outlets[name] = outlets[name];
} else {
let quote = function(s) { return ['"',s,'"'].join(''); };
throw new Error([
'Route expected outlets [',
names.map(quote),
'] but received [',
Object.keys(outlets).sort().map(quote),
'].'
].join(''));
}
}
return [newOpts, ...args];
}
}
export default OutletsReceivable;
| class OutletsReceivable {
static transform(modified, ...names) {
modified.outlets = names;
modified._argsTransformFns.push(this.filterOutlets.bind(null, modified));
}
static filterOutlets(modified, opts, ...args) {
let names = modified.outlets;
let outlets = opts.outlets || {};
let newOpts = {};
for (let prop in opts) {
if (opts.hasOwnProperty(prop)) {
newOpts[prop] = opts[prop];
}
}
newOpts.outlets = {};
for (let name of names) {
if (outlets.hasOwnProperty(name)) {
newOpts.outlets[name] = outlets[name];
} else {
throw new Error([
'Route expected outlets ',
JSON.stringify(names),
' but received ',
JSON.stringify(Object.keys(outlets).sort()),
'.'
].join(''));
}
}
return [newOpts, ...args];
}
}
export default OutletsReceivable;
| Use JSON.stringify to stringify Array | Use JSON.stringify to stringify Array
| JavaScript | mit | darvelo/ether,darvelo/ether,darvelo/ether | ---
+++
@@ -21,13 +21,12 @@
if (outlets.hasOwnProperty(name)) {
newOpts.outlets[name] = outlets[name];
} else {
- let quote = function(s) { return ['"',s,'"'].join(''); };
throw new Error([
- 'Route expected outlets [',
- names.map(quote),
- '] but received [',
- Object.keys(outlets).sort().map(quote),
- '].'
+ 'Route expected outlets ',
+ JSON.stringify(names),
+ ' but received ',
+ JSON.stringify(Object.keys(outlets).sort()),
+ '.'
].join(''));
}
} |
81dc99e8e63041c57c477fda1c56da228c259fcf | fan/tasks/views/TaskItemView.js | fan/tasks/views/TaskItemView.js | jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 390
this._maxWidth = 740
this._headerHeight = 0
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this.getTaskId = function() { return this._itemId }
this._buildHeader = function() {
new fan.ui.RadioButtons()
.addButton({ text: 'Normal', payload: 'normal' })
.addButton({ text: 'Crucial', payload: 'crucial' })
.addButton({ text: 'Backlog', payload: 'backlog' })
.addButton({ text: 'Done', payload: 'done' })
.subscribe('Click', this, '_toggleTaskState')
.appendTo(this._header)
}
this._buildBody = function() {
gUtil.withTemplate('task-panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
}) | jsio('from shared.javascript import Class')
jsio('import fan.ui.Button')
jsio('import fan.ui.RadioButtons')
jsio('import fan.tasks.views.View')
exports = Class(fan.tasks.views.View, function(supr) {
this._className += ' TaskItemView'
this._minWidth = 390
this._maxWidth = 740
this._headerHeight = 0
this.init = function(itemId) {
supr(this, 'init')
this._itemId = itemId
}
this.getTaskId = function() { return this._itemId }
// this._buildHeader = function() {
// new fan.ui.RadioButtons()
// .addButton({ text: 'Normal', payload: 'normal' })
// .addButton({ text: 'Crucial', payload: 'crucial' })
// .addButton({ text: 'Backlog', payload: 'backlog' })
// .addButton({ text: 'Done', payload: 'done' })
// .subscribe('Click', this, '_toggleTaskState')
// .appendTo(this._header)
// }
this._buildBody = function() {
gUtil.withTemplate('task-panel', bind(this, function(template) {
this._body.innerHTML = ''
this._body.appendChild(fin.applyTemplate(template, this._itemId))
}))
}
this._toggleTaskState = function(newState) {
console.log("TOGGLE STATE", newState)
}
}) | Comment out unused buildHeader code in taskItemView | Comment out unused buildHeader code in taskItemView
| JavaScript | mit | marcuswestin/Focus | ---
+++
@@ -17,15 +17,15 @@
this.getTaskId = function() { return this._itemId }
- this._buildHeader = function() {
- new fan.ui.RadioButtons()
- .addButton({ text: 'Normal', payload: 'normal' })
- .addButton({ text: 'Crucial', payload: 'crucial' })
- .addButton({ text: 'Backlog', payload: 'backlog' })
- .addButton({ text: 'Done', payload: 'done' })
- .subscribe('Click', this, '_toggleTaskState')
- .appendTo(this._header)
- }
+ // this._buildHeader = function() {
+ // new fan.ui.RadioButtons()
+ // .addButton({ text: 'Normal', payload: 'normal' })
+ // .addButton({ text: 'Crucial', payload: 'crucial' })
+ // .addButton({ text: 'Backlog', payload: 'backlog' })
+ // .addButton({ text: 'Done', payload: 'done' })
+ // .subscribe('Click', this, '_toggleTaskState')
+ // .appendTo(this._header)
+ // }
this._buildBody = function() {
gUtil.withTemplate('task-panel', bind(this, function(template) { |
a4f0ef9e898417a51bcc7a92c1e81605b62df5ce | tests/features/api/02-import-json_spec.js | tests/features/api/02-import-json_spec.js | describe('Import JSON', () => {
it('should work properly', () => {
cy.loginVisit('/')
cy.fixture('import.json').then(IMPORT_API => {
// Click [Import JSON] button
cy.get('.j-buttons__wrapper > a[href="/new"] + div > button')
.click()
// Prepare file upload
const file = JSON.stringify(IMPORT_API, null, 2)
const fileArray = file.split('\n')
const fileObject = new File(fileArray, 'import.json', { type: 'application/json' })
const dropEvent = {
dataTransfer: {
files: [
fileObject
]
}
}
// Execute File upload
cy.get('.uploader')
.trigger('drop', dropEvent).then(() => {
// Confirm upload
cy.get('.j-confirmation-container > .j-confirmation__buttons-group > .j-button--primary')
.click({ force: true })
.get('.j-confirmation__buttons-group > .j-button--primary')
.click()
// Validate that imported api endpoint is created
cy.loginVisit('/')
cy.get('.j-search-bar__input', { timeout: 100000 })
.type(IMPORT_API.name)
.get('.j-table__tbody')
.contains(IMPORT_API.name)
})
})
})
})
| describe('Import JSON', () => {
it('should work properly', () => {
cy.loginVisit('/')
cy.fixture('import.json').then(IMPORT_API => {
// Click [Import JSON] button
cy.get('.j-buttons__wrapper > a[href="/new"] + div > button')
.click()
// Prepare file upload
const file = JSON.stringify(IMPORT_API, null, 2)
const fileArray = file.split('\n')
const fileObject = new File(fileArray, 'import.json', { type: 'application/json' })
const dropEvent = {
dataTransfer: {
files: [
fileObject
]
}
}
// Execute File upload
cy.get('.uploader')
.trigger('drop', dropEvent).then(() => {
// Wait until editor appears, indicating successful upload
cy.get('#gw-json-editor')
// Confirm upload
cy.get('.j-confirmation-container > .j-confirmation__buttons-group > .j-button--primary')
.click({ force: true })
.get('.j-confirmation__buttons-group > .j-button--primary')
.click()
// Validate that imported api endpoint is created
cy.loginVisit('/')
cy.get('.j-search-bar__input', { timeout: 100000 })
.type(IMPORT_API.name)
.get('.j-table__tbody')
.contains(IMPORT_API.name)
})
})
})
})
| Fix tests failing on cypress 3.1.0 | Fix tests failing on cypress 3.1.0
| JavaScript | mit | hellofresh/janus-dashboard,hellofresh/janus-dashboard | ---
+++
@@ -23,6 +23,9 @@
cy.get('.uploader')
.trigger('drop', dropEvent).then(() => {
+ // Wait until editor appears, indicating successful upload
+ cy.get('#gw-json-editor')
+
// Confirm upload
cy.get('.j-confirmation-container > .j-confirmation__buttons-group > .j-button--primary')
.click({ force: true }) |
3abc44cceb5d10905092384b98a6d1c51a267180 | src/lights/AmbientLight.js | src/lights/AmbientLight.js | import { Light } from './Light';
/**
* @author mrdoob / http://mrdoob.com/
*/
function AmbientLight( color, intensity ) {
Light.call( this, color, intensity );
this.type = 'AmbientLight';
this.castShadow = undefined;
}
AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: AmbientLight,
isAmbientLight: true,
} );
export { AmbientLight };
| import { Light } from './Light';
/**
* @author mrdoob / http://mrdoob.com/
*/
function AmbientLight( color, intensity ) {
Light.call( this, color, intensity );
this.type = 'AmbientLight';
this.castShadow = undefined;
}
AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
constructor: AmbientLight,
isAmbientLight: true
} );
export { AmbientLight };
| Remove unneeded comma in AmbiantLight | Remove unneeded comma in AmbiantLight
| JavaScript | mit | spite/three.js,ndebeiss/three.js,TristanVALCKE/three.js,kaisalmen/three.js,sasha240100/three.js,amakaroff82/three.js,jostschmithals/three.js,mese79/three.js,aardgoose/three.js,Ludobaka/three.js,rlugojr/three.js,Jozain/three.js,matgr1/three.js,WestLangley/three.js,fraguada/three.js,nhalloran/three.js,nhalloran/three.js,bhouston/three.js,ndebeiss/three.js,mese79/three.js,fraguada/three.js,matgr1/three.js,RemusMar/three.js,Benjamin-Dobell/three.js,Astrak/three.js,mhoangvslev/data-visualizer,hsimpson/three.js,bdysvik/three.js,Jozain/three.js,Amritesh/three.js,ndebeiss/three.js,arodic/three.js,colombod/three.js,rfm1201/rfm.three.js,jayschwa/three.js,rlugojr/three.js,googlecreativelab/three.js,brianchirls/three.js,Ludobaka/three.js,technohippy/three.js,Mugen87/three.js,q437634645/three.js,ngokevin/three-dev,rfm1201/rfm.three.js,donmccurdy/three.js,takahirox/three.js,bhouston/three.js,fanzhanggoogle/three.js,spite/three.js,mhoangvslev/data-visualizer,nhalloran/three.js,satori99/three.js,ValtoLibraries/ThreeJS,stopyransky/three.js,Ludobaka/three.js,looeee/three.js,pailhead/three.js,Hectate/three.js,06wj/three.js,googlecreativelab/three.js,mese79/three.js,shinate/three.js,sasha240100/three.js,rlugojr/three.js,RemusMar/three.js,opensim-org/three.js,fyoudine/three.js,ndebeiss/three.js,nhalloran/three.js,ngokevin/three.js,carlosanunes/three.js,zhoushijie163/three.js,jee7/three.js,fraguada/three.js,sasha240100/three.js,Astrak/three.js,ValtoLibraries/ThreeJS,nhalloran/three.js,stanford-gfx/three.js,Benjamin-Dobell/three.js,carlosanunes/three.js,shinate/three.js,xundaokeji/three.js,Aldrien-/three.js,yrns/three.js,kaisalmen/three.js,Aldrien-/three.js,QingchaoHu/three.js,carlosanunes/three.js,mrdoob/three.js,colombod/three.js,ikerr/three.js,RemusMar/three.js,Benjamin-Dobell/three.js,ondys/three.js,Itee/three.js,Hectate/three.js,Benjamin-Dobell/three.js,satori99/three.js,technohippy/three.js,Samsy/three.js,Seagat2011/three.js,shinate/three.js,flimshaw/three.js,cadenasgmbh/three.js,technohippy/three.js,ngokevin/three-dev,Liuer/three.js,Hectate/three.js,ondys/three.js,Samsung-Blue/three.js,TristanVALCKE/three.js,Aldrien-/three.js,godlzr/Three.js,QingchaoHu/three.js,spite/three.js,spite/three.js,fernandojsg/three.js,brianchirls/three.js,Seagat2011/three.js,flimshaw/three.js,fraguada/three.js,ondys/three.js,Itee/three.js,Ludobaka/three.js,satori99/three.js,ngokevin/three.js,jayschwa/three.js,bdysvik/three.js,jpweeks/three.js,Aldrien-/three.js,q437634645/three.js,spite/three.js,Astrak/three.js,q437634645/three.js,zhoushijie163/three.js,q437634645/three.js,yrns/three.js,colombod/three.js,satori99/three.js,xundaokeji/three.js,ngokevin/three-dev,jostschmithals/three.js,amakaroff82/three.js,ngokevin/three.js,ikerr/three.js,fraguada/three.js,Amritesh/three.js,mrdoob/three.js,jee7/three.js,takahirox/three.js,colombod/three.js,agnivade/three.js,stopyransky/three.js,rlugojr/three.js,julapy/three.js,fanzhanggoogle/three.js,ngokevin/three-dev,godlzr/Three.js,ikerr/three.js,Jozain/three.js,jostschmithals/three.js,googlecreativelab/three.js,TristanVALCKE/three.js,gero3/three.js,jeffgoku/three.js,fernandojsg/three.js,Jozain/three.js,takahirox/three.js,colombod/three.js,hsimpson/three.js,shanmugamss/three.js-modified,sasha240100/three.js,ndebeiss/three.js,TristanVALCKE/three.js,Jozain/three.js,sttz/three.js,ondys/three.js,fanzhanggoogle/three.js,cadenasgmbh/three.js,shinate/three.js,ngokevin/three-dev,sherousee/three.js,greggman/three.js,googlecreativelab/three.js,Samsung-Blue/three.js,amakaroff82/three.js,rlugojr/three.js,ngokevin/three.js,xundaokeji/three.js,technohippy/three.js,Samsy/three.js,framelab/three.js,jee7/three.js,Samsung-Blue/three.js,amakaroff82/three.js,Aldrien-/three.js,jostschmithals/three.js,ngokevin/three.js,agnivade/three.js,sasha240100/three.js,daoshengmu/three.js,Samsy/three.js,googlecreativelab/three.js,daoshengmu/three.js,jeffgoku/three.js,takahirox/three.js,shinate/three.js,WestLangley/three.js,ngokevin/three-dev,takahirox/three.js,daoshengmu/three.js,Hectate/three.js,brianchirls/three.js,satori99/three.js,Liuer/three.js,fanzhanggoogle/three.js,bhouston/three.js,flimshaw/three.js,shanmugamss/three.js-modified,Seagat2011/three.js,Ludobaka/three.js,looeee/three.js,shanmugamss/three.js-modified,stopyransky/three.js,arodic/three.js,jostschmithals/three.js,matgr1/three.js,matgr1/three.js,framelab/three.js,ndebeiss/three.js,stopyransky/three.js,donmccurdy/three.js,rfm1201/rfm.three.js,amakaroff82/three.js,rlugojr/three.js,googlecreativelab/three.js,jeffgoku/three.js,mhoangvslev/data-visualizer,fanzhanggoogle/three.js,Samsung-Blue/three.js,greggman/three.js,agnivade/three.js,satori99/three.js,Samsy/three.js,Samsung-Blue/three.js,TristanVALCKE/three.js,sherousee/three.js,Astrak/three.js,q437634645/three.js,sherousee/three.js,sttz/three.js,RemusMar/three.js,fernandojsg/three.js,Mugen87/three.js,Amritesh/three.js,shanmugamss/three.js-modified,nhalloran/three.js,mese79/three.js,brianchirls/three.js,daoshengmu/three.js,arodic/three.js,stopyransky/three.js,framelab/three.js,xundaokeji/three.js,mhoangvslev/data-visualizer,Hectate/three.js,Samsy/three.js,godlzr/Three.js,matgr1/three.js,Ludobaka/three.js,technohippy/three.js,shinate/three.js,Seagat2011/three.js,yrns/three.js,RemusMar/three.js,jeffgoku/three.js,stanford-gfx/three.js,bhouston/three.js,takahirox/three.js,shanmugamss/three.js-modified,aardgoose/three.js,matgr1/three.js,jayschwa/three.js,arodic/three.js,agnivade/three.js,q437634645/three.js,technohippy/three.js,xundaokeji/three.js,Benjamin-Dobell/three.js,Samsung-Blue/three.js,carlosanunes/three.js,Jozain/three.js,jpweeks/three.js,flimshaw/three.js,Samsy/three.js,arodic/three.js,carlosanunes/three.js,TristanVALCKE/three.js,hsimpson/three.js,arodic/three.js,julapy/three.js,bhouston/three.js,Seagat2011/three.js,jeffgoku/three.js,Aldrien-/three.js,bdysvik/three.js,pailhead/three.js,daoshengmu/three.js,ValtoLibraries/ThreeJS,bhouston/three.js,amakaroff82/three.js,mese79/three.js,agnivade/three.js,jayschwa/three.js,daoshengmu/three.js,Benjamin-Dobell/three.js,fraguada/three.js,fyoudine/three.js,gero3/three.js,carlosanunes/three.js,colombod/three.js,stopyransky/three.js,flimshaw/three.js,bdysvik/three.js,sasha240100/three.js,fanzhanggoogle/three.js,agnivade/three.js,pailhead/three.js,bdysvik/three.js,makc/three.js.fork,Astrak/three.js,mese79/three.js,yrns/three.js,brianchirls/three.js,shanmugamss/three.js-modified,Mugen87/three.js,Seagat2011/three.js,yrns/three.js,flimshaw/three.js,mhoangvslev/data-visualizer,makc/three.js.fork,ondys/three.js,ValtoLibraries/ThreeJS,ValtoLibraries/ThreeJS,spite/three.js,SpinVR/three.js,godlzr/Three.js,xundaokeji/three.js,ValtoLibraries/ThreeJS,godlzr/Three.js,bdysvik/three.js,ondys/three.js,mhoangvslev/data-visualizer,yrns/three.js,jostschmithals/three.js,ikerr/three.js,jeffgoku/three.js,Astrak/three.js,jayschwa/three.js,julapy/three.js,ngokevin/three.js,godlzr/Three.js,SpinVR/three.js,brianchirls/three.js,RemusMar/three.js,opensim-org/three.js,Hectate/three.js,ikerr/three.js,jayschwa/three.js,06wj/three.js | ---
+++
@@ -18,7 +18,7 @@
constructor: AmbientLight,
- isAmbientLight: true,
+ isAmbientLight: true
} );
|
f418d87d1c57b19ac5fb85ab14fa2f57db63ac06 | content/menu-fill.js | content/menu-fill.js | console.log("menu-fill");
var menu_env = $("#menu-env");
var item1 = menu_env_data[0];
var item2 = menu_env_data[1];
function createLinkItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return _a;
}
function createSingleLevelMenuItem (item) {
return $("<li/>").append(createLinkItem(item));
}
function createMultiLevelMenuItem (item) {
item.link = "#";
var _a = createLinkItem(item);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _ul = $("<ul/>", { class: "treeview-menu" });
$.each(item.sub, function (index) {
this.icon = index == 0 ? "fa fa-certificate" : "fa fa-circle-o";
_ul.append(createSingleLevelMenuItem(this));
});
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
$.each(menu_env_data, function (index) {
if (this.sub) {
menu_env.after(createMultiLevelMenuItem(this));
}
else {
menu_env.after(createSingleLevelMenuItem(this));
}
});
| console.log("menu-fill");
var menu_env = $("#menu-env");
function createLinkItem (item) {
var _a = $("<a/>", { href: item.link });
$("<i/>", { class: item.icon }).appendTo(_a);
$("<span/>", { text: " " + item.name }).appendTo(_a);
return _a;
}
function createSingleLevelMenuItem (item) {
return $("<li/>").append(createLinkItem(item));
}
function createMultiLevelMenuItem (item) {
item.link = "#";
var _a = createLinkItem(item);
$("<span/>", { class: "label label-primary pull-right", text: item.sub.length - 1 }).appendTo(_a);
var _ul = $("<ul/>", { class: "treeview-menu" });
$.each(item.sub, function (index) {
this.icon = index == 0 ? "fa fa-certificate" : "fa fa-circle-o";
_ul.append(createSingleLevelMenuItem(this));
});
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
var item_list = []
$.each(menu_env_data, function (index) {
item_list.push(this.sub
? createMultiLevelMenuItem(this)
: createSingleLevelMenuItem(this)
);
});
$.each(item_list.reverse(), function () {
menu_env.after(this);
});
| Fix the order issue of menu items | Fix the order issue of menu items
| JavaScript | mit | vejuhust/yet-another-monitoring-dashboard,vejuhust/yet-another-monitoring-dashboard | ---
+++
@@ -1,10 +1,6 @@
console.log("menu-fill");
var menu_env = $("#menu-env");
-
-
-var item1 = menu_env_data[0];
-var item2 = menu_env_data[1];
function createLinkItem (item) {
@@ -32,11 +28,15 @@
return $("<li/>", { class: "treeview" }).append(_a).append(_ul);
}
+var item_list = []
$.each(menu_env_data, function (index) {
- if (this.sub) {
- menu_env.after(createMultiLevelMenuItem(this));
- }
- else {
- menu_env.after(createSingleLevelMenuItem(this));
- }
+ item_list.push(this.sub
+ ? createMultiLevelMenuItem(this)
+ : createSingleLevelMenuItem(this)
+ );
});
+
+$.each(item_list.reverse(), function () {
+ menu_env.after(this);
+});
+ |
7c42661294649483a283fc6d15866ea044da9bc4 | test/functional/initialize_map.js | test/functional/initialize_map.js | module.exports = {
before : function(client) {
console.log('Setting up functional tests...');
client
.url('http://localhost:3000')
.pause(1000);
},
after : function(client) {
console.log('Closing down functional tests...');
client.end();
},
'HTML body is present' : function(client) {
client.expect.element('body').to.be.present;
},
'Page title is correct' : function(client) {
// expect 'Hurricane Tracker' in the title
// client.expect.element('title').text.to.have.value.that.equals('Hurricane Tracker');
client.assert.title('Hurricane Tracker');
},
'Map is centered on the United States' : function(client) {
},
'Collapsed sidebar panes load' : function(client) {
},
'Universal search bar loads' : function(client) {}
};
| module.exports = {
before : function(client) {
console.log('Setting up functional tests...');
client
.url('http://localhost:3000')
.pause(1000);
},
after : function(client) {
console.log('Closing down functional tests...');
client.end();
},
'Basic HTML loads' : function(client) {
client.expect.element('body').to.be.present;
client.assert.title('Hurricane Tracker');
},
'Specific panes load' : function(client) {
client.expect.element('div#sidebarLeft').to.be.present;
},
'Widgets load' : function(client) {
client.expect.element('div#geocoder_widget').to.be.present;
}
};
| Add tests for panes loading in app. | Add tests for panes loading in app.
| JavaScript | mit | coshx/cmv-app,coshx/cmv-app | ---
+++
@@ -11,22 +11,16 @@
client.end();
},
- 'HTML body is present' : function(client) {
+ 'Basic HTML loads' : function(client) {
client.expect.element('body').to.be.present;
- },
-
- 'Page title is correct' : function(client) {
- // expect 'Hurricane Tracker' in the title
- // client.expect.element('title').text.to.have.value.that.equals('Hurricane Tracker');
client.assert.title('Hurricane Tracker');
},
- 'Map is centered on the United States' : function(client) {
+ 'Specific panes load' : function(client) {
+ client.expect.element('div#sidebarLeft').to.be.present;
},
- 'Collapsed sidebar panes load' : function(client) {
- },
-
- 'Universal search bar loads' : function(client) {}
-
+ 'Widgets load' : function(client) {
+ client.expect.element('div#geocoder_widget').to.be.present;
+ }
}; |
c35453c01ded83c521c1b953a3830185aa9bd74c | lib/rules/mixins-before-declarations.js | lib/rules/mixins-before-declarations.js | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent) {
var depth = 0,
declarationCount = [depth];
parent.traverse( function (item) {
if (item.type === 'ruleset') {
depth++;
declarationCount[depth] = 0;
}
else if (item.type === 'declaration') {
declarationCount[depth]++;
}
else if (item.type === 'include') {
item.forEach('simpleSelector', function (name) {
if (parser.options.exclude.indexOf(name.content[0].content) === -1 && declarationCount[depth] > 0) {
error = {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Mixins should come before declarations',
'severity': parser.severity
};
result = helpers.addUnique(result, error);
}
});
}
});
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'mixins-before-declarations',
'defaults': {
'exclude': [
'breakpoint',
'mq'
]
},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('include', function (node, i, parent) {
var depth = 0,
declarationCount = [depth];
parent.forEach( function (item) {
if (item.type === 'ruleset') {
depth++;
declarationCount[depth] = 0;
}
else if (item.type === 'declaration') {
if (item.first().is('property')) {
var prop = item.first();
if(prop.first().is('ident')) {
declarationCount[depth]++;
}
}
}
else if (item.type === 'include') {
item.forEach('simpleSelector', function (name) {
if (parser.options.exclude.indexOf(name.content[0].content) === -1 && declarationCount[depth] > 0) {
error = {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Mixins should come before declarations',
'severity': parser.severity
};
result = helpers.addUnique(result, error);
}
});
}
});
});
return result;
}
};
| Fix mixin before declaration issues | :bug: Fix mixin before declaration issues
Add check for declaration node content type
Fixes #227
Fixes #230
| JavaScript | mit | sktt/sass-lint,srowhani/sass-lint,DanPurdy/sass-lint,srowhani/sass-lint,sasstools/sass-lint,donabrams/sass-lint,ngryman/sass-lint,Dru89/sass-lint,bgriffith/sass-lint,flacerdk/sass-lint,benthemonkey/sass-lint,sasstools/sass-lint | ---
+++
@@ -18,13 +18,22 @@
var depth = 0,
declarationCount = [depth];
- parent.traverse( function (item) {
+ parent.forEach( function (item) {
if (item.type === 'ruleset') {
depth++;
declarationCount[depth] = 0;
}
else if (item.type === 'declaration') {
- declarationCount[depth]++;
+ if (item.first().is('property')) {
+
+ var prop = item.first();
+
+ if(prop.first().is('ident')) {
+
+ declarationCount[depth]++;
+
+ }
+ }
}
else if (item.type === 'include') {
item.forEach('simpleSelector', function (name) { |
1836d5b36ad6185e1152de0b11be07c2f10d629f | webpack.config.babel.js | webpack.config.babel.js | import Bootstrap from 'bootstrap-webpack-plugin'
import Path from 'path'
const path = Path.join.bind(null, __dirname)
const outputDir = path(`build`)
export default {
entry: {
playground: `./examples/playground/main.js`,
multipleTriggers: `./examples/multiple-triggers/main.js`,
},
output: {
path: outputDir,
filename: `[name].js`
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: [`babel`]},
{ test: /\.css$/, exclude: /node_modules/, loaders: [ `style`, `css`, `cssnext` ]},
],
},
devtool: `source-map`,
devServer: {
contentBase: outputDir,
},
plugins: [Bootstrap({})],
}
| import Bootstrap from 'bootstrap-webpack-plugin'
import Path from 'path'
const path = Path.join.bind(null, __dirname)
const outputDirName = `build`
const outputDir = path(outputDirName)
export default {
entry: {
playground: `./examples/playground/main.js`,
multipleTriggers: `./examples/multiple-triggers/main.js`,
},
output: {
path: outputDir,
filename: `[name].js`
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: [`babel`]},
{ test: /\.css$/, exclude: /node_modules/, loaders: [ `style`, `css`, `cssnext` ]},
],
},
devtool: `source-map`,
devServer: {
contentBase: outputDir,
},
plugins: [Bootstrap({})],
}
| Make a part of webpack config consistent with gh-pages branch variant for simpler future conflict resolutions. | Make a part of webpack config consistent with gh-pages branch variant for simpler future conflict resolutions.
| JavaScript | mit | gregory90/react-popover,littlebits/react-popover,clara-labs/react-popover | ---
+++
@@ -4,7 +4,8 @@
const path = Path.join.bind(null, __dirname)
-const outputDir = path(`build`)
+const outputDirName = `build`
+const outputDir = path(outputDirName)
export default {
entry: { |
02be6197ffec6c3f6d0214617c815423c6b8c4d4 | voice/proxy-call.js | voice/proxy-call.js | /* Voice Tutorial 4: Making a Proxy Call
API Reference: https://docs.nexmo.com/voice/voice-api/api-reference
*/
'use strict';
require('dotenv').config({path: __dirname + '/../.env'});
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const server = app.listen(process.env.PORT || 4004, () => {
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});
app.get('/proxy-call', (req, res) => {
const ncco = [
{
'action': 'connect',
'eventUrl': ['https://18627fc4.ngrok.io/event'],
'timeout': 45, // the default is 60
'from': process.env.FROM_NUMBER,
'endpoint': [
{
'type': 'phone',
'number': process.env.TO_NUMBER // forwarding to this real number
}
]
}
];
res.json(ncco);
});
app.post('/event', (req, res) => {
console.log(req.body);
res.status(204).end();
});
| /* Voice Tutorial 4: Making a Proxy Call
API Reference: https://docs.nexmo.com/voice/voice-api/api-reference
*/
'use strict';
require('dotenv').config({path: __dirname + '/../.env'});
const app = require('express')();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const NEXMO_FROM_NUMBER = process.env.NEXMO_FROM_NUMBER;
const NEXMO_TO_NUMBER = process.env.NEXMO_TO_NUMBER;
const server = app.listen(process.env.PORT || 4004, () => {
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});
app.get('/proxy-call', (req, res) => {
const ncco = [
{
'action': 'connect',
'eventUrl': ['https://18627fc4.ngrok.io/event'],
'timeout': 45, // the default is 60
'from': NEXMO_TO_NUMBER,
'endpoint': [
{
'type': 'phone',
'number': NEXMO_FROM_NUMBER // forwarding to this real number
}
]
}
];
res.json(ncco);
});
app.post('/event', (req, res) => {
console.log(req.body);
res.status(204).end();
});
| Use `NEXMO_` prefixes in proxy example | Use `NEXMO_` prefixes in proxy example | JavaScript | mit | nexmo-community/nexmo-node-quickstart,nexmo-community/nexmo-node-quickstart | ---
+++
@@ -9,6 +9,9 @@
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
+const NEXMO_FROM_NUMBER = process.env.NEXMO_FROM_NUMBER;
+const NEXMO_TO_NUMBER = process.env.NEXMO_TO_NUMBER;
+
const server = app.listen(process.env.PORT || 4004, () => {
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});
@@ -19,11 +22,11 @@
'action': 'connect',
'eventUrl': ['https://18627fc4.ngrok.io/event'],
'timeout': 45, // the default is 60
- 'from': process.env.FROM_NUMBER,
+ 'from': NEXMO_TO_NUMBER,
'endpoint': [
{
'type': 'phone',
- 'number': process.env.TO_NUMBER // forwarding to this real number
+ 'number': NEXMO_FROM_NUMBER // forwarding to this real number
}
]
} |
432b6421bbf4d49d22747bb15f1d0d741c6b4265 | src/config.js | src/config.js | /* global process */
const nodeEnv = (process.env.NODE_ENV || 'development');
export default {
nodeEnv,
logReduxActions: () => Boolean(process.env.LOG_REDUX_ACTIONS),
warnOnDroppedErrors: nodeEnv === 'development',
stubSVGs: nodeEnv === 'test',
firebaseApp: process.env.FIREBASE_APP || 'blistering-inferno-9896',
feedbackUrl: 'https://gitreports.com/issue/popcodeorg/popcode',
bugsnagApiKey: '400134511e506b91ae6c24ac962af962',
gitRevision: process.env.GIT_REVISION,
};
| /* global process */
const nodeEnv = (process.env.NODE_ENV || 'development');
export default {
nodeEnv,
logReduxActions: () => process.env.LOG_REDUX_ACTIONS === 'true',
warnOnDroppedErrors: nodeEnv === 'development',
stubSVGs: nodeEnv === 'test',
firebaseApp: process.env.FIREBASE_APP || 'blistering-inferno-9896',
feedbackUrl: 'https://gitreports.com/issue/popcodeorg/popcode',
bugsnagApiKey: '400134511e506b91ae6c24ac962af962',
gitRevision: process.env.GIT_REVISION,
};
| Fix check for LOG_REDUX_ACTIONS environment variable | Fix check for LOG_REDUX_ACTIONS environment variable
Right now it’s on in production! : 0
| JavaScript | mit | popcodeorg/popcode,popcodeorg/popcode,jwang1919/popcode,jwang1919/popcode,outoftime/learnpad,jwang1919/popcode,popcodeorg/popcode,popcodeorg/popcode,jwang1919/popcode,outoftime/learnpad | ---
+++
@@ -4,7 +4,7 @@
export default {
nodeEnv,
- logReduxActions: () => Boolean(process.env.LOG_REDUX_ACTIONS),
+ logReduxActions: () => process.env.LOG_REDUX_ACTIONS === 'true',
warnOnDroppedErrors: nodeEnv === 'development',
stubSVGs: nodeEnv === 'test',
|
1bf0f61c03478a1e2277fecbdf770bcb2a920041 | src/notebook/api/kernel.js | src/notebook/api/kernel.js | import {
createControlSubject,
createStdinSubject,
createIOPubSubject,
createShellSubject,
} from 'enchannel-zmq-backend';
import * as fs from 'fs';
import * as uuid from 'uuid';
import { launch } from 'spawnteract';
export function launchKernel(kernelSpecName, spawnOptions) {
return launch(kernelSpecName, spawnOptions)
.then(c => {
const kernelConfig = c.config;
const spawn = c.spawn;
const connectionFile = c.connectionFile;
const identity = uuid.v4();
const channels = {
shell: createShellSubject(identity, kernelConfig),
iopub: createIOPubSubject(identity, kernelConfig),
control: createControlSubject(identity, kernelConfig),
stdin: createStdinSubject(identity, kernelConfig),
};
return {
channels,
connectionFile,
spawn,
};
});
}
export function shutdownKernel(channels, spawn, connectionFile) {
if (channels) {
channels.shell.complete();
channels.iopub.complete();
channels.stdin.complete();
}
if (spawn) {
spawn.stdin.destroy();
spawn.stdout.destroy();
spawn.stderr.destroy();
spawn.kill('SIGKILL');
}
if (connectionFile) {
fs.unlinkSync(connectionFile);
}
}
| import {
createControlSubject,
createStdinSubject,
createIOPubSubject,
createShellSubject,
} from 'enchannel-zmq-backend';
import * as fs from 'fs';
import * as uuid from 'uuid';
import { launch } from 'spawnteract';
export function launchKernel(kernelSpecName, spawnOptions) {
return launch(kernelSpecName, spawnOptions)
.then(c => {
const kernelConfig = c.config;
const spawn = c.spawn;
const connectionFile = c.connectionFile;
const identity = uuid.v4();
const channels = {
shell: createShellSubject(identity, kernelConfig),
iopub: createIOPubSubject(identity, kernelConfig),
control: createControlSubject(identity, kernelConfig),
stdin: createStdinSubject(identity, kernelConfig),
};
return {
channels,
connectionFile,
spawn,
};
});
}
export function shutdownKernel(channels, spawn, connectionFile) {
if (channels) {
channels.shell.complete();
channels.iopub.complete();
channels.stdin.complete();
channels.control.complete();
}
if (spawn) {
spawn.stdin.destroy();
spawn.stdout.destroy();
spawn.stderr.destroy();
spawn.kill('SIGKILL');
}
if (connectionFile) {
fs.unlinkSync(connectionFile);
}
}
| Complete the control channel too. | Complete the control channel too.
| JavaScript | bsd-3-clause | rgbkrk/nteract,nteract/nteract,jdfreder/nteract,jdetle/nteract,nteract/nteract,0u812/nteract,rgbkrk/nteract,jdfreder/nteract,rgbkrk/nteract,0u812/nteract,captainsafia/nteract,nteract/nteract,nteract/nteract,jdetle/nteract,rgbkrk/nteract,jdfreder/nteract,0u812/nteract,nteract/composition,captainsafia/nteract,temogen/nteract,temogen/nteract,jdetle/nteract,0u812/nteract,captainsafia/nteract,nteract/nteract,captainsafia/nteract,nteract/composition,temogen/nteract,rgbkrk/nteract,jdfreder/nteract,jdetle/nteract,nteract/composition | ---
+++
@@ -35,6 +35,7 @@
channels.shell.complete();
channels.iopub.complete();
channels.stdin.complete();
+ channels.control.complete();
}
if (spawn) {
spawn.stdin.destroy(); |
15262b0348636af809d6c4b9240428412a367a96 | gulpfile.js/tasks/production.js | gulpfile.js/tasks/production.js | var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var os = require('os')
var path = require('path')
var productionTask = function(cb) {
global.production = true
// Build to a temporary directory, then move compiled files as a last step
PATH_CONFIG.finalDest = PATH_CONFIG.dest
PATH_CONFIG.dest = path.join(os.tmpdir(), 'gulp-starter')
var tasks = getEnabledTasks('production')
var rev = TASK_CONFIG.production.rev ? 'rev': false
var static = TASK_CONFIG.static ? 'static' : false
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, rev, 'size-report', static, 'replaceFiles', cb)
}
gulp.task('build', productionTask)
module.exports = productionTask
| var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var os = require('os')
var path = require('path')
var productionTask = function(cb) {
global.production = true
// Build to a temporary directory, then move compiled files as a last step
PATH_CONFIG.finalDest = PATH_CONFIG.dest
PATH_CONFIG.dest = PATH_CONFIG.temp
? path.join(process.env.PWD, PATH_CONFIG.temp)
: path.join(os.tmpdir(), 'gulp-starter');
var tasks = getEnabledTasks('production')
var rev = TASK_CONFIG.production.rev ? 'rev': false
var static = TASK_CONFIG.static ? 'static' : false
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, rev, 'size-report', static, 'replaceFiles', cb)
}
gulp.task('build', productionTask)
module.exports = productionTask
| Fix bug when trying to "cross-link" between multiple devices | Fix bug when trying to "cross-link" between multiple devices
| JavaScript | mit | jakefleming/mezzotent,jakefleming/mezzotent,vigetlabs/gulp-starter,jakefleming/mezzotent,greypants/gulp-starter,greypants/gulp-starter,vigetlabs/gulp-starter,jakefleming/mezzotent,greypants/gulp-starter,greypants/gulp-starter,vigetlabs/gulp-starter,vigetlabs/gulp-starter | ---
+++
@@ -9,7 +9,9 @@
// Build to a temporary directory, then move compiled files as a last step
PATH_CONFIG.finalDest = PATH_CONFIG.dest
- PATH_CONFIG.dest = path.join(os.tmpdir(), 'gulp-starter')
+ PATH_CONFIG.dest = PATH_CONFIG.temp
+ ? path.join(process.env.PWD, PATH_CONFIG.temp)
+ : path.join(os.tmpdir(), 'gulp-starter');
var tasks = getEnabledTasks('production')
var rev = TASK_CONFIG.production.rev ? 'rev': false |
da97d8885b8a9145c933d7cce7c713446f817f6c | src/components/views/messages/UnknownBody.js | src/components/views/messages/UnknownBody.js | /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
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.
*/
import React from "react";
export default ({mxEvent}) => {
const text = mxEvent.getContent().body;
return (
<span className="mx_UnknownBody">
{ text }
</span>
);
};
| /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2020 The Matrix.org Foundation C.I.C.
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.
*/
import React, {forwardRef} from "react";
export default forwardRef(({mxEvent}, ref) => {
const text = mxEvent.getContent().body;
return (
<span className="mx_UnknownBody" ref={ref}>
{ text }
</span>
);
});
| Fix react error about functional components can't take props | Fix react error about functional components can't take props
| JavaScript | apache-2.0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -15,13 +15,13 @@
limitations under the License.
*/
-import React from "react";
+import React, {forwardRef} from "react";
-export default ({mxEvent}) => {
+export default forwardRef(({mxEvent}, ref) => {
const text = mxEvent.getContent().body;
return (
- <span className="mx_UnknownBody">
+ <span className="mx_UnknownBody" ref={ref}>
{ text }
</span>
);
-};
+}); |
385658e20f1f513a77ce34758d0e41f197a8a4ba | core/workers.js | core/workers.js | (function() {
'use strict';
self.addEventListener('message', function(obj) {
window.setInterval(function() {
console.log('worker: ' + obj.existence);
var limit = obj.existence - 1;
if (obj.isDead !== undefined) {
obj.isDead(limit);
}
if (obj.setExistence !== undefined) {
obj.setExistence(limit);
}
}, 1000);
}, false);
}());
| (function() {
'use strict';
function calculateDeath(dead) {
setInterval(function() {
var limit = dead - 1;
if (limit === 0) {
self.postMessage(limit);
}
return (dead = limit);
}, 1000);
}
self.addEventListener('message', function(e) {
calculateDeath(e.data.ex);
}, false);
}());
| Improve web worker with new dead calculate | Improve web worker with new dead calculate
| JavaScript | mit | AlbertoFuente/lab,AlbertoFuente/lab | ---
+++
@@ -1,16 +1,17 @@
(function() {
'use strict';
- self.addEventListener('message', function(obj) {
- window.setInterval(function() {
- console.log('worker: ' + obj.existence);
- var limit = obj.existence - 1;
- if (obj.isDead !== undefined) {
- obj.isDead(limit);
+ function calculateDeath(dead) {
+ setInterval(function() {
+ var limit = dead - 1;
+ if (limit === 0) {
+ self.postMessage(limit);
}
- if (obj.setExistence !== undefined) {
- obj.setExistence(limit);
- }
+ return (dead = limit);
}, 1000);
+ }
+
+ self.addEventListener('message', function(e) {
+ calculateDeath(e.data.ex);
}, false);
}()); |
45df2186d52482b810fee9ef71179d46e4886ff8 | app/components/Settings/components/option.js | app/components/Settings/components/option.js | import React from 'react';
import PropTypes from 'prop-types';
import { InputGroup, Intent } from '@blueprintjs/core';
const Option = ({ intent, title, type, value, unit, onChange, inputStyles }) => (
<label className="pt-label pt-inline">
<div className="d-inline-block w-exact-225">{title} {unit && `(${unit})`}</div>
{type === 'number' ? (
<InputGroup
min="1"
type="number"
intent={value ? intent : Intent.DANGER}
value={value}
onChange={(e) => {
const val = +e.target.value;
if (!Option.isValidNumber(val)) return;
onChange(val);
}}
className={inputStyles}
/>
) : (
<InputGroup
type={type}
intent={intent}
value={value}
onChange={onChange}
className={inputStyles}
/>
)}
</label>
);
Option.propTypes = {
intent: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
unit: PropTypes.string,
onChange: PropTypes.func.isRequired,
inputStyles: PropTypes.string
};
Option.isValidNumber = (n) => n % 1 === 0;
export default Option;
| import React from 'react';
import PropTypes from 'prop-types';
import { InputGroup } from '@blueprintjs/core';
const Option = ({ intent, title, type, value, unit, onChange, inputStyles }) => (
<label className="pt-label pt-inline">
<div className="d-inline-block w-exact-225">{title} {unit && `(${unit})`}</div>
{type === 'number' ? (
<InputGroup
min="0"
type="number"
intent={intent}
value={value}
onChange={(e) => {
const val = +e.target.value;
if (!Option.isValidNumber(val)) return;
onChange(val);
}}
className={inputStyles}
/>
) : (
<InputGroup
type={type}
intent={intent}
value={value}
onChange={onChange}
className={inputStyles}
/>
)}
</label>
);
Option.propTypes = {
intent: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]).isRequired,
unit: PropTypes.string,
onChange: PropTypes.func.isRequired,
inputStyles: PropTypes.string
};
Option.isValidNumber = (n) => n % 1 === 0;
export default Option;
| Remove intent warning and allow zero values for settings | Remove intent warning and allow zero values for settings
| JavaScript | mit | builtwithluv/ZenFocus,builtwithluv/ZenFocus | ---
+++
@@ -1,15 +1,15 @@
import React from 'react';
import PropTypes from 'prop-types';
-import { InputGroup, Intent } from '@blueprintjs/core';
+import { InputGroup } from '@blueprintjs/core';
const Option = ({ intent, title, type, value, unit, onChange, inputStyles }) => (
<label className="pt-label pt-inline">
<div className="d-inline-block w-exact-225">{title} {unit && `(${unit})`}</div>
{type === 'number' ? (
<InputGroup
- min="1"
+ min="0"
type="number"
- intent={value ? intent : Intent.DANGER}
+ intent={intent}
value={value}
onChange={(e) => {
const val = +e.target.value; |
994ab2e64b18199d9d0acd34de8cd442aff1841d | LockServer/controllers/health-controller.js | LockServer/controllers/health-controller.js | const lock = require('./lock-controller');
const utils = require('./utils');
function notify(text) {
console.info(text);
utils.notifySlack({
channel: '#alerts',
text: text,
username: 'Lock System Monitoring'
});
}
exports.checkHealth = function() {
if (!lock.isIndoorScannerHealthy()) {
notify('Indoor BLE scanner is down');
}
if (!lock.isOutdoorScannerHealthy()) {
notify('Outdoor BLE scanner is down');
}
utils.get('http://192.168.0.6:8080/set(0,0,0)', function(err) {
notify('LED controller is down');
}, 1000);
utils.get('http://192.168.0.3:8080/status', function(err) {
notify('Lock controller is down');
}, 1000);
}
| const lock = require('./lock-controller');
const utils = require('./utils');
function notify(text) {
console.info(text);
utils.notifySlack({
channel: '#alerts',
text: text,
username: 'Lock System Monitoring'
});
}
exports.checkHealth = function() {
if (!lock.isIndoorScannerHealthy()) {
notify('Indoor BLE scanner is down');
}
if (!lock.isOutdoorScannerHealthy()) {
notify('Outdoor BLE scanner is down');
}
utils.get('http://192.168.0.6:8080/set(0,0,0)', function(err) {
notify('LED controller is down');
}, 3000);
utils.get('http://192.168.0.3:8080/status', function(err) {
notify('Lock controller is down');
}, 3000);
}
| Increase timeout to 3 sec for health check. | Increase timeout to 3 sec for health check.
| JavaScript | mit | straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock,straylightlabs/hands-free-lock | ---
+++
@@ -19,9 +19,9 @@
}
utils.get('http://192.168.0.6:8080/set(0,0,0)', function(err) {
notify('LED controller is down');
- }, 1000);
+ }, 3000);
utils.get('http://192.168.0.3:8080/status', function(err) {
notify('Lock controller is down');
- }, 1000);
+ }, 3000);
}
|
cb592c2306fbe401c13917a34f0813b5bcb5e04c | src/router.js | src/router.js | var express = require('express');
var parseCommand = require('./parse-command');
var router = express.Router();
router.post('/', (req, res) => {
parseCommand(req)
.then(res.send);
});
module.exports = router;
| const express = require('express');
const winston = require('winston');
const parseCommand = require('./parse-command');
const router = express.Router();
router.post('/', (req, res) => {
parseCommand(req)
.then((text) => {
res.status(200).send(text);
})
.catch((err) => {
winston.error(err);
res.sendStatus(500);
});
});
module.exports = router;
| Add general handling of any rejections | feat: Add general handling of any rejections
| JavaScript | mit | NSAppsTeam/nickel-bot | ---
+++
@@ -1,11 +1,18 @@
-var express = require('express');
-var parseCommand = require('./parse-command');
-
-var router = express.Router();
+const express = require('express');
+const winston = require('winston');
+const parseCommand = require('./parse-command');
+const router = express.Router();
router.post('/', (req, res) => {
+
parseCommand(req)
- .then(res.send);
+ .then((text) => {
+ res.status(200).send(text);
+ })
+ .catch((err) => {
+ winston.error(err);
+ res.sendStatus(500);
+ });
});
module.exports = router; |
2df12a10c390da8bf0e886b7717b70126508aa41 | web/src/scripts/controller/CartOauthCtrl.js | web/src/scripts/controller/CartOauthCtrl.js | 'use strict';
module.exports = function ($scope, $location, $service) {
console.log('CartOauthCtrl');
$scope.hasBeenInited = false;
$scope.startOauthProcess = function() {
$service.getOauthUrl().then(function(result) {
window.location.href = result.url;
});
};
$service.isBlogAuthed().then(function(result) {
if (result.isAuthed) {
$location.url('/master');
} else {
$scope.hasBeenInited = true;
}
});
}; | 'use strict';
module.exports = function ($scope, $location, $accessService) {
console.log('CartOauthCtrl');
$scope.hasBeenInited = false;
$scope.startOauthProcess = function() {
$accessService.getOauthUrl().then(function(result) {
window.location.href = result.url;
});
};
$accessService.isBlogAuthed().then(function(result) {
var isMaster = $accessService.isMaster();
if (result.isAuthed && isMaster) {
$location.url('/master');
} else if (result.isAuthed && !isMaster) {
$location.url('/login');
} else {
$scope.hasBeenInited = true;
}
});
}; | Fix oauth page response, redirect user to login page, if site already authed, not throw user into error page. | Fix oauth page response, redirect user to login page, if site already authed, not throw user into error page.
| JavaScript | mit | agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart | ---
+++
@@ -1,19 +1,22 @@
'use strict';
-module.exports = function ($scope, $location, $service) {
+module.exports = function ($scope, $location, $accessService) {
console.log('CartOauthCtrl');
$scope.hasBeenInited = false;
$scope.startOauthProcess = function() {
- $service.getOauthUrl().then(function(result) {
+ $accessService.getOauthUrl().then(function(result) {
window.location.href = result.url;
});
};
- $service.isBlogAuthed().then(function(result) {
- if (result.isAuthed) {
+ $accessService.isBlogAuthed().then(function(result) {
+ var isMaster = $accessService.isMaster();
+ if (result.isAuthed && isMaster) {
$location.url('/master');
+ } else if (result.isAuthed && !isMaster) {
+ $location.url('/login');
} else {
$scope.hasBeenInited = true;
} |
768ea00e7bee2b9de34d07b21fd18813cbdb6f2b | src/providers/weather/air-pollution-service.js | src/providers/weather/air-pollution-service.js | import { apiConstants, apiProvidersConst, httpService, newsModelFactory } from '../../common/common.js';
export default class AirPollution {
static getSummary() {
let options = httpService.clone(apiConstants.airPollution);
options.path = options.path.replace('{0}', options.token);
return httpService.performGetRequest(options, dataTransformer);
function dataTransformer(data) {
return [
newsModelFactory.get({
title: 'Air pollution',
info: constructInfo(data),
url: null,
image: null,
dateTime: new Date().toDateString(),
provider: apiProvidersConst.AIR_POLLUTION.id
})
];
}
function constructInfo(data) {
const itemSeparator = ' ',
lineSeparator = '\r\n';
let info = '';
if (data && data.table && data.table.values) {
info += 'current: ' + data.sensor.P1.current + lineSeparator;
data.table.values.reverse().forEach((model) => {
info += formatDate(new Date(model.time * 1000)) + ' ' + model.P1 + lineSeparator;
});
}
return info;
function formatDate(dateValue) {
return dateValue.getDate().toString() + '-' + (dateValue.getMonth() + 1).toString();
}
}
}
}
| import { apiConstants, apiProvidersConst, httpService, newsModelFactory } from '../../common/common.js';
export default class AirPollution {
static getSummary() {
let options = httpService.clone(apiConstants.airPollution);
options.path = options.path.replace('{0}', options.token);
return httpService.performGetRequest(options, dataTransformer);
function dataTransformer(data) {
return [
newsModelFactory.get({
title: 'Air pollution',
info: constructInfo(data),
url: null,
image: null,
dateTime: new Date().toDateString(),
provider: apiProvidersConst.AIR_POLLUTION.id
})
];
}
function constructInfo(data) {
const itemSeparator = ' ',
valueSeparator = '/',
lineSeparator = '\r\n';
let info = '';
if (data && data.table && data.table.values) {
info += 'current: ' +
data.sensor.P1.current +
valueSeparator +
data.sensor.P2.current +
lineSeparator;
data.table.values.reverse().forEach((model) => {
info += formatDate(new Date(model.time * 1000)) +
itemSeparator +
model.P1 +
valueSeparator +
model.P2 +
lineSeparator;
});
}
return info;
function formatDate(dateValue) {
return dateValue.getDate().toString() + '-' + (dateValue.getMonth() + 1).toString();
}
}
}
}
| Enhance air pollution service formatting | Enhance air pollution service formatting
| JavaScript | mit | AlexanderAntov/scraper-js,AlexanderAntov/scraper-js | ---
+++
@@ -21,12 +21,22 @@
function constructInfo(data) {
const itemSeparator = ' ',
+ valueSeparator = '/',
lineSeparator = '\r\n';
let info = '';
if (data && data.table && data.table.values) {
- info += 'current: ' + data.sensor.P1.current + lineSeparator;
+ info += 'current: ' +
+ data.sensor.P1.current +
+ valueSeparator +
+ data.sensor.P2.current +
+ lineSeparator;
data.table.values.reverse().forEach((model) => {
- info += formatDate(new Date(model.time * 1000)) + ' ' + model.P1 + lineSeparator;
+ info += formatDate(new Date(model.time * 1000)) +
+ itemSeparator +
+ model.P1 +
+ valueSeparator +
+ model.P2 +
+ lineSeparator;
});
}
return info; |
f83b13af8fa49a500fd554a53ba800f999be5919 | lib/copy-sync/copy-file-sync.js | lib/copy-sync/copy-file-sync.js | var fs = require('graceful-fs')
var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)
function copyFileSync (srcFile, destFile, options) {
var clobber = options.clobber
var preserveTimestamps = options.preserveTimestamps
if (fs.existsSync(destFile)) {
if (clobber) {
fs.chmodSync(destFile, parseInt('777', 8))
fs.unlinkSync(destFile)
} else {
throw Error('EEXIST')
}
}
var fdr = fs.openSync(srcFile, 'r')
var stat = fs.fstatSync(fdr)
var fdw = fs.openSync(destFile, 'w', stat.mode)
var bytesRead = 1
var pos = 0
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
fs.writeSync(fdw, _buff, 0, bytesRead)
pos += bytesRead
}
if (preserveTimestamps) {
fs.futimesSync(fdw, stat.atime, stat.mtime)
}
fs.closeSync(fdr)
fs.closeSync(fdw)
}
module.exports = copyFileSync
| var fs = require('graceful-fs')
var BUF_LENGTH = 64 * 1024
var _buff = new Buffer(BUF_LENGTH)
function copyFileSync (srcFile, destFile, options) {
var clobber = options.clobber
var preserveTimestamps = options.preserveTimestamps
if (fs.existsSync(destFile)) {
if (clobber) {
fs.chmodSync(destFile, parseInt('777', 8))
fs.unlinkSync(destFile)
} else {
var err = new Error('EEXIST: ' + destFile + ' already exists.')
err.code = 'EEXIST'
err.errno = -17
err.path = destFile
throw err
}
}
var fdr = fs.openSync(srcFile, 'r')
var stat = fs.fstatSync(fdr)
var fdw = fs.openSync(destFile, 'w', stat.mode)
var bytesRead = 1
var pos = 0
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
fs.writeSync(fdw, _buff, 0, bytesRead)
pos += bytesRead
}
if (preserveTimestamps) {
fs.futimesSync(fdw, stat.atime, stat.mtime)
}
fs.closeSync(fdr)
fs.closeSync(fdw)
}
module.exports = copyFileSync
| Improve EEXIST error message for copySync | Improve EEXIST error message for copySync
| JavaScript | mit | jprichardson/node-fs-extra | ---
+++
@@ -12,7 +12,11 @@
fs.chmodSync(destFile, parseInt('777', 8))
fs.unlinkSync(destFile)
} else {
- throw Error('EEXIST')
+ var err = new Error('EEXIST: ' + destFile + ' already exists.')
+ err.code = 'EEXIST'
+ err.errno = -17
+ err.path = destFile
+ throw err
}
}
|
45ab550d51fddf10526996423e1bcd70169c3e6f | benchmark/sync-vs-async.js | benchmark/sync-vs-async.js | #!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000
};
const bench = noOfBytes => Promise.resolve().then(async () => {
const results = {};
console.log(`Generating ${prettyBytes(noOfBytes)} of random binary data...`);
const randomBytes = crypto.randomBytes(noOfBytes);
console.log('Encoding sync...');
timer.reset();
const randomBytesBase64 = randomBytes.toString('base64');
results.encodeSync = timer.duration();
console.log('Decoding sync...');
timer.reset();
Buffer.from(randomBytesBase64, 'base64').toString();
results.decodeSync = timer.duration();
console.log('Encoding async...');
timer.reset();
await b64(randomBytes);
results.encodeAsync = timer.duration();
console.log('Decoding async...');
timer.reset();
await b64(randomBytesBase64);
results.decodeAsync = timer.duration();
console.log();
return results;
});
(async () => {
await bench(10000)
await bench(100000);
await bench(1000000);
await bench(10000000);
})();
| #!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const bytesToBenchmark = [10000, 100000, 1000000, 10000000];
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000
};
const bench = noOfBytes => Promise.resolve().then(async () => {
const results = {};
console.log(`Generating ${prettyBytes(noOfBytes)} of random binary data...`);
const randomBytes = crypto.randomBytes(noOfBytes);
console.log('Encoding sync...');
timer.reset();
const randomBytesBase64 = randomBytes.toString('base64');
results.encodeSync = timer.duration();
console.log('Decoding sync...');
timer.reset();
Buffer.from(randomBytesBase64, 'base64').toString();
results.decodeSync = timer.duration();
console.log('Encoding async...');
timer.reset();
await b64(randomBytes);
results.encodeAsync = timer.duration();
console.log('Decoding async...');
timer.reset();
await b64(randomBytesBase64);
results.decodeAsync = timer.duration();
console.log();
return results;
});
(async () => {
for(noOfBytes of bytesToBenchmark) {
await bench(noOfBytes);
}
})();
| Use array for benchmark bytes | Use array for benchmark bytes
| JavaScript | mit | lukechilds/base64-async | ---
+++
@@ -3,6 +3,8 @@
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
+
+const bytesToBenchmark = [10000, 100000, 1000000, 10000000];
const timer = {
reset: () => timer.startTime = process.hrtime(),
@@ -40,8 +42,7 @@
});
(async () => {
- await bench(10000)
- await bench(100000);
- await bench(1000000);
- await bench(10000000);
+ for(noOfBytes of bytesToBenchmark) {
+ await bench(noOfBytes);
+ }
})(); |
cfe552eaf0b7b036a7343da97080bf2660c03866 | src/helpers/junk_drawer.js | src/helpers/junk_drawer.js | import { decamelizeKeys } from 'humps'
import store from '../../store'
import { saveProfile } from '../../actions/profile'
export function preferenceToggleChanged(obj) {
const newObj = { ...obj }
if (newObj.hasOwnProperty('is_public')) {
if (!newObj.is_public) {
newObj.has_reposting_enabled = false
newObj.has_sharing_enabled = false
}
}
store.dispatch(saveProfile(decamelizeKeys(newObj)))
}
| import { decamelizeKeys } from 'humps'
import store from '../store'
import { saveProfile } from '../actions/profile'
export function preferenceToggleChanged(obj) {
const newObj = { ...obj }
if (newObj.hasOwnProperty('is_public')) {
if (!newObj.is_public) {
newObj.has_reposting_enabled = false
newObj.has_sharing_enabled = false
}
}
store.dispatch(saveProfile(decamelizeKeys(newObj)))
}
| Fix a borked import statement | Fix a borked import statement | JavaScript | mit | ello/webapp,ello/webapp,ello/webapp | ---
+++
@@ -1,6 +1,6 @@
import { decamelizeKeys } from 'humps'
-import store from '../../store'
-import { saveProfile } from '../../actions/profile'
+import store from '../store'
+import { saveProfile } from '../actions/profile'
export function preferenceToggleChanged(obj) {
const newObj = { ...obj } |
ef93b58cecc433382f125702934e3ed30d995eb3 | www/android/FileSystem.js | www/android/FileSystem.js | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
FILESYSTEM_PROTOCOL = "cdvfile";
module.exports = {
__format__: function(fullPath, nativeUrl) {
var path = '/' + this.name + '/' + encodeURI(fullPath);
path = path.replace('//','/');
var ret = FILESYSTEM_PROTOCOL + '://localhost' + path;
var m = /\?.*/.exec(nativeUrl);
if (m) {
ret += m[0];
}
return ret;
}
};
| /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
FILESYSTEM_PROTOCOL = "cdvfile";
module.exports = {
__format__: function(fullPath, nativeUrl) {
var path;
var contentUrlMatch = /^content:\/\//.exec(nativeUrl);
if (contentUrlMatch) {
// When available, use the path from a native content URL, which was already encoded by Android.
// This is necessary because JavaScript's encodeURI() does not encode as many characters as
// Android, which can result in permission exceptions when the encoding of a content URI
// doesn't match the string for which permission was originally granted.
path = nativeUrl.substring(contentUrlMatch[0].length - 1);
} else {
path = encodeURI(fullPath);
if (!/^\//.test(path)) {
path = '/' + path;
}
var m = /\?.*/.exec(nativeUrl);
if (m) {
path += m[0];
}
}
return FILESYSTEM_PROTOCOL + '://localhost/' + this.name + path;
}
};
| Fix permission errors due to URI encoding inconsistency on Android | CB-9891: Fix permission errors due to URI encoding inconsistency on Android
| JavaScript | apache-2.0 | tripodsan/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,tripodsan/cordova-plugin-file,macdonst/cordova-plugin-file,apache/cordova-plugin-file,macdonst/cordova-plugin-file,mnill/cordova-plugin-file,sanmeranam/cordova-file,cadenasgmbh/cordova-plugin-file,mnill/cordova-plugin-file,GenusAS/cordova-plugin-file,purplecabbage/cordova-plugin-file,purplecabbage/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,macdonst/cordova-plugin-file,purplecabbage/cordova-plugin-file,cadenasgmbh/cordova-plugin-file,sanmeranam/cordova-file,mnill/cordova-plugin-file,starquake/cordova-plugin-file,sanmeranam/cordova-file,tripodsan/cordova-plugin-file,purplecabbage/cordova-plugin-file,GenusAS/cordova-plugin-file,GenusAS/cordova-plugin-file,tripodsan/cordova-plugin-file,sanmeranam/cordova-file,GenusAS/cordova-plugin-file,mnill/cordova-plugin-file,starquake/cordova-plugin-file,apache/cordova-plugin-file,macdonst/cordova-plugin-file | ---
+++
@@ -23,14 +23,27 @@
module.exports = {
__format__: function(fullPath, nativeUrl) {
- var path = '/' + this.name + '/' + encodeURI(fullPath);
- path = path.replace('//','/');
- var ret = FILESYSTEM_PROTOCOL + '://localhost' + path;
- var m = /\?.*/.exec(nativeUrl);
- if (m) {
- ret += m[0];
+ var path;
+ var contentUrlMatch = /^content:\/\//.exec(nativeUrl);
+ if (contentUrlMatch) {
+ // When available, use the path from a native content URL, which was already encoded by Android.
+ // This is necessary because JavaScript's encodeURI() does not encode as many characters as
+ // Android, which can result in permission exceptions when the encoding of a content URI
+ // doesn't match the string for which permission was originally granted.
+ path = nativeUrl.substring(contentUrlMatch[0].length - 1);
+ } else {
+ path = encodeURI(fullPath);
+ if (!/^\//.test(path)) {
+ path = '/' + path;
+ }
+
+ var m = /\?.*/.exec(nativeUrl);
+ if (m) {
+ path += m[0];
+ }
}
- return ret;
+
+ return FILESYSTEM_PROTOCOL + '://localhost/' + this.name + path;
}
};
|
204053d95ffa1429288def46fa1e13941834e045 | addon-test-support/-private/is-focusable.js | addon-test-support/-private/is-focusable.js | export default function isFocusable(el) {
let focusableTags = ['INPUT', 'BUTTON', 'LINK', 'SELECT', 'A', 'TEXTAREA'];
let { tagName, type } = el;
if (type === 'hidden') {
return false;
}
return focusableTags.includes(tagName) || el.contentEditable;
}
| export default function isFocusable(el) {
let focusableTags = ['INPUT', 'BUTTON', 'LINK', 'SELECT', 'A', 'TEXTAREA'];
let { tagName, type } = el;
if (type === 'hidden') {
return false;
}
return focusableTags.indexOf(tagName) > -1 || el.contentEditable;
}
| Use indexOf instead of includes | Use indexOf instead of includes
| JavaScript | mit | cibernox/ember-native-dom-helpers,cibernox/ember-native-dom-helpers | ---
+++
@@ -6,5 +6,5 @@
return false;
}
- return focusableTags.includes(tagName) || el.contentEditable;
+ return focusableTags.indexOf(tagName) > -1 || el.contentEditable;
} |
ccb8732f686b578c9f1d09c21f5498769f15bf01 | src/core/sfx.js | src/core/sfx.js | var Sfx = {
sounds: { },
preload: function() {
// Note to self: Do not preload "burning tomato". It doesn't work due to timing issues and just causes overhead.
},
load: function(fileName) {
if (typeof Sfx.sounds[fileName] != 'undefined') {
return Sfx.sounds[fileName];
}
Sfx.sounds[fileName] = new Audio('assets/sfx/' + fileName);
Sfx.sounds[fileName].load();
return Sfx.sounds[fileName];
},
play: function(soundId, volume) {
if (volume == null) {
volume = 0.8;
}
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
// Call load() every time to fix Chrome issue where sound only plays first time
Sfx.sounds[soundId].load();
}
Sfx.sounds[soundId].volume = volume;
Sfx.sounds[soundId].play();
}
}; | var Sfx = {
sounds: { },
preload: function() {
// Note to self: Do not preload "burning tomato". It doesn't work due to timing issues and just causes overhead.
this.load('dialogue_tick.wav');
this.load('footstep_snow_1.wav');
this.load('footstep_snow_2.wav');
this.load('footstep_snow_3.wav');
this.load('footstep_snow_4.wav');
this.load('boom.wav');
this.load('knock.wav');
},
load: function(fileName) {
if (typeof Sfx.sounds[fileName] != 'undefined') {
return Sfx.sounds[fileName];
}
Sfx.sounds[fileName] = new Audio('assets/sfx/' + fileName);
Sfx.sounds[fileName].load();
return Sfx.sounds[fileName];
},
play: function(soundId, volume) {
if (volume == null) {
volume = 0.8;
}
if (typeof Sfx.sounds[soundId] == 'undefined') {
Sfx.load(soundId);
} else {
// Call load() every time to fix Chrome issue where sound only plays first time
Sfx.sounds[soundId].load();
}
Sfx.sounds[soundId].volume = volume;
Sfx.sounds[soundId].play();
}
}; | Update the preload list. Fixes issue with the first dialogue message glitching up with the ticking sound. | [SFX] Update the preload list. Fixes issue with the first dialogue message glitching up with the ticking sound.
| JavaScript | mit | burningtomatoes/CabinInTheSnow | ---
+++
@@ -3,6 +3,13 @@
preload: function() {
// Note to self: Do not preload "burning tomato". It doesn't work due to timing issues and just causes overhead.
+ this.load('dialogue_tick.wav');
+ this.load('footstep_snow_1.wav');
+ this.load('footstep_snow_2.wav');
+ this.load('footstep_snow_3.wav');
+ this.load('footstep_snow_4.wav');
+ this.load('boom.wav');
+ this.load('knock.wav');
},
load: function(fileName) { |
c4a345314585cd23d965d0e52441a275ae53f356 | test/lib/rules/disallow-objectcontroller.js | test/lib/rules/disallow-objectcontroller.js | describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
}
}
/* jshint ignore:end */
]);
});
});
| describe('lib/rules/disallow-objectcontroller', function () {
var checker = global.checker({
plugins: ['./lib/index']
});
describe('not configured', function() {
it('should report with undefined', function() {
global.expect(function() {
checker.configure({disallowObjectController: undefined});
}).to.throws(/requires a true value/i);
});
it('should report with an object', function() {
global.expect(function() {
checker.configure({disallowObjectController: {}});
}).to.throws(/requires a true value/i);
});
});
describe('with true', function() {
checker.rules({disallowObjectController: true});
checker.cases([
/* jshint ignore:start */
{
it: 'should not report',
code: function() {
Ember.Controller.extend({
});
}
}, {
it: 'should not report',
code: function() {
var foo = Ember.ObjectController;
}
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
Ember.ObjectController.extend({
});
},
errors: [{
column: 6, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}, {
it: 'should report deprecated use',
errors: 1,
code: function() {
var foo = Ember.ObjectController.create({
});
},
errors: [{
column: 16, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
message: 'ObjectController is deprecated in Ember 1.11'
}]
}
/* jshint ignore:end */
]);
});
});
| Add additional assertions around objectcontroller errors | Add additional assertions around objectcontroller errors
| JavaScript | mit | minichate/jscs-ember-deprecations,minichate/jscs-ember-deprecations | ---
+++
@@ -43,7 +43,11 @@
Ember.ObjectController.extend({
});
- }
+ },
+ errors: [{
+ column: 6, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
+ message: 'ObjectController is deprecated in Ember 1.11'
+ }]
}, {
it: 'should report deprecated use',
errors: 1,
@@ -51,7 +55,11 @@
var foo = Ember.ObjectController.create({
});
- }
+ },
+ errors: [{
+ column: 16, line: 1, filename: 'input', rule: 'disallowObjectController', fixed: undefined,
+ message: 'ObjectController is deprecated in Ember 1.11'
+ }]
}
/* jshint ignore:end */
]); |
1a15c2bd96e4356fd5659e52380cc5e519cd2007 | Commands/Commands/utils.js | Commands/Commands/utils.js | var commands = []
commands.ping = {
adminOnly: true,
modOnly: false,
fn: function (client, message) {
message.reply('Pong!')
}
}
commands['admin-only'] = {
adminOnly: true,
modOnly: false,
fn: function (client, message, suffix) {
message.reply(suffix)
}
}
commands['mod-only'] = {
adminOnly: false,
modOnly: true,
fn: function (client, message, suffix) {
message.reply(suffix)
}
}
exports.Commands = commands
| var commands = []
commands.ping = {
adminOnly: false,
modOnly: false,
fn: function (client, message) {
message.reply('Pong!')
}
}
commands['admin-only'] = {
adminOnly: true,
modOnly: false,
fn: function (client, message, suffix) {
message.reply(suffix)
}
}
commands['mod-only'] = {
adminOnly: false,
modOnly: true,
fn: function (client, message, suffix) {
message.reply(suffix)
}
}
exports.Commands = commands
| Make ping available to everyone | Make ping available to everyone
| JavaScript | unlicense | Dougley/DiscordFeedback | ---
+++
@@ -1,7 +1,7 @@
var commands = []
commands.ping = {
- adminOnly: true,
+ adminOnly: false,
modOnly: false,
fn: function (client, message) {
message.reply('Pong!') |
9fd9751f875e2800672c12e66889234375deeb51 | __tests__/assets/js/util.spec.js | __tests__/assets/js/util.spec.js | import * as util from '~/assets/js/util'
describe('util', () => {
test('getRSSLink', () => {
expect(util.getRSSLink('foo')).toEqual({
hid: 'rss',
rel: 'alternate',
type: 'application/rss+xml',
href: 'foo'
})
})
})
| import * as util from '~/assets/js/util'
describe('util', () => {
test('getRSSLink', () => {
expect(util.getRSSLink('foo')).toEqual({
hid: 'rss',
rel: 'alternate',
type: 'application/rss+xml',
href: 'foo'
})
})
describe('getImageURLs', () => {
it('get from link', () => {
expect(
util.getImageURLs({
content: {
entities: {
links: [
{
link: 'photo.jpeg'
}
]
}
}
})
).toEqual([
{
thumb: 'photo.jpeg',
original: 'photo.jpeg'
}
])
})
it('get from raw', () => {
expect(
util.getImageURLs(
{
content: {},
raw: [
{
type: 'io.pnut.core.oembed',
value: {
type: 'photo',
url: 'original.png',
thumbnail_url: 'thumbnail.png'
}
}
]
},
true
)
).toMatchObject([
{
thumb: 'thumbnail.png',
original: 'original.png'
}
])
})
it('Remove duplicate', () => {
expect(
util.getImageURLs({
content: {
entities: {
links: [
{
link: 'original.png'
}
]
}
},
raw: [
{
type: 'io.pnut.core.oembed',
value: {
type: 'photo',
url: 'original.png',
thumbnail_url: 'thumbnail.png'
}
}
]
})
).toMatchObject([
{
thumb: 'thumbnail.png',
original: 'original.png'
}
])
})
})
})
| Add the getImageURLs test case | Add the getImageURLs test case
| JavaScript | mit | sunya9/beta,sunya9/beta,sunya9/beta | ---
+++
@@ -9,4 +9,81 @@
href: 'foo'
})
})
+ describe('getImageURLs', () => {
+ it('get from link', () => {
+ expect(
+ util.getImageURLs({
+ content: {
+ entities: {
+ links: [
+ {
+ link: 'photo.jpeg'
+ }
+ ]
+ }
+ }
+ })
+ ).toEqual([
+ {
+ thumb: 'photo.jpeg',
+ original: 'photo.jpeg'
+ }
+ ])
+ })
+ it('get from raw', () => {
+ expect(
+ util.getImageURLs(
+ {
+ content: {},
+ raw: [
+ {
+ type: 'io.pnut.core.oembed',
+ value: {
+ type: 'photo',
+ url: 'original.png',
+ thumbnail_url: 'thumbnail.png'
+ }
+ }
+ ]
+ },
+ true
+ )
+ ).toMatchObject([
+ {
+ thumb: 'thumbnail.png',
+ original: 'original.png'
+ }
+ ])
+ })
+ it('Remove duplicate', () => {
+ expect(
+ util.getImageURLs({
+ content: {
+ entities: {
+ links: [
+ {
+ link: 'original.png'
+ }
+ ]
+ }
+ },
+ raw: [
+ {
+ type: 'io.pnut.core.oembed',
+ value: {
+ type: 'photo',
+ url: 'original.png',
+ thumbnail_url: 'thumbnail.png'
+ }
+ }
+ ]
+ })
+ ).toMatchObject([
+ {
+ thumb: 'thumbnail.png',
+ original: 'original.png'
+ }
+ ])
+ })
+ })
}) |
7adc1e15da0b0e0c11b383758322e2ed3412486a | addon/components/object-list-view-input-cell.js | addon/components/object-list-view-input-cell.js | import BaseComponent from './flexberry-base';
export default BaseComponent.extend({
tagName: 'td',
classNames: [],
column: null,
record: null,
didInsertElement: function() {
var _this = this;
this.$('input').change(function() {
_this.record.set(_this.column.propName, _this.$(this).val());
});
}
});
| import BaseComponent from './flexberry-base';
export default BaseComponent.extend({
tagName: 'td',
classNames: [],
column: null,
record: null,
didInsertElement: function() {
var _this = this;
this.$('input').change(function() {
_this._setValue();
});
this.$('input').keyup(function() {
_this._setValue();
});
},
_setValue: function() {
var currentModelValue = this.record.get(this.column.propName);
var currentInputValue = this.$('input').val();
if (currentModelValue !== currentInputValue) {
this.record.set(this.column.propName, currentInputValue);
}
}
});
| Modify the way of two way binding | Modify the way of two way binding
in object-list-view-input-cell component. Add binding input value with
model on key press.
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -9,7 +9,18 @@
didInsertElement: function() {
var _this = this;
this.$('input').change(function() {
- _this.record.set(_this.column.propName, _this.$(this).val());
+ _this._setValue();
});
+ this.$('input').keyup(function() {
+ _this._setValue();
+ });
+ },
+
+ _setValue: function() {
+ var currentModelValue = this.record.get(this.column.propName);
+ var currentInputValue = this.$('input').val();
+ if (currentModelValue !== currentInputValue) {
+ this.record.set(this.column.propName, currentInputValue);
+ }
}
}); |
420cda51273dd81b2d5eeff07400d23d31cc21c6 | src/store/api/playlists.js | src/store/api/playlists.js | import client from './client'
export default {
getPlaylists (production, callback) {
client.get(`/api/data/projects/${production.id}/playlists`, callback)
},
newPlaylist (playlist, callback) {
const data = {
name: playlist.name,
project_id: playlist.production_id
}
client.post('/api/data/playlists/', data, callback)
},
updatePlaylist (playlist, callback) {
const data = {
name: playlist.name
}
client.put(`/api/data/playlists/${playlist.id}`, data, callback)
},
deletePlaylist (playlist, callback) {
client.del(`/api/data/playlists/${playlist.id}`, callback)
}
}
| import client from './client'
export default {
getPlaylists (production, callback) {
client.get(`/api/data/projects/${production.id}/playlists`, callback)
},
getPlaylist (production, playlist, callback) {
const path = `/api/data/projects/${production.id}/playlists/${playlist.id}`
client.get(path, callback)
},
getShotPreviewFiles (shot, callback) {
const path = `/api/data/shots/${shot.id}/preview-files`
client.get(path, callback)
},
newPlaylist (playlist, callback) {
const data = {
name: playlist.name,
project_id: playlist.production_id
}
client.post('/api/data/playlists/', data, callback)
},
updatePlaylist (playlist, callback) {
const data = {
name: playlist.name
}
if (playlist.shots) {
data.shots = playlist.shots
}
client.put(`/api/data/playlists/${playlist.id}`, data, callback)
},
deletePlaylist (playlist, callback) {
client.del(`/api/data/playlists/${playlist.id}`, callback)
}
}
| Add functions to get details about preview files | Add functions to get details about preview files
| JavaScript | agpl-3.0 | cgwire/kitsu,cgwire/kitsu | ---
+++
@@ -3,6 +3,16 @@
export default {
getPlaylists (production, callback) {
client.get(`/api/data/projects/${production.id}/playlists`, callback)
+ },
+
+ getPlaylist (production, playlist, callback) {
+ const path = `/api/data/projects/${production.id}/playlists/${playlist.id}`
+ client.get(path, callback)
+ },
+
+ getShotPreviewFiles (shot, callback) {
+ const path = `/api/data/shots/${shot.id}/preview-files`
+ client.get(path, callback)
},
newPlaylist (playlist, callback) {
@@ -17,6 +27,10 @@
const data = {
name: playlist.name
}
+ if (playlist.shots) {
+ data.shots = playlist.shots
+ }
+
client.put(`/api/data/playlists/${playlist.id}`, data, callback)
},
|
f0295c57ad4b607c0922ddfbfc1ee6f694d8a97c | src/legacy/js/functions/_loadEmbedIframe.js | src/legacy/js/functions/_loadEmbedIframe.js | /**
* Created by crispin on 10/12/2015.
*/
function loadEmbedIframe(onSave) {
// add modal window
$('.workspace-menu').append(templates.embedIframe());
// variables
var modal = $(".modal");
// modal functions
function closeModal() {
modal.remove();
}
function saveUrl() {
var embedUrl = $('input#embed-url').val();
var fullWidth = $('input#full-width-checkbox').is(':checked');
if (!embedUrl) {
console.log("No url added");
sweetAlert('URL field is empty', 'Please add a url and save again');
return;
}
var parsedEmbedUrl = new URL(embedUrl);
if (parsedEmbedUrl.hostname === window.location.hostname) {
embedUrl = parsedEmbedUrl.pathname;
}
onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>');
modal.remove();
}
// bind events
$('.btn-embed-cancel').click(function() {
closeModal();
});
$('.btn-embed-save').click(function() {
saveUrl();
});
modal.keyup(function(e) {
if (e.keyCode == 27) { //close on esc key
closeModal()
}
if (e.keyCode == 13) { //save on enter key
saveUrl();
}
});
} | /**
* Created by crispin on 10/12/2015.
*/
function loadEmbedIframe(onSave) {
// add modal window
$('.workspace-menu').append(templates.embedIframe());
// variables
var modal = $(".modal");
// modal functions
function closeModal() {
modal.remove();
}
function saveUrl() {
var embedUrl = $('input#embed-url').val();
var fullWidth = $('input#full-width-checkbox').is(':checked');
if (!embedUrl) {
console.log("No url added");
sweetAlert('URL field is empty', 'Please add a url and save again');
return;
}
var parsedEmbedUrl = new URL(embedUrl);
console.log(parsedEmbedUrl);
console.log(window.location);
if (parsedEmbedUrl.host === window.location.host) {
embedUrl = parsedEmbedUrl.pathname;
}
onSave('<ons-interactive url="' + embedUrl + '" full-width="' + fullWidth + '"/>');
modal.remove();
}
// bind events
$('.btn-embed-cancel').click(function() {
closeModal();
});
$('.btn-embed-save').click(function() {
saveUrl();
});
modal.keyup(function(e) {
if (e.keyCode == 27) { //close on esc key
closeModal()
}
if (e.keyCode == 13) { //save on enter key
saveUrl();
}
});
} | Use host instead of hostname | Use host instead of hostname
| JavaScript | mit | ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence | ---
+++
@@ -23,7 +23,9 @@
}
var parsedEmbedUrl = new URL(embedUrl);
- if (parsedEmbedUrl.hostname === window.location.hostname) {
+ console.log(parsedEmbedUrl);
+ console.log(window.location);
+ if (parsedEmbedUrl.host === window.location.host) {
embedUrl = parsedEmbedUrl.pathname;
}
|
361b2f3c3d871da640431e8cd24baeedda15707d | lib/github.js | lib/github.js | 'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
var user = url.substr('https://github.com/'.length);
user = user.substr(0, user.indexOf('/'));
return user;
};
exports.getRepoFromUrl = function(url) {
var repo = url.substr(url.lastIndexOf('/')+1);
repo = repo.substr(0, repo.indexOf('.'));
return repo;
}
| 'use strict';
var GitHubApi = require('github');
var githubapi = new GitHubApi({
// required
version: "3.0.0",
// optional
timeout: 3000
});
exports.getPackageJson = function (user, repo, callback) {
if (!user) {
callback('GitHub user not valid.');
return;
}
if (!repo) {
callback('GitHub repo not valid.');
return;
}
githubapi.repos.getContent({
user: user,
repo: repo,
path: 'package.json'
}, function(error, result) {
if (error) {
callback(error.message || error.defaultMessage || error);
return;
}
var jsonString = new Buffer(result.content, result.encoding).toString();
var json = JSON.parse(jsonString);
callback(null, json);
});
};
exports.getUserFromUrl = function(url) {
if (!url) {
return url;
}
var user = url.substr('https://github.com/'.length);
return user && user.substr(0, user.indexOf('/'));
};
exports.getRepoFromUrl = function(url) {
if (!url) {
return url;
}
var repo = url.substr(url.lastIndexOf('/')+1);
return repo && repo.substr(0, repo.indexOf('.'));
}
| Add protection for empty GitHub url. | Add protection for empty GitHub url.
| JavaScript | mit | seriema/npmalerts,creationix/npmalerts | ---
+++
@@ -35,13 +35,19 @@
};
exports.getUserFromUrl = function(url) {
+ if (!url) {
+ return url;
+ }
+
var user = url.substr('https://github.com/'.length);
- user = user.substr(0, user.indexOf('/'));
- return user;
+ return user && user.substr(0, user.indexOf('/'));
};
exports.getRepoFromUrl = function(url) {
+ if (!url) {
+ return url;
+ }
+
var repo = url.substr(url.lastIndexOf('/')+1);
- repo = repo.substr(0, repo.indexOf('.'));
- return repo;
+ return repo && repo.substr(0, repo.indexOf('.'));
} |
6f1ba3e83d9375b92c63b3a5e43f0976eee5a0e8 | src/transformers/importExportDeclaration.js | src/transformers/importExportDeclaration.js | import replacePath from "../helpers/replacePath";
export default function (t, path, state, regexps) {
const sourcePath = path.get("source");
if(sourcePath) {
replacePath(t, sourcePath, state, regexps);
}
} | import replacePath from "../helpers/replacePath";
export default function (t, path, state, regexps) {
const sourcePath = path.get("source");
if(sourcePath.node) {
replacePath(t, sourcePath, state, regexps);
}
} | Fix noop export breaking on null source node | fix(transformers): Fix noop export breaking on null source node
| JavaScript | mit | Velenir/babel-plugin-import-redirect | ---
+++
@@ -2,7 +2,7 @@
export default function (t, path, state, regexps) {
const sourcePath = path.get("source");
- if(sourcePath) {
+ if(sourcePath.node) {
replacePath(t, sourcePath, state, regexps);
}
} |
c3ff50a7013280fdc3686e9ca676882ceddeef7b | app/assets/javascripts/admin/application.js | app/assets/javascripts/admin/application.js | //= require trix
//= require jquery.geocomplete
//= require cleave
//= require ./trix_events
//= require ./trix_toolbar
//= require ./app/init
//= require_tree ./app
$(document).on('turbolinks:load', function() {
// Datepicker
$('.air-datepicker').datepicker({
autoClose: true,
onSelect: function onSelect(_, _, instance) {
$(instance.el).trigger("datepicker-change");
}
});
});
| //= require trix
//= require jquery.geocomplete
//= require cleave
//= require ./trix_events
//= require ./trix_toolbar
//= require ./app/init
//= require_tree ./app
$(document).on('turbolinks:load', function() {
// Datepicker
$('.air-datepicker').datepicker({
autoClose: true,
minutesStep: 5,
onSelect: function onSelect(_, _, instance) {
$(instance.el).trigger("datepicker-change");
}
});
});
| Allow only 5 minute increments for date picker so we reduce the number of steps | Allow only 5 minute increments for date picker so we reduce the number of steps
| JavaScript | agpl-3.0 | PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto,PopulateTools/gobierto-dev,PopulateTools/gobierto,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev,PopulateTools/gobierto-dev | ---
+++
@@ -11,6 +11,7 @@
// Datepicker
$('.air-datepicker').datepicker({
autoClose: true,
+ minutesStep: 5,
onSelect: function onSelect(_, _, instance) {
$(instance.el).trigger("datepicker-change");
} |
50994f200ef2241d7a393f21edf29f743c53db68 | app/adapters/user.js | app/adapters/user.js | import ApplicationAdapter from 'ghost/adapters/application';
export default ApplicationAdapter.extend({
find: function (store, type, id) {
return this.findQuery(store, type, {id: id, status: 'all'});
},
findAll: function (store, type, id) {
return this.query(store, type, {id: id, status: 'all'});
}
});
| import ApplicationAdapter from 'ghost/adapters/application';
export default ApplicationAdapter.extend({
find: function (store, type, id) {
return this.findQuery(store, type, {id: id, status: 'all'});
},
// TODO: This is needed because the API currently expects you to know the
// status of the record before retrieving by ID. Quick fix is to always
// include status=all in the query
findRecord: function (store, type, id, snapshot) {
let url = this.buildIncludeURL(store, type.modelName, id, snapshot, 'findRecord');
url += '&status=all';
return this.ajax(url, 'GET');
},
findAll: function (store, type, id) {
return this.query(store, type, {id: id, status: 'all'});
}
});
| Fix "revoke invite" feature on /team page | Fix "revoke invite" feature on /team page
refs #5947
- override the `findRecord` method of the user adapter to always include "status=all" when querying by ID
| JavaScript | mit | airycanon/Ghost-Admin,kevinansfield/Ghost-Admin,acburdine/Ghost-Admin,JohnONolan/Ghost-Admin,TryGhost/Ghost-Admin,TryGhost/Ghost-Admin,kevinansfield/Ghost-Admin,airycanon/Ghost-Admin,dbalders/Ghost-Admin,acburdine/Ghost-Admin,JohnONolan/Ghost-Admin,dbalders/Ghost-Admin | ---
+++
@@ -5,6 +5,17 @@
return this.findQuery(store, type, {id: id, status: 'all'});
},
+ // TODO: This is needed because the API currently expects you to know the
+ // status of the record before retrieving by ID. Quick fix is to always
+ // include status=all in the query
+ findRecord: function (store, type, id, snapshot) {
+ let url = this.buildIncludeURL(store, type.modelName, id, snapshot, 'findRecord');
+
+ url += '&status=all';
+
+ return this.ajax(url, 'GET');
+ },
+
findAll: function (store, type, id) {
return this.query(store, type, {id: id, status: 'all'});
} |
e236cc4ad3a91774da45230544c73dc68d88c204 | ui/src/auth/Authenticated.js | ui/src/auth/Authenticated.js | import React from 'react'
import {routerActions} from 'react-router-redux'
import {UserAuthWrapper} from 'redux-auth-wrapper'
export const UserIsAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
authenticatingSelector: ({auth: {isAuthLoading}}) => isAuthLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsAuthenticated',
predicate: ({auth: {me, links, isAuthLoading}}) => isAuthLoading === false && links.length && me !== null,
})
//
// UserIsAuthenticated.onEnter = (store, nextState, replace) => {
// debugger
// console.log('bob')
// }
export const Authenticated = UserIsAuthenticated((props) => React.cloneElement(props.children, props))
export const UserIsNotAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
authenticatingSelector: ({auth: {isAuthLoading}}) => isAuthLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsNotAuthenticated',
predicate: ({auth: {me, links, isAuthLoading}}) => isAuthLoading === false && links.length > 0 && me === null,
failureRedirectPath: () => '/',
allowRedirectBack: false,
})
| import React from 'react'
import {routerActions} from 'react-router-redux'
import {UserAuthWrapper} from 'redux-auth-wrapper'
export const UserIsAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
authenticatingSelector: ({auth: {isMeLoading}}) => isMeLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsAuthenticated',
predicate: ({auth: {me, isMeLoading}}) => !isMeLoading && me !== null,
})
//
// UserIsAuthenticated.onEnter = (store, nextState, replace) => {
// debugger
// console.log('bob')
// }
export const Authenticated = UserIsAuthenticated((props) => React.cloneElement(props.children, props))
export const UserIsNotAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
authenticatingSelector: ({auth: {isMeLoading}}) => isMeLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsNotAuthenticated',
predicate: ({auth: {me, isMeLoading}}) => !isMeLoading && me === null,
failureRedirectPath: () => '/',
allowRedirectBack: false,
})
| Clarify and simplify authentication logic to predicate upon existence of 'me' object in 'auth' | Clarify and simplify authentication logic to predicate upon existence of 'me' object in 'auth'
| JavaScript | agpl-3.0 | brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf,brianbaker/chronograf | ---
+++
@@ -4,11 +4,11 @@
export const UserIsAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
- authenticatingSelector: ({auth: {isAuthLoading}}) => isAuthLoading,
+ authenticatingSelector: ({auth: {isMeLoading}}) => isMeLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsAuthenticated',
- predicate: ({auth: {me, links, isAuthLoading}}) => isAuthLoading === false && links.length && me !== null,
+ predicate: ({auth: {me, isMeLoading}}) => !isMeLoading && me !== null,
})
//
// UserIsAuthenticated.onEnter = (store, nextState, replace) => {
@@ -20,11 +20,11 @@
export const UserIsNotAuthenticated = UserAuthWrapper({
authSelector: ({auth}) => ({auth}),
- authenticatingSelector: ({auth: {isAuthLoading}}) => isAuthLoading,
+ authenticatingSelector: ({auth: {isMeLoading}}) => isMeLoading,
LoadingComponent: (() => <div className="page-spinner" />),
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsNotAuthenticated',
- predicate: ({auth: {me, links, isAuthLoading}}) => isAuthLoading === false && links.length > 0 && me === null,
+ predicate: ({auth: {me, isMeLoading}}) => !isMeLoading && me === null,
failureRedirectPath: () => '/',
allowRedirectBack: false,
}) |
c2abeaf62c7a8ec5b2435a579cc192a1edc58ceb | app/index-create-script.js | app/index-create-script.js | const bravePort = process.env.BRAVE_PORT || 8080
const createScript = function (scriptPath) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = scriptPath.replace(/\{port\}/, bravePort)
script.async = true
script.onload = resolve
script.onerror = reject
document.body.appendChild(script)
})
}
createScript('http://localhost:{port}/webpack-dev-server.js').catch(function () {
document.querySelector('#setupError').style.display = 'block'
}).then(function () {
createScript('http://localhost:{port}/built/app.entry.js')
})
| const bravePort = process.env.BRAVE_PORT || 8080
const createScript = function (scriptPath) {
return new Promise(function (resolve, reject) {
var script = document.createElement('script')
script.type = 'text/javascript'
script.src = scriptPath.replace(/\{port\}/, bravePort)
script.async = true
script.onload = resolve
script.onerror = reject
document.body.appendChild(script)
})
}
createScript('http://localhost:{port}/built/app.entry.js')
createScript('http://localhost:{port}/webpack-dev-server.js').catch(function () {
document.querySelector('#setupError').style.display = 'block'
})
| Fix dev app init for Windows | Fix dev app init for Windows
Having it load entry.js only after the other script is loading is
causing problems in init on slow machines (or my Windows VM).
The devserver doesn't need to be included first, it's just for live
realoading.
Auditors: da39a3ee5e6b4b0d3255bfef95601890afd80709@diracdeltas
| JavaScript | mpl-2.0 | MKuenzi/browser-laptop,Sh1d0w/browser-laptop,MKuenzi/browser-laptop,jonathansampson/browser-laptop,darkdh/browser-laptop,manninglucas/browser-laptop,manninglucas/browser-laptop,pmkary/braver,diasdavid/browser-laptop,MKuenzi/browser-laptop,Sh1d0w/browser-laptop,darkdh/browser-laptop,luixxiul/browser-laptop,pmkary/braver,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,diasdavid/browser-laptop,willy-b/browser-laptop,darkdh/browser-laptop,diasdavid/browser-laptop,willy-b/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,dcposch/browser-laptop,willy-b/browser-laptop,timborden/browser-laptop,timborden/browser-laptop,diasdavid/browser-laptop,manninglucas/browser-laptop,darkdh/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,dcposch/browser-laptop,MKuenzi/browser-laptop,timborden/browser-laptop,manninglucas/browser-laptop,pmkary/braver,pmkary/braver,luixxiul/browser-laptop,willy-b/browser-laptop | ---
+++
@@ -10,8 +10,7 @@
document.body.appendChild(script)
})
}
+createScript('http://localhost:{port}/built/app.entry.js')
createScript('http://localhost:{port}/webpack-dev-server.js').catch(function () {
document.querySelector('#setupError').style.display = 'block'
-}).then(function () {
- createScript('http://localhost:{port}/built/app.entry.js')
}) |
061d5ff56ea10b8b1b6441bdfe6dd4c0751ce6b6 | app/updateChannel.js | app/updateChannel.js | 'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length ?
utils.formatSchedule(changes) : Promise.reject('No changes'))
.then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length ?
utils.formatNews(news) : Promise.reject('No news'))
.then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
updateSchedule()
.then(() => updateNews())
| 'use strict'
const TelegramBot = require('node-telegram-bot-api');
const config = require('../config');
const utils = require('./utils');
const Kinospartak = require('./Kinospartak/Kinospartak');
const bot = new TelegramBot(config.TOKEN);
const kinospartak = new Kinospartak();
/**
* updateSchedule - update schedule and push updates to Telegram channel
*
* @return {Promise}
*/
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
changes.length
? utils.formatSchedule(changes)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.commitChanges())
};
/**
* updateNews - update news and push updates to Telegram channel
*
* @return {Promise}
*/
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
news.length
? utils.formatNews(news)
: undefined)
.then(messages =>
messages
? utils.sendInOrder(bot, config.CHANNEL, messages)
: undefined)
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
function update() {
return Promise.all([
updateSchedule,
updateNews
]).catch((err) => {
setTimeout(() => {
update();
}, 60 * 5);
})
}
update(); | Add error handling for channel updates | Add error handling for channel updates
| JavaScript | mit | TheBeastOfCaerbannog/kinospartak-bot | ---
+++
@@ -18,9 +18,13 @@
function updateSchedule() {
return kinospartak.getChanges()
.then(changes =>
- changes.length ?
- utils.formatSchedule(changes) : Promise.reject('No changes'))
- .then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
+ changes.length
+ ? utils.formatSchedule(changes)
+ : undefined)
+ .then(messages =>
+ messages
+ ? utils.sendInOrder(bot, config.CHANNEL, messages)
+ : undefined)
.then(() => kinospartak.commitChanges())
};
@@ -32,11 +36,25 @@
function updateNews() {
return kinospartak.getLatestNews()
.then(news =>
- news.length ?
- utils.formatNews(news) : Promise.reject('No news'))
- .then(messages => utils.sendInOrder(bot, config.CHANNEL, messages))
+ news.length
+ ? utils.formatNews(news)
+ : undefined)
+ .then(messages =>
+ messages
+ ? utils.sendInOrder(bot, config.CHANNEL, messages)
+ : undefined)
.then(() => kinospartak.setNewsOffset(new Date().toString()))
};
-updateSchedule()
- .then(() => updateNews())
+function update() {
+ return Promise.all([
+ updateSchedule,
+ updateNews
+ ]).catch((err) => {
+ setTimeout(() => {
+ update();
+ }, 60 * 5);
+ })
+}
+
+update(); |
8646b63a22e82765743b102c1665d5e97e831e75 | src/schema/defaultsetup.js | src/schema/defaultsetup.js | const {Plugin} = require("../edit")
const {menuBar} = require("../menu/menubar")
const {inputRules, allInputRules} = require("../inputrules")
const {defaultRules} = require("./inputrules")
const {defaultMenuItems} = require("./menu")
const {defaultSchemaKeymapPlugin} = require("./keymap")
const {defaultSchemaStyle} = require("./style")
// :: Plugin
// A convenience plugin that bundles together a simple menubar, the
// default input rules, default key bindings, and default styling.
// Probably only useful for quickly setting up a passable
// editor—you'll need more control over your settings in most
// real-world situations.
const defaultSetup = new Plugin(class DefaultSetup {
constructor(pm, options) {
let menu = defaultMenuItems(pm.schema).fullMenu
if (options.updateMenu) menu = options.updateMenu(menu)
this.plugins = (menu ? [menuBar.config({float: true, content: menu})] : []).concat([
inputRules.config({rules: allInputRules.concat(defaultRules(pm.schema))}),
defaultSchemaKeymapPlugin,
defaultSchemaStyle
])
this.plugins.forEach(plugin => plugin.attach(pm))
}
detach(pm) {
this.plugins.forEach(plugin => plugin.detach(pm))
}
})
exports.defaultSetup = defaultSetup
| const {Plugin} = require("../edit")
const {menuBar} = require("../menu/menubar")
const {inputRules, allInputRules} = require("../inputrules")
const {defaultRules} = require("./inputrules")
const {defaultMenuItems} = require("./menu")
const {defaultSchemaKeymapPlugin} = require("./keymap")
const {defaultSchemaStyle} = require("./style")
// :: Plugin
// A convenience plugin that bundles together a simple menubar, the
// default input rules, default key bindings, and default styling.
// Probably only useful for quickly setting up a passable
// editor—you'll need more control over your settings in most
// real-world situations.
const defaultSetup = new Plugin(class DefaultSetup {
constructor(pm, options) {
let menu = options.menu
if (menu == null)
menu = defaultMenuItems(pm.schema).fullMenu
this.plugins = (menu ? [menuBar.config({float: true, content: menu})] : []).concat([
inputRules.config({rules: allInputRules.concat(defaultRules(pm.schema))}),
defaultSchemaKeymapPlugin,
defaultSchemaStyle
])
this.plugins.forEach(plugin => plugin.attach(pm))
}
detach(pm) {
this.plugins.forEach(plugin => plugin.detach(pm))
}
})
exports.defaultSetup = defaultSetup
| Replace the updateMenu option to defaultSetup with a menu option | Replace the updateMenu option to defaultSetup with a menu option
Much cleaner
| JavaScript | mit | kiejo/prosemirror,tzuhsiulin/prosemirror,tzuhsiulin/prosemirror,kiejo/prosemirror,kiejo/prosemirror,salzhrani/prosemirror,tzuhsiulin/prosemirror,salzhrani/prosemirror,salzhrani/prosemirror | ---
+++
@@ -14,8 +14,9 @@
// real-world situations.
const defaultSetup = new Plugin(class DefaultSetup {
constructor(pm, options) {
- let menu = defaultMenuItems(pm.schema).fullMenu
- if (options.updateMenu) menu = options.updateMenu(menu)
+ let menu = options.menu
+ if (menu == null)
+ menu = defaultMenuItems(pm.schema).fullMenu
this.plugins = (menu ? [menuBar.config({float: true, content: menu})] : []).concat([
inputRules.config({rules: allInputRules.concat(defaultRules(pm.schema))}), |
01c728ab907329058ad29b456a2e6eb3ee2cacb2 | example/src/__mocks__/react-native-i18n.js | example/src/__mocks__/react-native-i18n.js | // @flow
import I18nJs from 'i18n-js';
I18nJs.locale = 'en'; // a locale from your available translations
export const getLanguages = () => Promise.resolve('en');
export default I18nJs;
| // @flow
import I18nJs from 'i18n-js';
I18nJs.locale = 'en'; // a locale from your available translations
export const getLanguages = () => Promise.resolve(['en']);
export default I18nJs;
| Fix test - getLanguages is a Promise<Array<string>> | Fix test - getLanguages is a Promise<Array<string>> | JavaScript | mit | AlexanderZaytsev/react-native-i18n,AlexanderZaytsev/react-native-i18n,AlexanderZaytsev/react-native-i18n,AlexanderZaytsev/react-native-i18n | ---
+++
@@ -3,5 +3,5 @@
import I18nJs from 'i18n-js';
I18nJs.locale = 'en'; // a locale from your available translations
-export const getLanguages = () => Promise.resolve('en');
+export const getLanguages = () => Promise.resolve(['en']);
export default I18nJs; |
08289ce0e335bffcb0126fc940660c465cf13d98 | addon/initializers/responsive.js | addon/initializers/responsive.js | import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
| import Media from 'ember-responsive/media';
/**
* An initializer that sets up `ember-responsive`.
*
* Refer to {{#crossLink "Ember.Application.responsive"}}{{/crossLink}}
* for examples of how to configure this library before the initializer
* before it's run by Ember.
*
* @static
* @constructor
* @module ember-responsive
* @namespace Ember.Application
* @class initializer
*/
export default {
/**
* @property name
* @type string
* @default responsive
*/
name: 'responsive',
/**
* @method initialize
* @param Ember.Container container
* @param Ember.Application app
*/
initialize: function(container, app) {
if (app.responsive) {
Ember.warn('Your breakpoints should be defined in /app/breakpoints.js');
}
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) {
for (var name in breakpoints) {
if (media.hasOwnProperty(name)) {
media.match(name, breakpoints[name]);
}
}
}
app.register('responsive:media', media, { instantiate: false });
app.inject('controller', 'media', 'responsive:media');
app.inject('component', 'media', 'responsive:media');
app.inject('route', 'media', 'responsive:media');
app.inject('view', 'media', 'responsive:media');
}
};
| Add a warning if breakpoints are still define in app.js | Add a warning if breakpoints are still define in app.js
| JavaScript | mit | topaxi/ember-responsive,jasonmit/ember-responsive,jasonmit/ember-responsive,jherdman/ember-responsive,topaxi/ember-responsive,freshbooks/ember-responsive,salzhrani/ember-responsive,salzhrani/ember-responsive,elwayman02/ember-responsive,f3ndot/ember-responsive,freshbooks/ember-responsive,f3ndot/ember-responsive,jherdman/ember-responsive,elwayman02/ember-responsive | ---
+++
@@ -27,6 +27,9 @@
* @param Ember.Application app
*/
initialize: function(container, app) {
+ if (app.responsive) {
+ Ember.warn('Your breakpoints should be defined in /app/breakpoints.js');
+ }
var breakpoints = container.lookupFactory('breakpoints:main');
var media = Media.create();
if (breakpoints) { |
8094fb5d78b8fecc3a45a0bd7771b034888bd41a | app/server/server.js | app/server/server.js | import path from 'path';
import renderApp from './renderApp.js';
import express from 'express';
import compression from 'compression';
const server = express();
const port = process.env.PORT || 80;
server.use(compression());
server.use(express.static('public'));
server.use('/fireball-js', express.static(path.resolve(__dirname, '../../node_modules/fireball-js')));
server.get('*', renderApp);
server.listen(port, () => {
console.log('Node running on port', port); // eslint-disable-line no-console
});
if (process.env.NODE_ENV !== 'production') {
require('../../buildTools/webpackDevServer.js');
}
| import path from 'path';
import renderApp from './renderApp.js';
import express from 'express';
import compression from 'compression';
const server = express();
const port = process.env.PORT || 80;
server.use(compression());
server.use(express.static('public', {maxAge: 31536000})); // 31536000 = one year
server.use('/fireball-js', express.static(path.resolve(__dirname, '../../node_modules/fireball-js')));
server.get('*', renderApp);
server.listen(port, () => {
console.log('Node running on port', port); // eslint-disable-line no-console
});
if (process.env.NODE_ENV !== 'production') {
require('../../buildTools/webpackDevServer.js');
}
| Add cache-control max age to static content | Add cache-control max age to static content
| JavaScript | mit | davidgilbertson/davidg-site,davidgilbertson/davidg-site | ---
+++
@@ -6,7 +6,7 @@
const port = process.env.PORT || 80;
server.use(compression());
-server.use(express.static('public'));
+server.use(express.static('public', {maxAge: 31536000})); // 31536000 = one year
server.use('/fireball-js', express.static(path.resolve(__dirname, '../../node_modules/fireball-js')));
|
f9639831d2d01cfad745f9355f76bd6bd305e932 | addon/components/file-renderer/component.js | addon/components/file-renderer/component.js | import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
export default Ember.Component.extend({
layout,
download: null,
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download');
var renderUrl = base + '?url=' + encodeURIComponent(download + '?direct&mode=render&initialWidth=766');
return renderUrl;
})
});
| import Ember from 'ember';
import layout from './template';
import config from 'ember-get-config';
export default Ember.Component.extend({
layout,
download: null,
width: '100%',
height: '100%',
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download');
var renderUrl = base + '?url=' + encodeURIComponent(download + '?direct&mode=render&initialWidth=766');
return renderUrl;
})
});
| Add height and width defaults for mfr renderer | Add height and width defaults for mfr renderer
| JavaScript | apache-2.0 | jamescdavis/ember-osf,crcresearch/ember-osf,CenterForOpenScience/ember-osf,samchrisinger/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,binoculars/ember-osf,hmoco/ember-osf,pattisdr/ember-osf,binoculars/ember-osf,hmoco/ember-osf,CenterForOpenScience/ember-osf,chrisseto/ember-osf,cwilli34/ember-osf,jamescdavis/ember-osf,chrisseto/ember-osf,pattisdr/ember-osf,samchrisinger/ember-osf,cwilli34/ember-osf,baylee-d/ember-osf | ---
+++
@@ -5,6 +5,8 @@
export default Ember.Component.extend({
layout,
download: null,
+ width: '100%',
+ height: '100%',
mfrUrl: Ember.computed('download', function() {
var base = config.OSF.renderUrl;
var download = this.get('download'); |
725165d485e127498f934e63e0498614dd7d4072 | Nope.safariextension/rules/custom/css_rules.js | Nope.safariextension/rules/custom/css_rules.js | var advertisingCSSRules = [{
"trigger": {
"url-filter": ".*"
},
"action": {
"type": "css-display-none",
"selector":
".ad-promotions-container,\
.ad-wide,\
.ad-top,\
#bottomads"
}
}];
| var advertisingCSSRules = [{
"trigger": {
"url-filter": ".*"
},
"action": {
"type": "css-display-none",
"selector":
".ad-promotions-container,\
.ad-wide,\
.ad-top,\
#bottomads,\
#tads"
}
}];
| Hide Google search top ads | [Rules] Hide Google search top ads
| JavaScript | mit | kaishin/Nope,kaishin/Nope,kaishin/Nope | ---
+++
@@ -8,6 +8,7 @@
".ad-promotions-container,\
.ad-wide,\
.ad-top,\
- #bottomads"
+ #bottomads,\
+ #tads"
}
}]; |
5d861adc02e43d859cad88b8e08338e625233bc5 | markitup_filebrowser/static/markitup_filebrowser/sets/markdown/FilebrowserHelper.js | markitup_filebrowser/static/markitup_filebrowser/sets/markdown/FilebrowserHelper.js | FileBrowserHelper = {
markItUp: false,
show: function(markItUp, type) {
this.markItUp = markItUp
var textarea_id = $(markItUp.textarea).attr('id');
FileBrowser.show(textarea_id, '/admin/filebrowser/browse/?pop=4&type=' + type);
},
triggerInsert: function(url) {
$(this.markItUp.textarea).trigger('insertion',
[{replaceWith: '![[![Alternative text]!]]('+url+' "[![Title]!]")'}]);
}
};
| FileBrowserHelper = {
markItUp: false,
show: function(markItUp, type) {
this.markItUp = markItUp
var textarea_id = $(markItUp.textarea).attr('id');
FileBrowser.show(textarea_id, '/admin/filebrowser/browse/?pop=1&type=' + type);
},
triggerInsert: function(url) {
$(this.markItUp.textarea).trigger('insertion',
[{replaceWith: '![[![Alternative text]!]]('+url+' "[![Title]!]")'}]);
}
};
| Return type to working one | Return type to working one
| JavaScript | bsd-3-clause | Iv/django-markiup-filebrowser,Iv/django-markiup-filebrowser | ---
+++
@@ -4,7 +4,7 @@
show: function(markItUp, type) {
this.markItUp = markItUp
var textarea_id = $(markItUp.textarea).attr('id');
- FileBrowser.show(textarea_id, '/admin/filebrowser/browse/?pop=4&type=' + type);
+ FileBrowser.show(textarea_id, '/admin/filebrowser/browse/?pop=1&type=' + type);
},
triggerInsert: function(url) { |
a13ed5a7f9a50ecd2e5c9341d37dfe795c374c02 | tests/extend.js | tests/extend.js | var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
return $.NSString('stringWithUTF8String', 'test')
})
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
//console.log(String(instance)) // now this one segfaults? WTF!?!?!
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 5)
| var $ = require('../')
, assert = require('assert')
$.import('Foundation')
$.NSAutoreleasePool('alloc')('init')
// Subclass 'NSObject', creating a new class named 'NRTest'
var NRTest = $.NSObject.extend('NRTest')
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
assert.ok(NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
console.log(self.ivar('name'))
return $.NSString('stringWithUTF8String', 'test')
}))
// Add an instance variable, an NSString* instance.
assert.ok(NRTest.addIvar('name', '@'))
// Finalize the class so the we can make instances of it
NRTest.register()
// Create an instance
var instance = NRTest('alloc')('init')
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
instance.ivar('name', $._('NodObjC Rules!'))
console.log(String(instance))
console.log(''+instance)
console.log(instance+'')
console.log(instance)
assert.equal(counter, 6)
| Add test for single addIvar call. For some reason this fixes the segfault from before... WTF... | Add test for single addIvar call. For some reason this fixes the segfault from before... WTF...
| JavaScript | mit | mralexgray/NodObjC,TooTallNate/NodObjC,TooTallNate/NodObjC,mralexgray/NodObjC,telerik/NodObjC,telerik/NodObjC,jerson/NodObjC,jerson/NodObjC,jerson/NodObjC | ---
+++
@@ -9,11 +9,15 @@
, counter = 0
// Add a new method to the NRTest class responding to the "description" selector
-NRTest.addMethod('description', '@@:', function (self, _cmd) {
+assert.ok(NRTest.addMethod('description', '@@:', function (self, _cmd) {
counter++
console.log(_cmd)
+ console.log(self.ivar('name'))
return $.NSString('stringWithUTF8String', 'test')
-})
+}))
+
+// Add an instance variable, an NSString* instance.
+assert.ok(NRTest.addIvar('name', '@'))
// Finalize the class so the we can make instances of it
NRTest.register()
@@ -24,9 +28,10 @@
// call [instance description] in a variety of ways (via toString())
console.log(instance('description')+'')
console.log(instance.toString())
-//console.log(String(instance)) // now this one segfaults? WTF!?!?!
+instance.ivar('name', $._('NodObjC Rules!'))
+console.log(String(instance))
console.log(''+instance)
console.log(instance+'')
console.log(instance)
-assert.equal(counter, 5)
+assert.equal(counter, 6) |
21c5f97e898b8f02ff38445536481151affdf077 | src/Oro/Bundle/UIBundle/Resources/public/js/extend/bootstrap/bootstrap-typeahead.js | src/Oro/Bundle/UIBundle/Resources/public/js/extend/bootstrap/bootstrap-typeahead.js | define(function(require) {
'use strict';
var $ = require('jquery');
require('bootstrap');
/**
* This customization allows to define own click, render, show functions for Typeahead
*/
var Typeahead;
var origTypeahead = $.fn.typeahead.Constructor;
var origFnTypeahead = $.fn.typeahead;
Typeahead = function(element, options) {
var opts = $.extend({}, $.fn.typeahead.defaults, options);
this.click = opts.click || this.click;
this.render = opts.render || this.render;
this.show = opts.show || this.show;
origTypeahead.apply(this, arguments);
};
Typeahead.prototype = origTypeahead.prototype;
Typeahead.prototype.constructor = Typeahead;
$.fn.typeahead = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('typeahead');
var options = typeof option === 'object' && option;
if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
};
$.fn.typeahead.defaults = origFnTypeahead.defaults;
$.fn.typeahead.Constructor = Typeahead;
$.fn.typeahead.noConflict = origFnTypeahead.noConflict;
});
| define(function(require) {
'use strict';
var $ = require('jquery');
require('bootstrap');
/**
* This customization allows to define own focus, click, render, show, lookup functions for Typeahead
*/
var Typeahead;
var origTypeahead = $.fn.typeahead.Constructor;
var origFnTypeahead = $.fn.typeahead;
Typeahead = function(element, options) {
var opts = $.extend({}, $.fn.typeahead.defaults, options);
this.focus = opts.focus || this.focus;
this.render = opts.render || this.render;
this.show = opts.show || this.show;
this.lookup = opts.lookup || this.lookup;
origTypeahead.apply(this, arguments);
};
Typeahead.prototype = origTypeahead.prototype;
Typeahead.prototype.constructor = Typeahead;
$.fn.typeahead = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('typeahead');
var options = typeof option === 'object' && option;
if (!data) {
$this.data('typeahead', (data = new Typeahead(this, options)));
}
if (typeof option === 'string') {
data[option]();
}
});
};
$.fn.typeahead.defaults = origFnTypeahead.defaults;
$.fn.typeahead.Constructor = Typeahead;
$.fn.typeahead.noConflict = origFnTypeahead.noConflict;
});
| Add validation functionality to RuleEditorComponent - extended typeahead plugin; - changed autocomplete init script; - added typeahead behavior ащк empty value; | BB-4210: Add validation functionality to RuleEditorComponent
- extended typeahead plugin;
- changed autocomplete init script;
- added typeahead behavior ащк empty value;
| JavaScript | mit | orocrm/platform,orocrm/platform,orocrm/platform | ---
+++
@@ -5,7 +5,7 @@
require('bootstrap');
/**
- * This customization allows to define own click, render, show functions for Typeahead
+ * This customization allows to define own focus, click, render, show, lookup functions for Typeahead
*/
var Typeahead;
var origTypeahead = $.fn.typeahead.Constructor;
@@ -13,9 +13,10 @@
Typeahead = function(element, options) {
var opts = $.extend({}, $.fn.typeahead.defaults, options);
- this.click = opts.click || this.click;
+ this.focus = opts.focus || this.focus;
this.render = opts.render || this.render;
this.show = opts.show || this.show;
+ this.lookup = opts.lookup || this.lookup;
origTypeahead.apply(this, arguments);
};
|
6637f4982ba917abdc1123f8cf1b6f615ecc9b73 | addon/controllers/sub-row-array.js | addon/controllers/sub-row-array.js | import Ember from 'ember';
var SubRowArray = Ember.ArrayController.extend({
init: function() {
this._super();
var oldObject = this.get('oldObject');
if (oldObject) {
var content = this.get('content');
var oldControllers = oldObject.get('_subControllers');
oldControllers.forEach(function(item) {
if (item) {
var index = content.indexOf(Ember.get(item, 'content'));
this.setControllerAt(item, index);
}
}.bind(this));
}
},
objectAt: function (idx) {
return this._subControllers[idx];
},
setControllerAt: function (controller, idx) {
this._subControllers[idx] = controller;
this.incrementProperty('definedControllersCount', 1);
},
objectAtContent: function (idx) {
var content = this.get('content');
return content.objectAt(idx);
},
definedControllersCount: 0,
definedControllers: function () {
return this._subControllers.filter(function (item) {
return !!item;
});
}
});
export default SubRowArray;
| import Ember from 'ember';
var SubRowArray = Ember.ArrayController.extend({
init: function() {
this._super();
var self = this;
var oldObject = this.get('oldObject');
if (oldObject) {
var content = this.get('content');
var oldControllers = oldObject.get('_subControllers');
oldControllers.forEach(function(item) {
if (item) {
var index = content.indexOf(Ember.get(item, 'content'));
self.setControllerAt(item, index);
}
});
}
},
objectAt: function (idx) {
return this._subControllers[idx];
},
setControllerAt: function (controller, idx) {
this._subControllers[idx] = controller;
this.incrementProperty('definedControllersCount', 1);
},
objectAtContent: function (idx) {
var content = this.get('content');
return content.objectAt(idx);
},
definedControllersCount: 0,
definedControllers: function () {
return this._subControllers.filter(function (item) {
return !!item;
});
}
});
export default SubRowArray;
| Fix ember test and remove bind syntax | Fix ember test and remove bind syntax
| JavaScript | bsd-3-clause | Gaurav0/ember-table,Gaurav0/ember-table,Cuiyansong/ember-table,nomadop/ember-table,nomadop/ember-table,hedgeserv/ember-table,hedgeserv/ember-table,phoebusliang/ember-table,Cuiyansong/ember-table,phoebusliang/ember-table | ---
+++
@@ -3,6 +3,7 @@
var SubRowArray = Ember.ArrayController.extend({
init: function() {
this._super();
+ var self = this;
var oldObject = this.get('oldObject');
if (oldObject) {
var content = this.get('content');
@@ -10,9 +11,9 @@
oldControllers.forEach(function(item) {
if (item) {
var index = content.indexOf(Ember.get(item, 'content'));
- this.setControllerAt(item, index);
+ self.setControllerAt(item, index);
}
- }.bind(this));
+ });
}
},
|
ab85db461e34bae17b7510204bc405736af26e05 | app/soc/content/js/datetimepicker-090825.js | app/soc/content/js/datetimepicker-090825.js | jQuery(
function () {
jQuery('.datetime-pick').datetimepicker();
jQuery('.date-pick').datetimepicker({
'pickDateOnly': true,
'defaultDate': new Date('01/01/1974'),
'timeFormat': '',
'yearRange': '1900:2008'
});
}
);
| jQuery(
function () {
var cur_year = new Date().getFullYear();
jQuery('.datetime-pick').datetimepicker();
jQuery('.date-pick').datetimepicker({
'pickDateOnly': true,
'defaultDate': new Date('01/01/1974'),
'timeFormat': '',
'yearRange': '1900:' + (cur_year + 1)
});
}
);
| Fix the date picker to show the year till the current year plus one. | Fix the date picker to show the year till the current year plus one.
--HG--
extra : rebase_source : 251155a2af486272154e6eb5e993859fc4fd0650
| JavaScript | apache-2.0 | SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange | ---
+++
@@ -1,11 +1,12 @@
jQuery(
function () {
+ var cur_year = new Date().getFullYear();
jQuery('.datetime-pick').datetimepicker();
jQuery('.date-pick').datetimepicker({
'pickDateOnly': true,
'defaultDate': new Date('01/01/1974'),
'timeFormat': '',
- 'yearRange': '1900:2008'
+ 'yearRange': '1900:' + (cur_year + 1)
});
}
); |
59b316ab7f226fddb5ee1475ba7433bf48ea2ee6 | TabBar.js | TabBar.js | 'use strict';
import React, {
Platform,
StyleSheet,
View,
} from 'react-native';
import Layout from './Layout';
export default class TabBar extends React.Component {
static propTypes = {
...View.propTypes,
shadowStyle: View.propTypes.style,
}
render() {
return (
<View {...this.props} style={[styles.container, this.props.style]}>
{this.props.children}
<View style={[styles.shadow, this.props.shadowStyle]} />
</View>
);
}
}
let styles = StyleSheet.create({
container: {
backgroundColor: '#f8f8f8',
flexDirection: 'row',
justifyContent: 'space-around',
height: Layout.tabBarHeight,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
shadow: {
backgroundColor: 'rgba(0, 0, 0, 0.25)',
height: Layout.pixel,
position: 'absolute',
left: 0,
right: 0,
top: Platform.OS === 'android' ? 0 : -Layout.pixel,
},
});
| 'use strict';
import React, {
Platform,
StyleSheet,
View,
} from 'react-native';
import Layout from './Layout';
export default class TabBar extends React.Component {
static propTypes = {
...View.propTypes,
shadowStyle: View.propTypes.style,
};
render() {
return (
<View {...this.props} style={[styles.container, this.props.style]}>
{this.props.children}
<View style={[styles.shadow, this.props.shadowStyle]} />
</View>
);
}
}
let styles = StyleSheet.create({
container: {
backgroundColor: '#f8f8f8',
flexDirection: 'row',
justifyContent: 'space-around',
height: Layout.tabBarHeight,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
shadow: {
backgroundColor: 'rgba(0, 0, 0, 0.25)',
height: Layout.pixel,
position: 'absolute',
left: 0,
right: 0,
top: Platform.OS === 'android' ? 0 : -Layout.pixel,
},
});
| Add missing semicolon for ES7 | Add missing semicolon for ES7 | JavaScript | mit | exponentjs/react-native-tab-navigator | ---
+++
@@ -12,7 +12,7 @@
static propTypes = {
...View.propTypes,
shadowStyle: View.propTypes.style,
- }
+ };
render() {
return ( |
b4d0577e3734b979a204b44989ec615191b7b632 | test/serialization_test.js | test/serialization_test.js | suite('serialization', function () {
setup(function () {
var documents = [{
id: 'a',
title: 'Mr. Green kills Colonel Mustard',
body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.',
wordCount: 19
},{
id: 'b',
title: 'Plumb waters plant',
body: 'Professor Plumb has a green plant in his study',
wordCount: 9
},{
id: 'c',
title: 'Scarlett helps Professor',
body: 'Miss Scarlett watered Professor Plumbs green plant while he was away from his office last week.',
wordCount: 16
}]
this.idx = lunr(function () {
this.ref('id')
this.field('title')
this.field('body')
documents.forEach(function (document) {
this.add(document)
}, this)
})
this.serializedIdx = JSON.stringify(this.idx)
this.loadedIdx = lunr.Index.load(JSON.parse(this.serializedIdx))
})
test('search', function () {
var idxResults = this.idx.search('green'),
serializedResults = this.loadedIdx.search('green')
assert.deepEqual(idxResults, serializedResults)
})
})
| suite('serialization', function () {
setup(function () {
var documents = [{
id: 'a',
title: 'Mr. Green kills Colonel Mustard',
body: 'Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.',
wordCount: 19
},{
id: 'b',
title: 'Plumb waters plant',
body: 'Professor Plumb has a green plant in his study',
wordCount: 9
},{
id: 'c',
title: 'Scarlett helps Professor',
body: 'Miss Scarlett watered Professor Plumbs green plant while he was away from his office last week.',
wordCount: 16
},{
id: 'd',
title: 'All about JavaScript',
body: 'JavaScript objects have a special __proto__ property',
wordCount: 7
}]
this.idx = lunr(function () {
this.ref('id')
this.field('title')
this.field('body')
documents.forEach(function (document) {
this.add(document)
}, this)
})
this.serializedIdx = JSON.stringify(this.idx)
this.loadedIdx = lunr.Index.load(JSON.parse(this.serializedIdx))
})
test('search', function () {
var idxResults = this.idx.search('green'),
serializedResults = this.loadedIdx.search('green')
assert.deepEqual(idxResults, serializedResults)
})
test('__proto__ double serialization', function () {
var doubleLoadedIdx = lunr.Index.load(JSON.parse(JSON.stringify(this.loadedIdx))),
idxResults = this.idx.search('__proto__'),
doubleSerializedResults = doubleLoadedIdx.search('__proto__')
assert.deepEqual(idxResults, doubleSerializedResults)
})
})
| Test that __proto__ is indexed across two serializations | Test that __proto__ is indexed across two serializations
I found while using lunr that __proto__ can slip through the
serialization process if you're serializing an index that was
itself loaded from a serialized index - it might not be a bad idea
to make sure that serializing an index loaded from a JSON blob
serializes to the exact same JSON blob (well, forgiving things like
a change in the order of the keys)
| JavaScript | mit | olivernn/lunr.js,olivernn/lunr.js,olivernn/lunr.js | ---
+++
@@ -15,6 +15,11 @@
title: 'Scarlett helps Professor',
body: 'Miss Scarlett watered Professor Plumbs green plant while he was away from his office last week.',
wordCount: 16
+ },{
+ id: 'd',
+ title: 'All about JavaScript',
+ body: 'JavaScript objects have a special __proto__ property',
+ wordCount: 7
}]
this.idx = lunr(function () {
@@ -37,4 +42,12 @@
assert.deepEqual(idxResults, serializedResults)
})
+
+ test('__proto__ double serialization', function () {
+ var doubleLoadedIdx = lunr.Index.load(JSON.parse(JSON.stringify(this.loadedIdx))),
+ idxResults = this.idx.search('__proto__'),
+ doubleSerializedResults = doubleLoadedIdx.search('__proto__')
+
+ assert.deepEqual(idxResults, doubleSerializedResults)
+ })
}) |
fbed3b71609ec1354bf5140d2bc3d28681d54709 | redirectToUpToDateDocumentation.user.js | redirectToUpToDateDocumentation.user.js | // ==UserScript==
// @name Redirect to up to date documentation
// @namespace sieradzki.it
// @description Detects if currently viewed online documentation page is the most recent version available, and if not, redirects user to the latest version.
// @version 1.0.0
// @match *://*/*
// ==/UserScript==
(function () {
'use strict';
var DocumentationRedirect = function () {
};
DocumentationRedirect.prototype.ifPageExists = function (url, callback) {
var request = new XMLHttpRequest();
request.open('HEAD', url, true);
request.timeout = 15000; // 15 seconds
request.onload = function () {
if (request.status < 400) {
callback();
}
};
request.send();
};
window.DocumentationRedirect = new DocumentationRedirect();
})();
| // ==UserScript==
// @name Redirect to up to date documentation
// @namespace sieradzki.it
// @description Detects if currently viewed online documentation page is the most recent version available, and if not, redirects user to the latest version.
// @version 1.0.0
// @match *://docs.oracle.com/javase/*
// ==/UserScript==
(function () {
'use strict';
var documentations = {
javaSE: {
currentVersion: '8',
isOutdatedDocumentationPage: function (url) {
var matches = url.match(/^http(s)?:\/\/docs\.oracle\.com\/javase\/([0-9\.]+)\/docs\/api\//);
return matches !== null && matches[2] !== this.currentVersion;
},
rewriteUrl: function (url) {
return url.replace(/\/javase\/([0-9\.]+)\/docs\/api\//, '/javase/'+ this.currentVersion + '/docs/api/');
}
}
};
var DocumentationRedirect = function () {
for (var key in documentations) {
if (documentations[key].isOutdatedDocumentationPage(window.location.href)) {
var rewrittenUrl = documentations[key].rewriteUrl(window.location.href);
this.ifPageExists(rewrittenUrl, function (url) {
window.location.replace(url);
});
break;
}
}
};
DocumentationRedirect.prototype.ifPageExists = function (url, callback) {
var request = new XMLHttpRequest();
request.open('HEAD', url, true);
request.timeout = 15000; // 15 seconds
request.onload = function () {
if (request.status < 400) {
callback(url);
}
};
request.send();
};
window.DocumentationRedirect = new DocumentationRedirect();
})();
| Add working redirection for Java SE documentation | Add working redirection for Java SE documentation
| JavaScript | mit | kuc/Redirect-to-up-to-date-documentation | ---
+++
@@ -3,13 +3,38 @@
// @namespace sieradzki.it
// @description Detects if currently viewed online documentation page is the most recent version available, and if not, redirects user to the latest version.
// @version 1.0.0
-// @match *://*/*
+// @match *://docs.oracle.com/javase/*
// ==/UserScript==
(function () {
'use strict';
+ var documentations = {
+ javaSE: {
+ currentVersion: '8',
+ isOutdatedDocumentationPage: function (url) {
+ var matches = url.match(/^http(s)?:\/\/docs\.oracle\.com\/javase\/([0-9\.]+)\/docs\/api\//);
+ return matches !== null && matches[2] !== this.currentVersion;
+ },
+ rewriteUrl: function (url) {
+ return url.replace(/\/javase\/([0-9\.]+)\/docs\/api\//, '/javase/'+ this.currentVersion + '/docs/api/');
+ }
+ }
+ };
+
var DocumentationRedirect = function () {
+
+ for (var key in documentations) {
+ if (documentations[key].isOutdatedDocumentationPage(window.location.href)) {
+ var rewrittenUrl = documentations[key].rewriteUrl(window.location.href);
+
+ this.ifPageExists(rewrittenUrl, function (url) {
+ window.location.replace(url);
+ });
+
+ break;
+ }
+ }
};
DocumentationRedirect.prototype.ifPageExists = function (url, callback) {
@@ -19,7 +44,7 @@
request.timeout = 15000; // 15 seconds
request.onload = function () {
if (request.status < 400) {
- callback();
+ callback(url);
}
};
request.send(); |
4c8392797d795261187a29d84f714cf9b116fcbc | client/components/ImageUpload.js | client/components/ImageUpload.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<div>
<button
className="btn btn-add"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Add Pics</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
// import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<button
className="btn btn-default"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Upload</button>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
| Update image upload button styling | Update image upload button styling
| JavaScript | mit | forkful/forkful,forkful/forkful,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,forkful/forkful | ---
+++
@@ -3,21 +3,19 @@
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
-import '../scss/_createRecipe.scss';
+// import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
- <div>
<button
- className="btn btn-add"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- uploadPicture(recipe);
- }}>Add Pics</button>
- </div>
+ className="btn btn-default"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ uploadPicture(recipe);
+ }}>Upload</button>
);
}
} |
a4d75a52e958995836c6136a05238a3a96dfbcf9 | tests/config/karma.unit.js | tests/config/karma.unit.js | module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',
// Test files
'tests/specs/*.js'
],
preprocessors: {
'js/*.js': ['coverage']
},
coverageReporter: {
reporters: [
{type: 'cobertura', dir: 'tests/coverage/cobertura'},
{type: 'html', dir: 'tests/coverage/html'}
]
},
reporters: ['dots', 'coverage', 'junit'],
junitReporter: {
outputFile: 'tests/results/junit-result.xml'
},
port: 9876,
runnerPort: 9910,
color: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS'],
singleRun: true
})
}
| module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',
// Test files
'tests/specs/*.js'
],
preprocessors: {
'js/**/*.js': ['coverage']
},
coverageReporter: {
reporters: [
{type: 'cobertura', dir: 'tests/coverage/cobertura'},
{type: 'html', dir: 'tests/coverage/html'}
]
},
reporters: ['dots', 'coverage', 'junit'],
junitReporter: {
outputFile: 'tests/results/junit-result.xml'
},
port: 9876,
runnerPort: 9910,
color: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS'],
singleRun: true
})
}
| Fix coverage to cover all files | Fix coverage to cover all files
| JavaScript | mit | Ikornaselur/coredata-api-service | ---
+++
@@ -15,7 +15,7 @@
'tests/specs/*.js'
],
preprocessors: {
- 'js/*.js': ['coverage']
+ 'js/**/*.js': ['coverage']
},
coverageReporter: {
reporters: [ |
5aa417475b32f75560c994fb7cff850e7663d4ca | static/script/user/view.js | static/script/user/view.js | $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: "json",
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
console.log( res );
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
| $( document ).ready( function() {
function showUploadedImage( source ) {
$( "#userImage" ).attr( "src", source );
}
$( "#image-form" ).submit( function() {
var image = document.getElementById( "image" ).files[ 0 ];
var token = $( "input[type=hidden]" ).val();
var formdata = new FormData();
var reader = new FileReader();
$( "#imageSubmit" ).hide();
$( "#uploading" ).show();
reader.onloadend = function ( e ) {
showUploadedImage( e.target.result );
}
reader.readAsDataURL( image );
formdata.append( "image", image );
formdata.append( "token", token );
$.ajax( {
url: "image/create",
type: "POST",
data: formdata,
cache: false,
dataType: false,
processData: false,
contentType: false,
success: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
},
error: function( res ) {
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
}
} );
return false;
} );
} );
| Make it not expect json | Make it not expect json
| JavaScript | mit | VitSalis/endofcodes,VitSalis/endofcodes,VitSalis/endofcodes,dionyziz/endofcodes,dionyziz/endofcodes,dionyziz/endofcodes,VitSalis/endofcodes | ---
+++
@@ -24,7 +24,7 @@
type: "POST",
data: formdata,
cache: false,
- dataType: "json",
+ dataType: false,
processData: false,
contentType: false,
success: function( res ) {
@@ -32,7 +32,6 @@
$( "#uploading" ).hide();
},
error: function( res ) {
- console.log( res );
$( "#imageSubmit" ).show();
$( "#uploading" ).hide();
} |
3a8ebb82e964b2deadfe5f216e6a54c0a847f482 | both/collections/groups.js | both/collections/groups.js | Groups = new Mongo.Collection('groups');
var GroupsSchema = new SimpleSchema({
name: {
type: String
}
});
// Add i18n tags
GroupsSchema.i18n("groups");
Groups.attachSchema(GroupsSchema);
Groups.helpers({
'homes': function () {
// Get group ID
var groupId = this._id;
// Get all homes assigned to group
var homes = Homes.find({'groupId': groupId}).fetch();
return homes;
}
});
Groups.allow({
insert: function () {
return true;
}
});
| Groups = new Mongo.Collection('groups');
var GroupsSchema = new SimpleSchema({
name: {
type: String
}
});
// Add i18n tags
GroupsSchema.i18n("groups");
Groups.attachSchema(GroupsSchema);
Groups.helpers({
'homes': function () {
// Get group ID
var groupId = this._id;
// Get all homes assigned to group
var homes = Homes.find({'groupId': groupId}).fetch();
return homes;
}
});
Groups.allow({
insert () {
// Get user ID
const userId = Meteor.userId();
// Check if user is administrator
const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
if (userIsAdmin) {
// admin user can insert
return true;
}
},
update () {
// Get user ID
const userId = Meteor.userId();
// Check if user is administrator
const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
if (userIsAdmin) {
// admin user can update
return true;
}
}
});
| Add update allow rule; refactor insert rule | Add update allow rule; refactor insert rule
| JavaScript | agpl-3.0 | GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing | ---
+++
@@ -24,7 +24,28 @@
});
Groups.allow({
- insert: function () {
- return true;
+ insert () {
+ // Get user ID
+ const userId = Meteor.userId();
+
+ // Check if user is administrator
+ const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
+
+ if (userIsAdmin) {
+ // admin user can insert
+ return true;
+ }
+ },
+ update () {
+ // Get user ID
+ const userId = Meteor.userId();
+
+ // Check if user is administrator
+ const userIsAdmin = Roles.userIsInRole(userId, ['admin']);
+
+ if (userIsAdmin) {
+ // admin user can update
+ return true;
+ }
}
}); |
be716adc76382618e44836f17b37a76a380b2094 | src/utils/hotfixes/DisableTextSelection.js | src/utils/hotfixes/DisableTextSelection.js | /**
* Created by tom on 08/07/16.
*/
let location = window.location;
let isWebsite = location.protocol.indexOf('http') !== -1 && location.host.indexOf('localhost') === -1;
if(!isWebsite) {
/* Source: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule */
var styleElement = document.createElement('style'),
styleSheet;
/* Append style element to head */
document.head.appendChild(styleElement);
/* Grab style sheet */
styleSheet = styleElement.sheet;
styleSheet.insertRule('*{-webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none;}', 0);
} | /**
* Created by tom on 08/07/16.
*/
var currentLocation = window.location;
var isWebsite = currentLocation.protocol.indexOf('http') !== -1 && currentLocation.host.indexOf('localhost') === -1;
if(!isWebsite) {
/* Source: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule */
var styleElement = document.createElement('style'),
styleSheet;
/* Append style element to head */
document.head.appendChild(styleElement);
console.log("Appending");
/* Grab style sheet */
styleSheet = styleElement.sheet;
styleSheet.insertRule('*{-webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none;}', 0);
}
| Patch hot fix to work on mobile | Patch hot fix to work on mobile
| JavaScript | mit | Bizboard/arva-mvc | ---
+++
@@ -2,8 +2,10 @@
* Created by tom on 08/07/16.
*/
-let location = window.location;
-let isWebsite = location.protocol.indexOf('http') !== -1 && location.host.indexOf('localhost') === -1;
+var currentLocation = window.location;
+var isWebsite = currentLocation.protocol.indexOf('http') !== -1 && currentLocation.host.indexOf('localhost') === -1;
+
+
if(!isWebsite) {
/* Source: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule */
@@ -12,6 +14,7 @@
/* Append style element to head */
document.head.appendChild(styleElement);
+ console.log("Appending");
/* Grab style sheet */
styleSheet = styleElement.sheet; |
0b748d12de5d129f7e2ec84e0f0d957a677e9f16 | example/main.js | example/main.js | import { Core,
Dummy,
Dashboard,
GoogleDrive,
Webcam,
Tus10,
MetaData,
Informer } from '../src/index.js'
// import ru_RU from '../src/locales/ru_RU.js'
// import MagicLog from '../src/plugins/MagicLog'
const uppy = new Core({debug: true, autoProceed: false})
.use(Dashboard, {trigger: '#uppyModalOpener', inline: false})
.use(GoogleDrive, {target: Dashboard, host: 'http://ya.ru'})
.use(Dummy, {target: Dashboard})
.use(Webcam, {target: Dashboard})
// .use(ProgressBar, {target: Dashboard})
.use(Tus10, {endpoint: 'http://master.tus.io:8080/files/', resume: false})
.use(Informer, {target: Dashboard})
.use(MetaData, {
fields: [
{ id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
{ id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
]
})
uppy.run()
// uppy.emit('informer', 'Smile!', 'info', 2000)
uppy.on('core:success', (fileCount) => {
console.log(fileCount)
})
document.querySelector('#uppyModalOpener').click()
| import { Core,
Dummy,
Dashboard,
GoogleDrive,
Webcam,
Tus10,
MetaData,
Informer } from '../src/index.js'
// import ru_RU from '../src/locales/ru_RU.js'
// import MagicLog from '../src/plugins/MagicLog'
const uppy = new Core({debug: true, autoProceed: false})
.use(Dashboard, {trigger: '#uppyModalOpener', inline: false})
.use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
.use(Dummy, {target: Dashboard})
.use(Webcam, {target: Dashboard})
// .use(ProgressBar, {target: Dashboard})
.use(Tus10, {endpoint: 'http://master.tus.io:8080/files/', resume: false})
.use(Informer, {target: Dashboard})
.use(MetaData, {
fields: [
{ id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
{ id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
]
})
uppy.run()
// uppy.emit('informer', 'Smile!', 'info', 2000)
uppy.on('core:success', (fileCount) => {
console.log(fileCount)
})
document.querySelector('#uppyModalOpener').click()
| Switch to example to localhost uppy-server | Switch to example to localhost uppy-server
| JavaScript | mit | varung-optimus/uppy,transloadit/uppy,varung-optimus/uppy,transloadit/uppy,transloadit/uppy,transloadit/uppy,varung-optimus/uppy | ---
+++
@@ -12,7 +12,7 @@
const uppy = new Core({debug: true, autoProceed: false})
.use(Dashboard, {trigger: '#uppyModalOpener', inline: false})
- .use(GoogleDrive, {target: Dashboard, host: 'http://ya.ru'})
+ .use(GoogleDrive, {target: Dashboard, host: 'http://localhost:3020'})
.use(Dummy, {target: Dashboard})
.use(Webcam, {target: Dashboard})
// .use(ProgressBar, {target: Dashboard}) |
7ce1ab4d5b06b93e73276638e9a91086bb54463a | public/js/custom.layout.js | public/js/custom.layout.js | // Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0.
$(document).ready(function () {
'use strict';
var hideDownloadsForAnon = function () {
if (json.global.logged !== "1") {
$('.downloadObject').hide();
}
};
// Go to the landing page.
$('div.HeaderLogo').unbind('click').click(function () {
window.location = json.global.webroot;
});
// Remove download links if the user is not logged into the system.
hideDownloadsForAnon();
midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED',
'rsnabranding', hideDownloadsForAnon);
// Change upload button to "Request Upload"
$('.uploadFile-top')
.empty()
.unbind()
.html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>")
.click(function (evt) {
if (evt.originalEvent) {
window.location = "https://www.rsna.org/QIDW-Contributor-Request/";
}
});
// Hide the users and feed links
$('#menuUsers').hide();
$('#menuFeed').hide();
});
| // Midas Server. Copyright Kitware SAS. Licensed under the Apache License 2.0.
$(document).ready(function () {
'use strict';
var hideDownloadsForAnon = function () {
if (json.global.logged !== "1") {
$('.downloadObject').hide();
}
};
// Go to the landing page.
$('div.HeaderLogo').unbind('click').click(function () {
window.location = json.global.webroot;
});
// Remove download links if the user is not logged into the system.
hideDownloadsForAnon();
midas.registerCallback('CALLBACK_CORE_RESOURCE_HIGHLIGHTED',
'rsnabranding', hideDownloadsForAnon);
// Change upload button to "Request Upload"
$('.uploadFile-top')
.empty()
.unbind()
.html("<div style=\"color: white; font-size: 14pt; padding-top: 2px;\">Request Upload</div>")
.click(function (evt) {
if (evt.originalEvent) {
window.location = "https://www.rsna.org/QIDW-Contributor-Request/";
}
});
// Hide the users and feed links
$('#menuUsers').hide();
$('#menuFeed').hide();
// Hide user deletion for non admins
$('#userDeleteActionNonAdmin').hide();
});
| Hide user deletion for non-admins. | Hide user deletion for non-admins.
| JavaScript | apache-2.0 | midasplatform/rsnabranding,midasplatform/rsnabranding,midasplatform/rsnabranding | ---
+++
@@ -34,4 +34,7 @@
$('#menuUsers').hide();
$('#menuFeed').hide();
+ // Hide user deletion for non admins
+ $('#userDeleteActionNonAdmin').hide();
+
}); |
b8142700dbe5c9f4031c866cd6ac2d4dba2c55ee | app/js/models/key_pair.js | app/js/models/key_pair.js | (function(bitcoinWorker, Models) {
function KeyPair() {
self = this;
self.isGenerated = false;
// self.bitcoin_worker = new Worker('/js/workers/bitcoin_worker.js');
// self.bitcoin_worker.postMessage();
// self.bitcoin_worker.currentMessageId = 0;
// self.bitcoin_worker.callbacks = {};
// self.bitcoin_worker.onmessage = function(e) {
// var message = e.data;
// self.bitcoin_worker.callbacks[message.id].apply(null, [message.result]);
// delete self.bitcoin_worker.callbacks[message.id];
// };
// self.bitcoin_worker.async = function(functionName, params, hollaback) {
// var message = {
// id: self.bitcoin_worker.currentMessageId,
// functionName: functionName,
// params: params,
// };
// self.bitcoin_worker.callbacks[message.id] = hollaback;
// self.bitcoin_worker.postMessage(message);
// self.bitcoin_worker.currentMessageId++;
// };
}
KeyPair.prototype.generate = function(password, hollaback) {
var self = this;
var params = [
Models.entropy.randomWords(32),
password
];
bitcoinWorker.async("seedGenerateAndEncryptKeys", params, function(keyPair) {
self.isGenerated = true;
self.encryptedPrivateKeyExponent = keyPair.encryptedPrivateKeyExponent;
self.publicKeyX = keyPair.publicKeyX;
self.publicKeyY = keyPair.publicKeyY;
// self.bitcoinAddress = keyPair.bitcoinAddress;
self.bitcoinAddress = "1GyqJhgVYkjBgEy8wf2iApwx4EvU3LvEtR";
if (typeof hollaback === "function") {
hollaback(keyPair);
}
self.trigger('keyPair.generate', keyPair);
});
};
MicroEvent.mixin(KeyPair);
Models.keyPair = new KeyPair();
})(CoinPocketApp.Models.bitcoinWorker, CoinPocketApp.Models);
| (function(bitcoinWorker, Models) {
function KeyPair() {
self = this;
self.isGenerated = false;
}
KeyPair.prototype.generate = function(password, hollaback) {
var self = this;
var params = [
Models.entropy.randomWords(32),
password
];
bitcoinWorker.async("seedGenerateAndEncryptKeys", params, function(keyPair) {
self.isGenerated = true;
self.encryptedPrivateKeyExponent = keyPair.encryptedPrivateKeyExponent;
self.publicKeyX = keyPair.publicKeyX;
self.publicKeyY = keyPair.publicKeyY;
self.bitcoinAddress = keyPair.bitcoinAddress;
if (typeof hollaback === "function") {
hollaback(keyPair);
}
self.trigger('keyPair.generate', keyPair);
});
};
MicroEvent.mixin(KeyPair);
Models.keyPair = new KeyPair();
})(CoinPocketApp.Models.bitcoinWorker, CoinPocketApp.Models);
| Clean up and remove stub | Clean up and remove stub
| JavaScript | mit | MrBluePotato/Dogepocket,enriquez/coinpocketapp.com,MrBluePotato/Dogepocket,enriquez/coinpocketapp.com,enriquez/coinpocketapp.com | ---
+++
@@ -4,29 +4,6 @@
self = this;
self.isGenerated = false;
-
- // self.bitcoin_worker = new Worker('/js/workers/bitcoin_worker.js');
- // self.bitcoin_worker.postMessage();
- // self.bitcoin_worker.currentMessageId = 0;
- // self.bitcoin_worker.callbacks = {};
- // self.bitcoin_worker.onmessage = function(e) {
- // var message = e.data;
- // self.bitcoin_worker.callbacks[message.id].apply(null, [message.result]);
- // delete self.bitcoin_worker.callbacks[message.id];
- // };
-
- // self.bitcoin_worker.async = function(functionName, params, hollaback) {
- // var message = {
- // id: self.bitcoin_worker.currentMessageId,
- // functionName: functionName,
- // params: params,
- // };
-
- // self.bitcoin_worker.callbacks[message.id] = hollaback;
- // self.bitcoin_worker.postMessage(message);
-
- // self.bitcoin_worker.currentMessageId++;
- // };
}
KeyPair.prototype.generate = function(password, hollaback) {
@@ -43,8 +20,7 @@
self.encryptedPrivateKeyExponent = keyPair.encryptedPrivateKeyExponent;
self.publicKeyX = keyPair.publicKeyX;
self.publicKeyY = keyPair.publicKeyY;
- // self.bitcoinAddress = keyPair.bitcoinAddress;
- self.bitcoinAddress = "1GyqJhgVYkjBgEy8wf2iApwx4EvU3LvEtR";
+ self.bitcoinAddress = keyPair.bitcoinAddress;
if (typeof hollaback === "function") {
hollaback(keyPair); |
d4fe86d1e075e35c7e4a0181c12b147f22f0b418 | GraphiQL/webpack.config.js | GraphiQL/webpack.config.js | const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader", "style-loader"]
}
]
}
};
| const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist")
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
}
};
| Correct the order of css loaders. | Correct the order of css loaders.
| JavaScript | mit | dadish/ProcessGraphQL,dadish/ProcessGraphQL | ---
+++
@@ -10,7 +10,7 @@
rules: [
{
test: /\.css$/,
- use: ["css-loader", "style-loader"]
+ use: ["style-loader", "css-loader"]
}
]
} |
d868839ac1cb21eaa48dfbca97f3c629131796a6 | client/mobrender/components/widget.connected.js | client/mobrender/components/widget.connected.js | import { connect } from 'react-redux'
import { asyncUpdateWidget as update } from '../action-creators'
import Widget from './widget'
const mapStateToProps = (state, props) => ({
saving: state.widgets.saving,
})
const mapActionsToProps = { update }
export default connect(mapStateToProps, mapActionsToProps)(Widget)
| import { connect } from 'react-redux'
import { asyncUpdateWidget as update } from '../redux/action-creators'
import Widget from './widget'
const mapStateToProps = (state, props) => ({
saving: state.widgets.saving,
})
const mapActionsToProps = { update }
export default connect(mapStateToProps, mapActionsToProps)(Widget)
| Fix import to update widget action | Fix import to update widget action
| JavaScript | agpl-3.0 | nossas/bonde-client,nossas/bonde-client,nossas/bonde-client | ---
+++
@@ -1,5 +1,5 @@
import { connect } from 'react-redux'
-import { asyncUpdateWidget as update } from '../action-creators'
+import { asyncUpdateWidget as update } from '../redux/action-creators'
import Widget from './widget'
const mapStateToProps = (state, props) => ({ |
edd3ee4cbe2ad7f0ac3a3b975a4f9c2d573ce013 | tasks-gulp/config/watch.js | tasks-gulp/config/watch.js | /**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
module.exports = function(gulp, plugins, growl) {
var server = plugins.livereload();
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
};
| /**
* Run predefined tasks whenever watched file patterns are added, changed or deleted.
*
* ---------------------------------------------------------------
*
* Watch for changes on
* - files in the `assets` folder
* - the `tasks/pipeline.js` file
* and re-run the appropriate tasks.
*
*
*/
var server = require('gulp-livereload');
module.exports = function(gulp, plugins, growl) {
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets'])
.on('change', function(file) {
server.changed(file.path);
});
});
}; | Change to prevent livereload from dying on certain file changes. | Change to prevent livereload from dying on certain file changes.
| JavaScript | mit | JoshDobbin/CrispyAdmin,JoshDobbin/CrispyAdmin,JoshDobbin/CrispyAdmin | ---
+++
@@ -10,8 +10,9 @@
*
*
*/
+var server = require('gulp-livereload');
+
module.exports = function(gulp, plugins, growl) {
- var server = plugins.livereload();
gulp.task('watch:api', function() {
// Watch Style files
return gulp.watch('api/**/*', ['syncAssets'])
@@ -19,7 +20,7 @@
server.changed(file.path);
});
});
-
+
gulp.task('watch:assets', function() {
// Watch assets
return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets']) |
d44749756d41329802e332658105640aa5aa2ea8 | app/assets/javascripts/blogelator/routes/posts_new_route.js | app/assets/javascripts/blogelator/routes/posts_new_route.js | (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.deleteRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return App.Post.createRecord();
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
| (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
record.destroyRecord();
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.destroyRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return this.store.createRecord('post');
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
| Fix new route after new ember-data | Fix new route after new ember-data
| JavaScript | mit | codelation/blogelator,codelation/blogelator,codelation/blogelator | ---
+++
@@ -10,13 +10,14 @@
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
+ record.destroyRecord();
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
- record.deleteRecord();
+ record.destroyRecord();
return true;
} else {
transition.abort();
@@ -37,7 +38,7 @@
},
model: function() {
- return App.Post.createRecord();
+ return this.store.createRecord('post');
},
renderTemplate: function() { |
75817975623de3b2ebd5482ffff9d021cccfc96b | lib/control-panel/js/app.js | lib/control-panel/js/app.js | /*global window*/
/*global angular*/
/*global ___socket___*/
(function (window, socket) {
"use strict";
var app = angular.module("BrowserSync", []);
/**
* Socket Factory
*/
app.service("Socket", function () {
return {
addEvent: function (name, callback) {
socket.on(name, callback);
},
removeEvent: function (name, callback) {
socket.removeListener(name, callback);
}
};
});
/**
* Options Factory
*/
app.service("Options", function () {
return {
}
});
app.controller("MainCtrl", function ($scope, Socket) {
$scope.options = {};
$scope.socketEvents = {
connection: function (options) {
$scope.$apply(function () {
$scope.options = options;
});
}
};
Socket.addEvent("connection", $scope.socketEvents.connection);
});
}(window, (typeof ___socket___ === "undefined") ? {} : ___socket___)); | /*global window*/
/*global angular*/
/*global ___socket___*/
(function (window, socket) {
"use strict";
var app = angular.module("BrowserSync", []);
/**
* Socket Factory
*/
app.service("Socket", function () {
return {
addEvent: function (name, callback) {
socket.on(name, callback);
},
removeEvent: function (name, callback) {
socket.removeListener(name, callback);
}
};
});
/**
* Options Factory
*/
app.service("Options", function () {
return {
};
});
app.controller("MainCtrl", function ($scope, Socket) {
$scope.options = {};
$scope.socketEvents = {
connection: function (options) {
$scope.$apply(function () {
$scope.options = options;
});
}
};
Socket.addEvent("connection", $scope.socketEvents.connection);
});
}(window, (typeof ___socket___ === "undefined") ? {} : ___socket___)); | Add control-panel asset & initial specs | Add control-panel asset & initial specs
| JavaScript | apache-2.0 | pmq20/browser-sync,Iced-Tea/browser-sync,BrowserSync/browser-sync,BrowserSync/browser-sync,syarul/browser-sync,nitinsurana/browser-sync,d-g-h/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,shelsonjava/browser-sync,felixdae/browser-sync,zhelezko/browser-sync,BrowserSync/browser-sync,mcanthony/browser-sync,harmoney-nikr/browser-sync,mnquintana/browser-sync,cnbin/browser-sync,portned/browser-sync,pepelsbey/browser-sync,nothiphop/browser-sync,chengky/browser-sync,michaelgilley/browser-sync,portned/browser-sync,schmod/browser-sync,harmoney-nikr/browser-sync,Teino1978-Corp/Teino1978-Corp-browser-sync,pmq20/browser-sync,naoyak/browser-sync,naoyak/browser-sync,nothiphop/browser-sync,mcanthony/browser-sync,syarul/browser-sync,guiquanz/browser-sync,EdwonLim/browser-sync,stevemao/browser-sync,BrowserSync/browser-sync,shelsonjava/browser-sync,michaelgilley/browser-sync,Plou/browser-sync,d-g-h/browser-sync,markcatley/browser-sync,zhelezko/browser-sync,beni55/browser-sync,pepelsbey/browser-sync,nitinsurana/browser-sync,EdwonLim/browser-sync,felixdae/browser-sync,stevemao/browser-sync,Iced-Tea/browser-sync,beni55/browser-sync,lookfirst/browser-sync,chengky/browser-sync,guiquanz/browser-sync,schmod/browser-sync,Plou/browser-sync | ---
+++
@@ -27,7 +27,7 @@
app.service("Options", function () {
return {
- }
+ };
});
app.controller("MainCtrl", function ($scope, Socket) { |
d4ec5ba0c60c0ab81f7b8945bbafff578e59ff20 | app/scripts.babel/contentscript.js | app/scripts.babel/contentscript.js | 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
}
}
| 'use strict';
console.log('\'Allo \'Allo! Content script');
// https://gist.github.com/dkniffin/b6f5dd4e1bde716e7b32#gistcomment-1980578
function toggle_visibility(data_id) {
var matches = document.querySelectorAll(data_id);
[].forEach.call(matches, function(e) {
if(e.style.display == 'none') {
e.style.display = 'table-cell';
} else {
e.style.display = 'none';
}
});
}
window.addEventListener ('load', myMain, false);
function myMain (evt) {
var jsInitChecktimer = setInterval (checkForDomReady, 111);
function checkForDomReady () {
var selector = jQuery('#ghx-column-headers > li.ghx-column');
if (selector) {
selector.append(function() {
return jQuery('<a href="#" class="column-header-hider"><i class="aui-icon aui-icon-small aui-iconfont-remove-label ghx-iconfont"></i></a>')
.click(function() {
var col = jQuery(this).parent().data('id');
toggle_visibility('[data-id="'+col+'"]');
toggle_visibility('[data-column-id="'+col+'"]');
});
});
clearInterval(jsInitChecktimer);
}
var somePadding = jQuery('.ghx-wrap-issue');
if(somePadding){
somePadding.css('padding-top','20px');
}
}
}
| Add CSS for moving cards down a little | Add CSS for moving cards down a little
| JavaScript | mit | GabLeRoux/hide-jira-board-columns,GabLeRoux/hide-jira-board-columns | ---
+++
@@ -32,5 +32,10 @@
});
clearInterval(jsInitChecktimer);
}
+
+ var somePadding = jQuery('.ghx-wrap-issue');
+ if(somePadding){
+ somePadding.css('padding-top','20px');
+ }
}
} |
ca3373c477bcc7e351554e02b4b4c262e27ed059 | test/FBTestFireformat.js | test/FBTestFireformat.js | /* See license.txt for terms of usage */
var Format = {};
Components.utils.import("resource://fireformat/formatters.jsm", Format);
var Firebug = FW.Firebug;
var FBTestFireformat = {
PrefHandler: function(prefs) {
var original = [], globals = {};
for (var i = 0; i < prefs.length; i++) {
original.push(Firebug.getPref(Firebug.prefDomain, prefs[i]));
}
return {
setGlobal: function(pref, value) {
if (!globals.hasOwnProperty(pref)) {
globals[pref] = Firebug.getPref(Firebug.prefDomain, pref);
}
Firebug.setPref(Firebug.prefDomain, pref, value);
},
setPrefs: function() {
for (var i = 0; i < arguments.length; i++) {
Firebug.setPref(Firebug.prefDomain, prefs[i], arguments[i]);
}
},
reset: function() {
this.setPrefs.apply(this, original);
for (var x in globals) {
if (globals.hasOwnProperty(x)) {
Firebug.setPref(Firebug.prefDomain, x, globals[x]);
}
}
globals = {};
}
};
}
}; | /* See license.txt for terms of usage */
var Format = {};
Components.utils.import("resource://fireformat/formatters.jsm", Format);
var Firebug = FW.Firebug;
var FBTestFireformat = {
PrefHandler: function(prefs) {
var original = [], globals = {};
for (var i = 0; i < prefs.length; i++) {
original.push(Firebug.getPref(Firebug.prefDomain, prefs[i]));
}
return {
setGlobal: function(pref, value) {
if (!globals.hasOwnProperty(pref)) {
globals[pref] = Firebug.getPref(Firebug.prefDomain, pref);
}
Firebug.setPref(Firebug.prefDomain, pref, value);
},
setPrefs: function() {
for (var i = 0; i < arguments.length; i++) {
Firebug.setPref(Firebug.prefDomain, prefs[i], arguments[i]);
}
for (; i < prefs.length; i++) {
Firebug.setPref(Firebug.prefDomain, prefs[i], original[i]);
}
},
reset: function() {
this.setPrefs.apply(this, original);
for (var x in globals) {
if (globals.hasOwnProperty(x)) {
Firebug.setPref(Firebug.prefDomain, x, globals[x]);
}
}
globals = {};
}
};
}
}; | Reset prefs that are not explicitly passed into setPrefs | Reset prefs that are not explicitly passed into setPrefs
git-svn-id: 6772fbf0389af6646c0263f7120f2a1d688953ed@5182 e969d3be-0e28-0410-a27f-dd5c76401a8b
| JavaScript | bsd-3-clause | kpdecker/fireformat | ---
+++
@@ -22,6 +22,9 @@
for (var i = 0; i < arguments.length; i++) {
Firebug.setPref(Firebug.prefDomain, prefs[i], arguments[i]);
}
+ for (; i < prefs.length; i++) {
+ Firebug.setPref(Firebug.prefDomain, prefs[i], original[i]);
+ }
},
reset: function() {
this.setPrefs.apply(this, original); |
7ed647f025681828dee8295b3a0976354f3f2162 | configs/grunt/mochaTest.js | configs/grunt/mochaTest.js | module.exports = {
options: { reporter: 'spec' },
all: { src: 'test/*-test.js' },
app: { src: 'test/app-test.js' },
node: { src: 'test/node-test.js' },
nodeServer: { src: 'test/node-server-test.js' }
};
| module.exports = {
options: { reporter: 'spec' },
all: {
src: [
'test/app-test.js',
'test/node-test.js',
'test/node-server-test.js'
]
},
app: { src: 'test/app-test.js' },
node: { src: 'test/node-test.js' },
nodeServer: { src: 'test/node-server-test.js' }
};
| Enforce order of tests when running all. | Enforce order of tests when running all.
| JavaScript | bsd-2-clause | KK578/generator-kk578,KK578/generator-kk578 | ---
+++
@@ -1,6 +1,12 @@
module.exports = {
options: { reporter: 'spec' },
- all: { src: 'test/*-test.js' },
+ all: {
+ src: [
+ 'test/app-test.js',
+ 'test/node-test.js',
+ 'test/node-server-test.js'
+ ]
+ },
app: { src: 'test/app-test.js' },
node: { src: 'test/node-test.js' },
nodeServer: { src: 'test/node-server-test.js' } |
30dd78fb19b0a378a9ca6bdc4b70d82f23d97d71 | projects/gear-ratio/webpack.config.js | projects/gear-ratio/webpack.config.js | const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const BUILD_DIR = path.resolve(__dirname, 'build')
module.exports = {
entry: {
'content_script/dashboard': './src/content_script/dashboard.js',
'content_script/gear': './src/content_script/gear.js'
},
output: {
path: BUILD_DIR,
filename: '[name].js'
},
// TODO: parameterize
mode: 'development',
optimization: { minimize: false },
module: {
},
// TODO: Copy from web-extension-polyfill
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: './addon/', to: BUILD_DIR }
]
})
]
}
| const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const BUILD_DIR = path.resolve(__dirname, 'build')
module.exports = {
entry: {
'content_script/dashboard': './src/content_script/dashboard/index.js',
'content_script/gear': './src/content_script/gear/index.js'
},
output: {
path: BUILD_DIR,
filename: '[name].js'
},
// TODO: parameterize
mode: 'development',
optimization: { minimize: false },
module: {
},
// TODO: Copy from web-extension-polyfill
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: './addon/', to: BUILD_DIR }
]
})
]
}
| Move content scripts to own dir | Move content scripts to own dir
| JavaScript | agpl-3.0 | erik/sketches,erik/sketches,erik/sketches,erik/sketches,erik/sketches,erik/sketches,erik/sketches,erik/sketches | ---
+++
@@ -5,8 +5,8 @@
module.exports = {
entry: {
- 'content_script/dashboard': './src/content_script/dashboard.js',
- 'content_script/gear': './src/content_script/gear.js'
+ 'content_script/dashboard': './src/content_script/dashboard/index.js',
+ 'content_script/gear': './src/content_script/gear/index.js'
},
output: { |
397ed5a09edd16cac35ea6f30173b10841a46c7a | gulp/scripts.js | gulp/scripts.js | 'use strict';
var gulp = require('gulp');
var env = require('node-env-file');
env(".env");
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('scripts', function () {
return gulp.src(paths.src + '/{app,components}/**/*.coffee')
.pipe($.replace('PUSHER_APP_KEY', process.env.PUSHER_APP_KEY))
.pipe($.coffeelint())
.pipe($.coffeelint.reporter())
.pipe($.coffee())
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe(gulp.dest(paths.tmp + '/serve/'))
.pipe($.size())
});
| 'use strict';
var gulp = require('gulp');
var env = require('node-env-file');
try {
env(__dirname + "/.env");
} catch (_error) {
console.log(_error);
}
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('scripts', function () {
return gulp.src(paths.src + '/{app,components}/**/*.coffee')
.pipe($.replace('PUSHER_APP_KEY', process.env.PUSHER_APP_KEY))
.pipe($.coffeelint())
.pipe($.coffeelint.reporter())
.pipe($.coffee())
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe(gulp.dest(paths.tmp + '/serve/'))
.pipe($.size())
});
| Allow build with no env file | Allow build with no env file | JavaScript | mit | adambutler/geo-pusher,adambutler/geo-pusher,adambutler/geo-pusher | ---
+++
@@ -2,7 +2,12 @@
var gulp = require('gulp');
var env = require('node-env-file');
-env(".env");
+
+try {
+ env(__dirname + "/.env");
+} catch (_error) {
+ console.log(_error);
+}
var paths = gulp.paths;
|
3df8a507d11831c60cf0bef33d6e0872ef167117 | resources/public/common/dataSource.js | resources/public/common/dataSource.js | var dataSource = function () {
var module = {};
module.load = function (url, callback) {
d3.json(url, function (_, data) {
callback(data);
});
};
module.loadCSV = function (url, callback) {
d3.csv(url, function (_, data) {
callback(data);
});
};
return module;
}();
| var dataSource = function () {
var module = {};
module.load = function (url, callback) {
d3.json(url, function (error, data) {
if (error) return console.warn(error);
callback(data);
});
};
module.loadCSV = function (url, callback) {
d3.csv(url, function (error, data) {
if (error) return console.warn(error);
callback(data);
});
};
return module;
}();
| Handle ajax errors, don't show 'no content' | Handle ajax errors, don't show 'no content'
| JavaScript | bsd-2-clause | cburgmer/buildviz,cburgmer/buildviz,cburgmer/buildviz | ---
+++
@@ -2,13 +2,17 @@
var module = {};
module.load = function (url, callback) {
- d3.json(url, function (_, data) {
+ d3.json(url, function (error, data) {
+ if (error) return console.warn(error);
+
callback(data);
});
};
module.loadCSV = function (url, callback) {
- d3.csv(url, function (_, data) {
+ d3.csv(url, function (error, data) {
+ if (error) return console.warn(error);
+
callback(data);
});
}; |
1e7176484d41769d04d46b2f8877764a87e17851 | puzzles/99_Bottles/javascript/99bottles.js | puzzles/99_Bottles/javascript/99bottles.js | let bottles = 99;
while (bottles != 0)
{
console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
--bottles;
console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
}
console.log('No more bottles of beer on the wall, no more bottles of beer.');
console.log('Go to the store and buy some more, 99 bottles of beer on the wall.');
| let bottles = 99;
while (bottles != 0)
{
if (bottles === 1) {
console.log(`${bottles} bottle of beer on the wall, ${bottles} bottles of beer.`);
} else {
console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
}
--bottles;
if (bottles === 1) {
console.log(`Take one down and pass it around, ${bottles} bottle of beer on the wall.`);
} else if (bottles === 0) {
console.log(`Take one down and pass it around, no more bottles of beer on the wall.`);
} else {
console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
}
}
console.log('No more bottles of beer on the wall, no more bottles of beer.');
console.log('Go to the store and buy some more, 99 bottles of beer on the wall.');
| Add condition for one bottle | Add condition for one bottle
It will now print -
"2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.
1 bottle of beer on the wall, 1 bottle of beer."
instead of -
"2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle(s) of beer on the wall.
1 bottle(s) of beer on the wall, 1 bottle(s) of beer." | JavaScript | cc0-1.0 | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms | ---
+++
@@ -1,9 +1,21 @@
let bottles = 99;
while (bottles != 0)
{
- console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
- --bottles;
- console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
+ if (bottles === 1) {
+ console.log(`${bottles} bottle of beer on the wall, ${bottles} bottles of beer.`);
+ } else {
+ console.log(`${bottles} bottles of beer on the wall, ${bottles} bottles of beer.`);
+ }
+
+ --bottles;
+
+ if (bottles === 1) {
+ console.log(`Take one down and pass it around, ${bottles} bottle of beer on the wall.`);
+ } else if (bottles === 0) {
+ console.log(`Take one down and pass it around, no more bottles of beer on the wall.`);
+ } else {
+ console.log(`Take one down and pass it around, ${bottles} bottles of beer on the wall.`);
+ }
}
console.log('No more bottles of beer on the wall, no more bottles of beer.');
console.log('Go to the store and buy some more, 99 bottles of beer on the wall.'); |
d034c23af62b0b007471ce7d178f1878e695243b | app/assets/javascripts/delete_open_session.js | app/assets/javascripts/delete_open_session.js | var deleteOpenSession = function(timeslot_id){
event.preventDefault();
$("#modal_remote").modal('hide');
swal({
title: "Are you sure you wish to cancel?",
text: "This will delete your mentoring timeslot.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel this mentoring timeslot.",
cancelButtonText: "No, I've changed my mind.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "DELETE",
url: "/api/timeslots/" + timeslot_id
}).done(function(){
swal({
title: "Deleted!",
text: "Your mentoring availabilty has been removed.",
confirmButtonColor: "#66BB6A",
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
else {
swal({
title: "Cancelled",
text: "Your availabilty is still scheduled.",
confirmButtonColor: "#2196F3",
type: "error"
});
}
});
}
| var deleteOpenSession = function(timeslot_id){
event.preventDefault();
$("#modal_remote").modal('hide');
swal({
title: "Are you sure you wish to cancel?",
text: "This will delete your mentoring timeslot.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#EF5350",
confirmButtonText: "Yes, cancel this mentoring timeslot.",
cancelButtonText: "No, I've changed my mind.",
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
$.ajax({
type: "DELETE",
url: "/api/timeslots/" + timeslot_id
}).done(function(){
swal({
title: "Deleted!",
text: "Your mentoring availabilty has been removed.",
confirmButtonColor: "#FFFFFF",
showConfirmButton: false,
allowOutsideClick: true,
timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function() {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
}
});
}
| Add timer and remove confirm buttonk, overall cleanup for better ux | Add timer and remove confirm buttonk, overall cleanup for better ux
| JavaScript | mit | theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board | ---
+++
@@ -10,7 +10,7 @@
confirmButtonText: "Yes, cancel this mentoring timeslot.",
cancelButtonText: "No, I've changed my mind.",
closeOnConfirm: false,
- closeOnCancel: false
+ closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
@@ -21,7 +21,10 @@
swal({
title: "Deleted!",
text: "Your mentoring availabilty has been removed.",
- confirmButtonColor: "#66BB6A",
+ confirmButtonColor: "#FFFFFF",
+ showConfirmButton: false,
+ allowOutsideClick: true,
+ timer: 1500,
type: "info"
});
$('#tutor-cal').fullCalendar('refetchEvents');
@@ -34,13 +37,5 @@
});
});
}
- else {
- swal({
- title: "Cancelled",
- text: "Your availabilty is still scheduled.",
- confirmButtonColor: "#2196F3",
- type: "error"
- });
- }
});
} |
aec02042fa069c87506e27c7756404368e755523 | web/src/stores/settings.js | web/src/stores/settings.js | import i18n from 'i18next';
const $app = document.getElementById('app');
class StoreSettings {
data = {}
defaultData = {
lang: i18n.languages[0] || 'en',
theme: 'light',
view: 'map',
debug: 0
}
// Update setting, optionally save to localStorage.
update(key, value, save) {
if (save) {
this.data[key] = value;
localStorage.setItem('settings', JSON.stringify(this.data));
}
// Handle setting side effects.
switch (key) {
case 'lang':
i18n.changeLanguage(value);
document.body.parentElement.setAttribute('lang', value);
break;
case 'theme':
$app.setAttribute('data-theme', value);
break;
case 'debug':
$app.className = 'is-debug-' + value;
break;
}
}
// Load and apply settings.
constructor() {
this.data = { ...this.defaultData, ...JSON.parse(localStorage.getItem('settings') || '{}') };
for (const key of Object.keys(this.data)) this.update(key, this.data[key]);
}
}
export default new StoreSettings();
| import i18n from 'i18next';
const $app = document.getElementById('app');
class StoreSettings {
data = {}
defaultData = {
lang: i18n.languages[0] || 'en',
theme: 'light',
view: 'map',
debug: 0
}
// Update setting, optionally save to localStorage.
update(key, value, save) {
if (save) {
this.data[key] = value;
localStorage.setItem('settings', JSON.stringify(this.data));
}
// Handle setting side effects.
switch (key) {
case 'lang':
i18n.changeLanguage(value);
document.body.parentElement.setAttribute('lang', value);
break;
case 'theme':
$app.setAttribute('data-theme', value);
break;
case 'debug':
$app.className = 'is-debug-' + value;
break;
default: break;
}
}
// Load and apply settings.
constructor() {
this.data = { ...this.defaultData, ...JSON.parse(localStorage.getItem('settings') || '{}') };
for (const key of Object.keys(this.data)) this.update(key, this.data[key]);
}
}
export default new StoreSettings();
| Add default case for switch (web) | Add default case for switch (web)
| JavaScript | agpl-3.0 | karlkoorna/Bussiaeg,karlkoorna/Bussiaeg | ---
+++
@@ -32,6 +32,7 @@
case 'debug':
$app.className = 'is-debug-' + value;
break;
+ default: break;
}
}
|
99939b68695d1b8b6ff9f765abe7a742c6017845 | background.js | background.js | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
); | chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({
name: "X-Molotov-Agent",
value: "{\"app_id\":\"electron_app\",\"app_build\":1,\"app_version_name\":\"0.9.6\",\"type\":\"desktop\",\"os\":\"\",\"os_version\":\"\",\"manufacturer\":\"\",\"serial\":\"\",\"model\":\"\",\"brand\":\"\"}"
});
return {requestHeaders: details.requestHeaders};
},
{
urls: [
"https://fapi.molotov.tv/v2/auth/login",
"https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
},
["blocking", "requestHeaders"]
); | Add "X-Molotov-Agent" header on authentication token refresh requests. | Add "X-Molotov-Agent" header on authentication token refresh requests.
| JavaScript | bsd-2-clause | jleroy/MoloChrome,jleroy/MoloChrome | ---
+++
@@ -9,7 +9,8 @@
},
{
urls: [
- "https://fapi.molotov.tv/v2/auth/login"
+ "https://fapi.molotov.tv/v2/auth/login",
+ "https://fapi.molotov.tv/v2/auth/refresh/*"
],
types: ["xmlhttprequest"]
}, |
11cbb36d19865113636b291e207e5dd587bbd1e2 | deserializers/resource.js | deserializers/resource.js | 'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
| 'use strict';
var _ = require('lodash');
var P = require('bluebird');
var humps = require('humps');
var Schemas = require('../generators/schemas');
function ResourceDeserializer(model, params) {
var schema = Schemas.schemas[model.collection.name];
function extractAttributes() {
return new P(function (resolve) {
var attributes = params.data.attributes;
attributes._id = params.data.id;
resolve(attributes);
});
}
function extractRelationships() {
return new P(function (resolve) {
var relationships = {};
_.each(schema.fields, function (field) {
if (field.reference && params.data.relationships &&
params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null;
} else if (params.data.relationships[field.field].data) {
// Set the relationship
relationships[field.field] = params.data.relationships[field.field]
.data.id;
} // Else ignore the relationship
}
});
resolve(relationships);
});
}
this.perform = function () {
return P.all([extractAttributes(), extractRelationships()])
.spread(function (attributes, relationships) {
return humps.camelizeKeys(_.extend(attributes, relationships));
});
};
}
module.exports = ResourceDeserializer;
| Fix the deserializer when no relationships is present. | Fix the deserializer when no relationships is present.
| JavaScript | mit | SeyZ/forest-express-mongoose | ---
+++
@@ -20,7 +20,8 @@
var relationships = {};
_.each(schema.fields, function (field) {
- if (field.reference && params.data.relationships[field.field]) {
+ if (field.reference && params.data.relationships &&
+ params.data.relationships[field.field]) {
if (params.data.relationships[field.field].data === null) {
// Remove the relationships
relationships[field.field] = null; |
ba44e3a48b9e383c9d8ad573f920d8f3a665e483 | src/components/home/HomePage.js | src/components/home/HomePage.js | import React from 'react';
import GithubAPI from '../../api/githubAPI';
class HomePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showResult: "l"
};
this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this);
}
invokeGitHubAPI(){
GithubAPI.testOctokat().then(testResult => {
let parsedTestResult = testResult.pushedAt.toTimeString();
console.log(testResult);
console.log(parsedTestResult);
this.setState({showResult: parsedTestResult});
}).catch(error => {
throw(error);
});
}
render() {
return (
<div>
<h1>GitHub Status API GUI</h1>
<h3>Open browser console to see JSON data returned from GitHub API</h3>
<div className="row">
<div className="col-sm-3">
<button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<span>{this.state.showResult}</span>
</div>
</div>
</div>
);
}
}
export default HomePage;
| import React from 'react';
import GithubAPI from '../../api/githubAPI';
class HomePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
showResult: "NO DATA - Click button above to fetch data."
};
this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this);
}
invokeGitHubAPI(){
GithubAPI.testOctokat().then(testResult => {
let parsedTestResult = testResult.pushedAt.toTimeString();
console.log(testResult);
console.log(parsedTestResult);
this.setState({showResult: parsedTestResult});
}).catch(error => {
throw(error);
});
}
render() {
return (
<div>
<h1>GitHub Status API GUI</h1>
<h3>Open browser console to see JSON data returned from GitHub API</h3>
<div className="row">
<div className="col-sm-3">
<button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button>
</div>
</div>
<div className="row">
<div className="col-sm-6">
<span>{this.state.showResult}</span>
</div>
</div>
</div>
);
}
}
export default HomePage;
| Change initial default showResult value to 'NO DATA' message | Change initial default showResult value to 'NO DATA' message
| JavaScript | mit | compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI | ---
+++
@@ -6,7 +6,7 @@
super(props, context);
this.state = {
- showResult: "l"
+ showResult: "NO DATA - Click button above to fetch data."
};
this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); |
9f32a721ee065f0a031e766c58a71b74976140f7 | e2e/ComplexLayout.test.js | e2e/ComplexLayout.test.js | const Utils = require('./Utils');
const testIDs = require('../playground/src/testIDs');
const { elementByLabel, elementById } = Utils;
describe('complex layout', () => {
beforeEach(async () => {
await device.relaunchApp();
});
test(':ios: shows external component in stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_STACK).tap();
await expect(elementByLabel('External component in stack')).toBeVisible();
});
test(':ios: shows external component in deep stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_DEEP_STACK).tap();
await expect(elementByLabel('External component in deep stack')).toBeVisible();
});
});
| const Utils = require('./Utils');
const testIDs = require('../playground/src/testIDs');
const { elementByLabel, elementById } = Utils;
describe('complex layout', () => {
beforeEach(async () => {
await device.relaunchApp();
});
test('shows external component in stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_STACK).tap();
await expect(elementByLabel('External component in stack')).toBeVisible();
});
test('shows external component in deep stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_DEEP_STACK).tap();
await expect(elementByLabel('External component in deep stack')).toBeVisible();
});
});
| Enable external component e2e on Android | Enable external component e2e on Android
| JavaScript | mit | ceyhuno/react-native-navigation,wix/react-native-navigation,thanhzusu/react-native-navigation,Jpoliachik/react-native-navigation,3sidedcube/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,chicojasl/react-native-navigation,guyca/react-native-navigation,chicojasl/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation,guyca/react-native-navigation,Jpoliachik/react-native-navigation,3sidedcube/react-native-navigation,thanhzusu/react-native-navigation,ceyhuno/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,thanhzusu/react-native-navigation,chicojasl/react-native-navigation,ceyhuno/react-native-navigation,ceyhuno/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,thanhzusu/react-native-navigation,thanhzusu/react-native-navigation,3sidedcube/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,Jpoliachik/react-native-navigation,Jpoliachik/react-native-navigation,wix/react-native-navigation,wix/react-native-navigation,guyca/react-native-navigation,wix/react-native-navigation,chicojasl/react-native-navigation,Jpoliachik/react-native-navigation | ---
+++
@@ -8,13 +8,13 @@
await device.relaunchApp();
});
- test(':ios: shows external component in stack in modal', async () => {
+ test('shows external component in stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_STACK).tap();
await expect(elementByLabel('External component in stack')).toBeVisible();
});
- test(':ios: shows external component in deep stack in modal', async () => {
+ test('shows external component in deep stack in modal', async () => {
await elementById(testIDs.COMPLEX_LAYOUT_BUTTON).tap();
await elementById(testIDs.EXTERNAL_COMPONENT_IN_DEEP_STACK).tap();
await expect(elementByLabel('External component in deep stack')).toBeVisible(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.