commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
f2f346573d1383e6d0e645b21514bb16102ecc84
update webpack to read version from package
webpack.config.js
webpack.config.js
const path = require ('path'); const {BannerPlugin} = require ('webpack'); const UglifyJSPlugin = require ('uglifyjs-webpack-plugin'); const lib = require ('./package.json'); const LIBRARY_NAME = lib.name; const LIBRARY_VERSION = lib.version; const LIBRARY_DESCRIPTION = lib.description; const LIBRARY_BANNER = `React xStore JavaScript Library v${LIBRARY_VERSION} ${LIBRARY_DESCRIPTION} https://github.com/tamerzorba/react-xstore Copyright ©2017 Tamer Zorba and other contributors Released under the MIT license https://opensource.org/licenses/MIT`; const PATHS = { app: path.join (__dirname, 'src'), build: path.join (__dirname, 'dist'), }; module.exports = { entry: PATHS.app, output: { path: PATHS.build, filename: 'bundle.js', library: LIBRARY_NAME, libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [new BannerPlugin (LIBRARY_BANNER), new UglifyJSPlugin ()], externals: { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react', }, }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['react', 'es2015'], }, }, ], }, };
const path = require ('path'); const {BannerPlugin} = require ('webpack'); const UglifyJSPlugin = require ('uglifyjs-webpack-plugin'); const LIBRARY_NAME = 'react-xstore'; const LIBRARY_VERSION = '2.0.0'; const LIBRARY_BANNER = `React xStore JavaScript Library v${LIBRARY_VERSION} https://github.com/tamerzorba/react-xstore Copyright ©2017 Tamer Zorba and other contributors Released under the MIT license https://opensource.org/licenses/MIT`; const PATHS = { app: path.join (__dirname, 'src'), build: path.join (__dirname, 'dist'), }; module.exports = { entry: PATHS.app, output: { path: PATHS.build, filename: 'bundle.js', library: LIBRARY_NAME, libraryTarget: 'umd', umdNamedDefine: true, }, plugins: [new BannerPlugin (LIBRARY_BANNER), new UglifyJSPlugin ()], externals: { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react', }, }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['react', 'es2015'], }, }, ], }, };
JavaScript
0
7f32c19d4fdfe210058061d82b7dc2d41ba8856c
Revert "Remove hidden attribute to get around the "!important" flag"
src/js/edu-benefits/education-wizard.js
src/js/edu-benefits/education-wizard.js
function toggleClass(element, className) { element.classList.toggle(className); } function openState(element) { element.setAttribute('hidden', false); element.setAttribute('data-state', 'open'); } function closeState(element) { element.setAttribute('hidden', true); element.setAttribute('data-state', 'closed'); const selectionElement = element.querySelector('input:checked'); if (selectionElement) { selectionElement.checked = false; } } function closeStateAndCheckChild(alternateQuestion, container) { const selectionElement = alternateQuestion.querySelector('input:checked'); if (!selectionElement) { return closeState(alternateQuestion); } const descendentQuestion = selectionElement.dataset.nextQuestion; if (!descendentQuestion) { return closeState(alternateQuestion); } const descendentElement = container.querySelector(`[data-question=${descendentQuestion}]`); closeStateAndCheckChild(descendentElement, container); return closeState(alternateQuestion); } function reInitWidget() { const container = document.querySelector('.wizard-anchor .wizard-container'); const button = container.querySelector('.wizard-button'); const content = container.querySelector('.wizard-content'); const applyLink = container.querySelector('#apply-now-link'); const applyButton = container.querySelector('#apply-now-button'); const transferWarning = container.querySelector('#transfer-warning'); const nctsWarning = container.querySelector('#ncts-warning'); function resetForm() { const selections = Array.from(container.querySelectorAll('input:checked')); // eslint-disable-next-line no-return-assign, no-param-reassign selections.forEach(selection => selection.checked = false); } applyLink.addEventListener('click', resetForm); content.addEventListener('change', (e) => { const radio = e.target; const otherChoices = radio.dataset.alternate.split(' '); otherChoices.forEach((otherChoice) => { const otherNextQuestion = container.querySelector(`#${otherChoice}`).dataset.nextQuestion; if (otherNextQuestion) { const otherNextQuestionElement = container.querySelector(`[data-question=${otherNextQuestion}]`); closeStateAndCheckChild(otherNextQuestionElement, container); } }); if ((applyButton.dataset.state === 'open') && !radio.dataset.selectedForm) { closeState(applyButton); } if ((transferWarning.dataset.state === 'open') && (radio.id !== 'create-non-transfer')) { closeState(transferWarning); } if ((nctsWarning.dataset.state === 'open') && (radio.id !== 'is-ncts')) { closeState(nctsWarning); } if (radio.dataset.selectedForm) { if (applyButton.dataset.state === 'closed') { openState(applyButton); } if ((transferWarning.dataset.state === 'closed') && (radio.id === 'create-non-transfer')) { openState(transferWarning); } if ((nctsWarning.dataset.state === 'closed') && (radio.id === 'is-ncts')) { openState(nctsWarning); } applyLink.href = `/education/apply-for-education-benefits/application/${radio.dataset.selectedForm}/introduction`; } if (radio.dataset.nextQuestion) { const nextQuestion = radio.dataset.nextQuestion; const nextQuestionElement = container.querySelector(`[data-question=${nextQuestion}]`); openState(nextQuestionElement); } }); button.addEventListener('click', () => { toggleClass(content, 'wizard-content-closed'); toggleClass(button, 'va-button-primary'); }); // Ensure form is reset on page load to prevent unexpected behavior associated with backtracking resetForm(); } function loadImports() { const importContent = document.getElementById('wizard-template').innerHTML; const anchor = document.querySelector('.wizard-anchor'); anchor.innerHTML = importContent; } window.addEventListener('DOMContentLoaded', () => { loadImports(); reInitWidget(); });
function toggleClass(element, className) { element.classList.toggle(className); } function openState(element) { element.removeAttribute('hidden'); element.setAttribute('data-state', 'open'); } function closeState(element) { element.setAttribute('hidden', true); element.setAttribute('data-state', 'closed'); const selectionElement = element.querySelector('input:checked'); if (selectionElement) { selectionElement.checked = false; } } function closeStateAndCheckChild(alternateQuestion, container) { const selectionElement = alternateQuestion.querySelector('input:checked'); if (!selectionElement) { return closeState(alternateQuestion); } const descendentQuestion = selectionElement.dataset.nextQuestion; if (!descendentQuestion) { return closeState(alternateQuestion); } const descendentElement = container.querySelector(`[data-question=${descendentQuestion}]`); closeStateAndCheckChild(descendentElement, container); return closeState(alternateQuestion); } function reInitWidget() { const container = document.querySelector('.wizard-anchor .wizard-container'); const button = container.querySelector('.wizard-button'); const content = container.querySelector('.wizard-content'); const applyLink = container.querySelector('#apply-now-link'); const applyButton = container.querySelector('#apply-now-button'); const transferWarning = container.querySelector('#transfer-warning'); const nctsWarning = container.querySelector('#ncts-warning'); function resetForm() { const selections = Array.from(container.querySelectorAll('input:checked')); // eslint-disable-next-line no-return-assign, no-param-reassign selections.forEach(selection => selection.checked = false); } applyLink.addEventListener('click', resetForm); content.addEventListener('change', (e) => { const radio = e.target; const otherChoices = radio.dataset.alternate.split(' '); otherChoices.forEach((otherChoice) => { const otherNextQuestion = container.querySelector(`#${otherChoice}`).dataset.nextQuestion; if (otherNextQuestion) { const otherNextQuestionElement = container.querySelector(`[data-question=${otherNextQuestion}]`); closeStateAndCheckChild(otherNextQuestionElement, container); } }); if ((applyButton.dataset.state === 'open') && !radio.dataset.selectedForm) { closeState(applyButton); } if ((transferWarning.dataset.state === 'open') && (radio.id !== 'create-non-transfer')) { closeState(transferWarning); } if ((nctsWarning.dataset.state === 'open') && (radio.id !== 'is-ncts')) { closeState(nctsWarning); } if (radio.dataset.selectedForm) { if (applyButton.dataset.state === 'closed') { openState(applyButton); } if ((transferWarning.dataset.state === 'closed') && (radio.id === 'create-non-transfer')) { openState(transferWarning); } if ((nctsWarning.dataset.state === 'closed') && (radio.id === 'is-ncts')) { openState(nctsWarning); } applyLink.href = `/education/apply-for-education-benefits/application/${radio.dataset.selectedForm}/introduction`; } if (radio.dataset.nextQuestion) { const nextQuestion = radio.dataset.nextQuestion; const nextQuestionElement = container.querySelector(`[data-question=${nextQuestion}]`); openState(nextQuestionElement); } }); button.addEventListener('click', () => { toggleClass(content, 'wizard-content-closed'); toggleClass(button, 'va-button-primary'); }); // Ensure form is reset on page load to prevent unexpected behavior associated with backtracking resetForm(); } function loadImports() { const importContent = document.getElementById('wizard-template').innerHTML; const anchor = document.querySelector('.wizard-anchor'); anchor.innerHTML = importContent; } window.addEventListener('DOMContentLoaded', () => { loadImports(); reInitWidget(); });
JavaScript
0
a871b476b2911c352f86efade81a74a8eab0dc65
add suppress
webpack.config.js
webpack.config.js
//noinspection NodeJsCodingAssistanceForCoreModules const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require("copy-webpack-plugin"); module.exports = { entry: { home: './src/js/home.js', privacy: './src/js/privacy.js' }, output: { path: path.join(__dirname, 'public'), filename: 'js/[name].js' }, devServer: { contentBase: path.resolve(__dirname, 'public') }, module: { loaders: [ { loader: 'babel-loader', exclude: /node_modules/, test: /\.js[x]?$/, query: { cacheDirectory: true, presets: ['es2015'] } }, {test: /\.pug$/, loader: 'pug-loader'}, {test: /\.css$/, loader: 'style-loader!css-loader'}, {test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader']}, {test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml'}, {test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.ttf$/, loader: 'url-loader?mimetype=application/font-woff'} ] }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), new CopyWebpackPlugin( [ {from: "src/img/", to: "img/"}, {from: "src/json/", to: "json/"} ] ), new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: 'head', chunks: ['home'] }), new HtmlWebpackPlugin({ filename: 'privacy.html', template: 'src/privacy.pug', inject: 'head', chunks: ['home', 'privacy'] }) ] };
const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = require('path'); module.exports = { entry: { home: './src/js/home.js', privacy: './src/js/privacy.js' }, output: { path: path.join(__dirname, 'public'), filename: 'js/[name].js' }, devServer: { contentBase: path.resolve(__dirname, 'public') }, module: { loaders: [ { loader: 'babel-loader', exclude: /node_modules/, test: /\.js[x]?$/, query: { cacheDirectory: true, presets: ['es2015'] } }, {test: /\.pug$/, loader: 'pug-loader'}, {test: /\.css$/, loader: 'style-loader!css-loader'}, {test: /\.scss$/, loaders: ['style-loader', 'css-loader', 'sass-loader']}, {test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml'}, {test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff'}, {test: /\.ttf$/, loader: 'url-loader?mimetype=application/font-woff'} ] }, plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }), new CopyWebpackPlugin( [ {from: "src/img/", to: "img/"}, {from: "src/json/", to: "json/"} ] ), new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: 'head', chunks: ['home'] }), new HtmlWebpackPlugin({ filename: 'privacy.html', template: 'src/privacy.pug', inject: 'head', chunks: ['home', 'privacy'] }) ] };
JavaScript
0.000095
d9c28d12d3cfe1e403d9be47dc574c0fe771670e
Copy extension assets from VM
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); // Plugins var CopyWebpackPlugin = require('copy-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); // PostCss var autoprefixer = require('autoprefixer'); var postcssVars = require('postcss-simple-vars'); var postcssImport = require('postcss-import'); module.exports = { devServer: { contentBase: path.resolve(__dirname, 'build'), host: '0.0.0.0', port: process.env.PORT || 8601 }, devtool: 'cheap-module-source-map', entry: { lib: ['react', 'react-dom'], gui: './src/index.jsx', blocksonly: './src/examples/blocks-only.jsx', compatibilitytesting: './src/examples/compatibility-testing.jsx', player: './src/examples/player.jsx' }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js' }, externals: { React: 'react', ReactDOM: 'react-dom' }, module: { rules: [{ test: /\.jsx?$/, loader: 'babel-loader', include: path.resolve(__dirname, 'src') }, { test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: '[name]_[local]_[hash:base64:5]', camelCase: true } }, { loader: 'postcss-loader', options: { ident: 'postcss', plugins: function () { return [ postcssImport, postcssVars, autoprefixer({ browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8'] }) ]; } } }] }, { test: /\.(svg|png|wav)$/, loader: 'file-loader' }] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"' + process.env.NODE_ENV + '"', 'process.env.DEBUG': Boolean(process.env.DEBUG) }), new webpack.optimize.CommonsChunkPlugin({ name: 'lib', filename: 'lib.min.js' }), new HtmlWebpackPlugin({ chunks: ['lib', 'gui'], template: 'src/index.ejs', title: 'Scratch 3.0 GUI' }), new HtmlWebpackPlugin({ chunks: ['lib', 'blocksonly'], template: 'src/index.ejs', filename: 'blocks-only.html', title: 'Scratch 3.0 GUI: Blocks Only Example' }), new HtmlWebpackPlugin({ chunks: ['lib', 'compatibilitytesting'], template: 'src/index.ejs', filename: 'compatibility-testing.html', title: 'Scratch 3.0 GUI: Compatibility Testing' }), new HtmlWebpackPlugin({ chunks: ['lib', 'player'], template: 'src/index.ejs', filename: 'player.html', title: 'Scratch 3.0 GUI: Player Example' }), new CopyWebpackPlugin([{ from: 'node_modules/scratch-blocks/media', to: 'static/blocks-media' }]), new CopyWebpackPlugin([{ from: 'node_modules/scratch-vm/dist/node/assets', to: 'static/extension-assets' }]), new CopyWebpackPlugin([{ from: 'extensions/**', to: 'static', context: 'src/examples' }]), new CopyWebpackPlugin([{ from: 'extension-worker.{js,js.map}', context: 'node_modules/scratch-vm/dist/web' }]) ].concat(process.env.NODE_ENV === 'production' ? [ new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ] : []) };
var path = require('path'); var webpack = require('webpack'); // Plugins var CopyWebpackPlugin = require('copy-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); // PostCss var autoprefixer = require('autoprefixer'); var postcssVars = require('postcss-simple-vars'); var postcssImport = require('postcss-import'); module.exports = { devServer: { contentBase: path.resolve(__dirname, 'build'), host: '0.0.0.0', port: process.env.PORT || 8601 }, devtool: 'cheap-module-source-map', entry: { lib: ['react', 'react-dom'], gui: './src/index.jsx', blocksonly: './src/examples/blocks-only.jsx', compatibilitytesting: './src/examples/compatibility-testing.jsx', player: './src/examples/player.jsx' }, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js' }, externals: { React: 'react', ReactDOM: 'react-dom' }, module: { rules: [{ test: /\.jsx?$/, loader: 'babel-loader', include: path.resolve(__dirname, 'src') }, { test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', options: { modules: true, importLoaders: 1, localIdentName: '[name]_[local]_[hash:base64:5]', camelCase: true } }, { loader: 'postcss-loader', options: { ident: 'postcss', plugins: function () { return [ postcssImport, postcssVars, autoprefixer({ browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8'] }) ]; } } }] }, { test: /\.(svg|png|wav)$/, loader: 'file-loader' }] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"' + process.env.NODE_ENV + '"', 'process.env.DEBUG': Boolean(process.env.DEBUG) }), new webpack.optimize.CommonsChunkPlugin({ name: 'lib', filename: 'lib.min.js' }), new HtmlWebpackPlugin({ chunks: ['lib', 'gui'], template: 'src/index.ejs', title: 'Scratch 3.0 GUI' }), new HtmlWebpackPlugin({ chunks: ['lib', 'blocksonly'], template: 'src/index.ejs', filename: 'blocks-only.html', title: 'Scratch 3.0 GUI: Blocks Only Example' }), new HtmlWebpackPlugin({ chunks: ['lib', 'compatibilitytesting'], template: 'src/index.ejs', filename: 'compatibility-testing.html', title: 'Scratch 3.0 GUI: Compatibility Testing' }), new HtmlWebpackPlugin({ chunks: ['lib', 'player'], template: 'src/index.ejs', filename: 'player.html', title: 'Scratch 3.0 GUI: Player Example' }), new CopyWebpackPlugin([{ from: 'node_modules/scratch-blocks/media', to: 'static/blocks-media' }]), new CopyWebpackPlugin([{ from: 'extensions/**', to: 'static', context: 'src/examples' }]), new CopyWebpackPlugin([{ from: 'extension-worker.{js,js.map}', context: 'node_modules/scratch-vm/dist/web' }]) ].concat(process.env.NODE_ENV === 'production' ? [ new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ] : []) };
JavaScript
0
2d6798ed15488edeb0487e77977d24249eb74072
Fix externalRequest
webpack.config.js
webpack.config.js
const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } module.exports = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `var (${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } }) ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } };
const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } module.exports = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `(${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } }) ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } };
JavaScript
0.000003
e3226236a23a74ec4f0d46d49fcf8c57b602dea7
Add revoke action
chrome-extension/options.js
chrome-extension/options.js
document.addEventListener("DOMContentLoaded", () => { const defaultUri = "http://localhost:3000/api/v1" const $ = document.querySelector.bind(document) // Service URL setting chrome.storage.sync.get("service_uri", ({service_uri}) => { if (service_uri === undefined) { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri }) } else { $("input[name=uri]").value = service_uri } }) $("button[name=reset]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("button[name=update]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: $("input[name=uri]").value}, () => { $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("input[name=uri]").addEventListener("input", (eve) => { $("button[name=update]").disabled = false $("button[name=token]").disabled = true }, false) // Token setting chrome.storage.sync.get("token", ({token}) => { if (token === undefined) { if (location.search) { const queries = location.search.replace(/^\?/, "").split("&") for (const query of queries) { if (query.search(/^token=/) === 0) { const token = query.split("=")[1] if (!token) { continue } chrome.storage.sync.set({token: token}, () => { $("input[name=token]").value = token }) return } } } $("button[name=token]").innerText = "Get Token" } else { $("input[name=token]").value = token } }) $("button[name=token]").addEventListener("click", (eve) => { switch (eve.target.innerText) { case "Revoke Token": chrome.storage.sync.get(["service_uri", "token"], ({service_uri, token}) => { fetch(`${service_uri}/auth/token/${token}`, { method: "DELETE" }) .then(() => chrome.storage.sync.remove("token", () => { $("input[name=token]").value = "" eve.target.innerText = "Get Token" })) .catch((e) => { alert(`Failed to send revoke request.`) }) }) break case "Get Token": const callbackUrl = chrome.extension.getURL("options.html") chrome.storage.sync.get("service_uri", ({service_uri}) => { chrome.tabs.getCurrent(cur => { chrome.tabs.update(cur.id, {url: `${service_uri}/auth?callback=${callbackUrl}`}) }) }) break default: throw new Error() } }, false) }, false)
document.addEventListener("DOMContentLoaded", () => { const defaultUri = "http://localhost:3000/api/v1" const $ = document.querySelector.bind(document) // Service URL setting chrome.storage.sync.get("service_uri", ({service_uri}) => { if (service_uri === undefined) { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri }) } else { $("input[name=uri]").value = service_uri } }) $("button[name=reset]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: defaultUri}, () => { $("input[name=uri]").value = defaultUri $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("button[name=update]").addEventListener("click", (eve) => { chrome.storage.sync.set({service_uri: $("input[name=uri]").value}, () => { $("button[name=update]").disabled = true $("button[name=token]").disabled = false }) }, false) $("input[name=uri]").addEventListener("input", (eve) => { $("button[name=update]").disabled = false $("button[name=token]").disabled = true }, false) // Token setting chrome.storage.sync.get("token", ({token}) => { if (token === undefined) { if (location.search) { const queries = location.search.replace(/^\?/, "").split("&") for (const query of queries) { if (query.search(/^token=/) === 0) { const token = query.split("=")[1] if (!token) { continue } chrome.storage.sync.set({token: token}, () => { $("input[name=token]").value = token }) return } } } $("button[name=token]").innerText = "Get Token" } else { $("input[name=token]").value = token } }) $("button[name=token]").addEventListener("click", (eve) => { switch (eve.target.innerText) { case "Revoke Token": chrome.storage.sync.remove("token", () => { $("input[name=token]").value = "" eve.target.innerText = "Get Token" }) break case "Get Token": const callbackUrl = chrome.extension.getURL("options.html") chrome.storage.sync.get("service_uri", ({service_uri}) => { chrome.tabs.getCurrent(cur => { chrome.tabs.update(cur.id, {url: `${service_uri}/auth?callback=${callbackUrl}`}) }) }) break default: throw new Error() } }, false) }, false)
JavaScript
0.000004
660cfaeeea175d1f829ca1d6eb0dab26f492fc81
Fix JSON webpack loader
webpack.config.js
webpack.config.js
'use strict'; const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } const webpackConfig = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `var (${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json-loader' } ] }, plugins: [ ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } }; if (process.env.DEBUG !== 'true') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } })); } module.exports = webpackConfig;
'use strict'; const webpack = require('webpack'); function criWrapper(_, options, callback) { window.criRequest(options, callback); } const webpackConfig = { resolve: { alias: { 'ws': './websocket-wrapper.js' } }, externals: [ { './external-request.js': `var (${criWrapper})` } ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.json$/, loader: 'json' } ] }, plugins: [ ], entry: './index.js', output: { libraryTarget: process.env.TARGET || 'commonjs2', library: 'CDP', filename: 'chrome-remote-interface.js' } }; if (process.env.DEBUG !== 'true') { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false }, output: { comments: false } })); } module.exports = webpackConfig;
JavaScript
0.000504
51d06c57bf37389859033e6641a6b6078402dffe
Add an alias for fonts in webpack config
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] } ] }, resolve: { alias: { fonts: path.resolve(__dirname, 'web/fonts') } } };
const path = require('path'); module.exports = { entry: { app: path.resolve(__dirname, 'app/Resources/assets/js/app.js') }, output: { path: path.resolve(__dirname, 'web/builds'), filename: 'bundle.js', publicPath: '/builds/' }, module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: 'babel-loader' }, { test: /\.scss$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" } ] } ] } };
JavaScript
0.000001
c4b4a4a3c9d84454d77cb096a24ca793fff30f4d
remove obsolete DedupePlugin
webpack.config.js
webpack.config.js
const path = require('path'); const DefinePlugin = require('webpack').DefinePlugin; const ProgressPlugin = require('webpack').ProgressPlugin; const HtmlPlugin = require('html-webpack-plugin'); const nodeEnv = process.env.NODE_ENV || 'development'; // Minification options used in production mode. const htmlMinifierOptions = { removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeTagWhitespace: true, removeAttributeQuotes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeOptionalTags: true }; const plugins = [ new DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(nodeEnv) } }), new HtmlPlugin({ chunks: [ 'app' ], inject: false, template: './index.html', minify: nodeEnv === 'production' ? htmlMinifierOptions : false, loadingScreen: () => require('./tasks/utils/renderLoadingScreen')() }), new ProgressPlugin() ]; if (nodeEnv === 'production') { const LoaderOptionsPlugin = require('webpack').LoaderOptionsPlugin; const OccurrenceOrderPlugin = require('webpack').optimize.OccurrenceOrderPlugin; const UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin; plugins.push( new OccurrenceOrderPlugin(), new LoaderOptionsPlugin({ minimize: true, debug: false }), new UglifyJsPlugin({ // Yeah… Enables some riskier minification that doesn't work in IE8. // But üWave doesn't work in IE8 _anyway_, so we don't care. compress: { screw_ie8: true, pure_getters: true, unsafe: true }, output: { screw_ie8: true }, // Rename top-level (global scope) variables to shorter names too. // There's no other code that depends on those variables to be // available, so it doesn't really matter what they're called! mangle: { toplevel: true } }) ); } module.exports = { context: path.join(__dirname, 'src'), entry: { app: './app.js' }, output: { publicPath: '/', path: path.join(__dirname, 'public'), filename: '[name].js' }, plugins, module: { rules: [ { test: /\.yaml$/, use: [ 'json-loader', 'yaml-loader' ] }, { test: /\.json$/, use: [ 'json-loader' ] }, { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader' ] } ] } };
const path = require('path'); const DefinePlugin = require('webpack').DefinePlugin; const ProgressPlugin = require('webpack').ProgressPlugin; const HtmlPlugin = require('html-webpack-plugin'); const nodeEnv = process.env.NODE_ENV || 'development'; // Minification options used in production mode. const htmlMinifierOptions = { removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeTagWhitespace: true, removeAttributeQuotes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, removeOptionalTags: true }; const plugins = [ new DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(nodeEnv) } }), new HtmlPlugin({ chunks: [ 'app' ], inject: false, template: './index.html', minify: nodeEnv === 'production' ? htmlMinifierOptions : false, loadingScreen: () => require('./tasks/utils/renderLoadingScreen')() }), new ProgressPlugin() ]; if (nodeEnv === 'production') { const LoaderOptionsPlugin = require('webpack').LoaderOptionsPlugin; const DedupePlugin = require('webpack').optimize.DedupePlugin; const OccurrenceOrderPlugin = require('webpack').optimize.OccurrenceOrderPlugin; const UglifyJsPlugin = require('webpack').optimize.UglifyJsPlugin; plugins.push( new OccurrenceOrderPlugin(), new DedupePlugin(), new LoaderOptionsPlugin({ minimize: true, debug: false }), new UglifyJsPlugin({ // Yeah… Enables some riskier minification that doesn't work in IE8. // But üWave doesn't work in IE8 _anyway_, so we don't care. compress: { screw_ie8: true, pure_getters: true, unsafe: true }, output: { screw_ie8: true }, // Rename top-level (global scope) variables to shorter names too. // There's no other code that depends on those variables to be // available, so it doesn't really matter what they're called! mangle: { toplevel: true } }) ); } module.exports = { context: path.join(__dirname, 'src'), entry: { app: './app.js' }, output: { publicPath: '/', path: path.join(__dirname, 'public'), filename: '[name].js' }, plugins, module: { rules: [ { test: /\.yaml$/, use: [ 'json-loader', 'yaml-loader' ] }, { test: /\.json$/, use: [ 'json-loader' ] }, { test: /\.js$/, exclude: /node_modules/, use: [ 'babel-loader' ] } ] } };
JavaScript
0.000012
e965f41adc81cf97415448642cdcda6bbe08690f
fix staging build
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ProgressBarPlugin = require('progress-bar-webpack-plugin'); const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin'); const RobotstxtPlugin = require('robotstxt-webpack-plugin').default; const PORT = process.env.PORT || 3000; const HOST = process.env.HOST || 'localhost'; const NODE_ENV = process.env.NODE_ENV || 'production'; const isProduction = (NODE_ENV === 'production' || NODE_ENV === 'staging'); const isDevelopment = (NODE_ENV === 'development'); const config = { entry: isDevelopment ? [ 'babel-polyfill', 'react-hot-loader/patch', // activate HMR for React `webpack-hot-middleware/client?path=http://${HOST}:${PORT}/__webpack_hmr`, // bundle the client for webpack-hot-middleware and connect to the provided endpoint './src/client.jsx', ] : [ 'babel-polyfill', './src/client.jsx', ], resolve: { extensions: ['.js', '.jsx', '.json'], }, output: { path: path.join(__dirname, 'dist/public/'), filename: isDevelopment ? 'main.js' : 'assets/scripts/[name].[chunkhash].js', }, module: { rules: [ { test: /\.css$/, use: ['css-hot-loader'].concat( ExtractTextPlugin.extract({ fallback: 'style-loader', use: [{ loader: 'css-loader', options: {minimize: true}, }], }), ), }, { test: /\.jsx?$/, use: ['babel-loader'], include: path.join(__dirname, 'src'), }, ], }, plugins: [ new ProgressBarPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), }), isDevelopment ? new webpack.HotModuleReplacementPlugin() // enable HMR globally : null, isDevelopment ? new webpack.NamedModulesPlugin() // prints more readable module names in the browser console on HMR updates : null, isDevelopment ? new webpack.NoEmitOnErrorsPlugin() // do not emit compiled assets that include errors : null, new ExtractTextPlugin({ filename: isDevelopment ? 'assets/styles/main.css' : 'assets/styles/[name].[chunkhash].css', }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: module => /node_modules/.test(module.resource), }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({name: 'manifest'}), isDevelopment ? null : new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src/index.html'), minify: isProduction ? {collapseWhitespace: true, collapseInlineTagWhitespace: true} : false, alwaysWriteToDisk: true, }), new HtmlWebpackHarddiskPlugin(), new CopyWebpackPlugin([ { context: 'src/assets/media', from: '**/*', to: 'assets/media', }, ]), new RobotstxtPlugin({ policy: [ isProduction ? {userAgent: '*', allow: '/'} : {userAgent: '*', disallow: '/'}, ], }), ].filter(Boolean), devtool: isProduction ? 'none' : 'cheap-module-eval-source-map', performance: { maxAssetSize: 500000, }, }; module.exports = config;
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ProgressBarPlugin = require('progress-bar-webpack-plugin'); const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin'); const RobotstxtPlugin = require('robotstxt-webpack-plugin').default; const PORT = process.env.PORT || 3000; const HOST = process.env.HOST || 'localhost'; const NODE_ENV = process.env.NODE_ENV || 'production'; const isProduction = (NODE_ENV === 'production'); const isDevelopment = (NODE_ENV === 'development'); const config = { entry: isDevelopment ? [ 'babel-polyfill', 'react-hot-loader/patch', // activate HMR for React `webpack-hot-middleware/client?path=http://${HOST}:${PORT}/__webpack_hmr`, // bundle the client for webpack-hot-middleware and connect to the provided endpoint './src/client.jsx', ] : [ 'babel-polyfill', './src/client.jsx', ], resolve: { extensions: ['.js', '.jsx', '.json'], }, output: { path: path.join(__dirname, 'dist/public/'), filename: isDevelopment ? 'main.js' : 'assets/scripts/[name].[chunkhash].js', }, module: { rules: [ { test: /\.css$/, use: ['css-hot-loader'].concat( ExtractTextPlugin.extract({ fallback: 'style-loader', use: [{ loader: 'css-loader', options: {minimize: true}, }], }), ), }, { test: /\.jsx?$/, use: ['babel-loader'], include: path.join(__dirname, 'src'), }, ], }, plugins: [ new ProgressBarPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV), }), isDevelopment ? new webpack.HotModuleReplacementPlugin() // enable HMR globally : null, isDevelopment ? new webpack.NamedModulesPlugin() // prints more readable module names in the browser console on HMR updates : null, isDevelopment ? new webpack.NoEmitOnErrorsPlugin() // do not emit compiled assets that include errors : null, new ExtractTextPlugin({ filename: isDevelopment ? 'assets/styles/main.css' : 'assets/styles/[name].[chunkhash].css', }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: module => /node_modules/.test(module.resource), }), isDevelopment ? null : new webpack.optimize.CommonsChunkPlugin({name: 'manifest'}), isDevelopment ? null : new webpack.optimize.UglifyJsPlugin(), new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src/index.html'), minify: isProduction ? {collapseWhitespace: true, collapseInlineTagWhitespace: true} : false, alwaysWriteToDisk: true, }), new HtmlWebpackHarddiskPlugin(), new CopyWebpackPlugin([ { context: 'src/assets/media', from: '**/*', to: 'assets/media', }, ]), new RobotstxtPlugin({ policy: [ isProduction ? {userAgent: '*', allow: '/'} : {userAgent: '*', disallow: '/'}, ], }), ].filter(Boolean), devtool: isProduction ? 'none' : 'cheap-module-eval-source-map', performance: { maxAssetSize: 500000, }, }; module.exports = config;
JavaScript
0.000001
8a47ef7fa497ec280b3a47959e8c04d14339c9a3
fix env reading order
webpack.config.js
webpack.config.js
const dotenv = require('dotenv'); const Encore = require('@symfony/webpack-encore'); const StyleLintPlugin = require('stylelint-webpack-plugin'); dotenv.config({ path : __dirname + '/.env' }); dotenv.config({ path : __dirname + '/.env.local' }); // Manually configure the runtime environment if not already configured yet by the "encore" command. // It's useful when you use tools that rely on webpack.config.js file. if (!Encore.isRuntimeEnvironmentConfigured()) { Encore.configureRuntimeEnvironment(process.env.NODE_ENV || process.env.APP_ENV || 'dev'); } Encore // directory where compiled assets will be stored .setOutputPath('public/build/') // public path used by the web server to access the output path .setPublicPath(process.env.ASSETS_ORIGIN + '/build/') // only needed for CDN's or sub-directory deploy .setManifestKeyPrefix('build/') /* * ENTRY CONFIG * * Add 1 entry for each "page" of your app * (including one that's included on every page - e.g. "app") * * Each entry will result in one JavaScript file (e.g. app.js) * and one CSS file (e.g. app.css) if your JavaScript imports CSS. */ .addEntry('athorrent', './assets/js/athorrent.js') .addEntry('files', './assets/js/files.js') .addEntry('media', './assets/js/media.js') .addEntry('search', './assets/js/search.js') .addEntry('sharings', './assets/js/sharings.js') .addEntry('torrents', './assets/js/torrents.js') .addEntry('users', './assets/js/users.js') .addStyleEntry('administration', './assets/css/administration.scss') .addStyleEntry('cache', './assets/css/cache.scss') .addStyleEntry('home', './assets/css/home.scss') .addStyleEntry('main', './assets/css/main.scss') .copyFiles({ from: './assets/images', pattern: /\.(ico|png)$/ }) // When enabled, Webpack "splits" your files into smaller pieces for greater optimization. .splitEntryChunks() // will require an extra script tag for runtime.js // but, you probably want this, unless you're building a single-page app .enableSingleRuntimeChunk() /* * FEATURE CONFIG * * Enable & configure other features below. For a full * list of features, see: * https://symfony.com/doc/current/frontend.html#adding-more-features */ .cleanupOutputBeforeBuild() .enableBuildNotifications() .enableSourceMaps(!Encore.isProduction()) // enables hashed filenames (e.g. app.abc123.css) .enableVersioning(Encore.isProduction()) // enables Sass/SCSS support .enableSassLoader() .enablePostCssLoader() .addPlugin(new StyleLintPlugin({ context: './assets/css' })) // uncomment if you're having problems with a jQuery plugin .autoProvidejQuery() ; module.exports = Encore.getWebpackConfig();
const dotenv = require('dotenv'); const Encore = require('@symfony/webpack-encore'); const StyleLintPlugin = require('stylelint-webpack-plugin'); dotenv.config({ path : __dirname + '/.env.local' }); dotenv.config({ path : __dirname + '/.env' }); // Manually configure the runtime environment if not already configured yet by the "encore" command. // It's useful when you use tools that rely on webpack.config.js file. if (!Encore.isRuntimeEnvironmentConfigured()) { Encore.configureRuntimeEnvironment(process.env.NODE_ENV || process.env.APP_ENV || 'dev'); } Encore // directory where compiled assets will be stored .setOutputPath('public/build/') // public path used by the web server to access the output path .setPublicPath(process.env.ASSETS_ORIGIN + '/build/') // only needed for CDN's or sub-directory deploy .setManifestKeyPrefix('build/') /* * ENTRY CONFIG * * Add 1 entry for each "page" of your app * (including one that's included on every page - e.g. "app") * * Each entry will result in one JavaScript file (e.g. app.js) * and one CSS file (e.g. app.css) if your JavaScript imports CSS. */ .addEntry('athorrent', './assets/js/athorrent.js') .addEntry('files', './assets/js/files.js') .addEntry('media', './assets/js/media.js') .addEntry('search', './assets/js/search.js') .addEntry('sharings', './assets/js/sharings.js') .addEntry('torrents', './assets/js/torrents.js') .addEntry('users', './assets/js/users.js') .addStyleEntry('administration', './assets/css/administration.scss') .addStyleEntry('cache', './assets/css/cache.scss') .addStyleEntry('home', './assets/css/home.scss') .addStyleEntry('main', './assets/css/main.scss') .copyFiles({ from: './assets/images', pattern: /\.(ico|png)$/ }) // When enabled, Webpack "splits" your files into smaller pieces for greater optimization. .splitEntryChunks() // will require an extra script tag for runtime.js // but, you probably want this, unless you're building a single-page app .enableSingleRuntimeChunk() /* * FEATURE CONFIG * * Enable & configure other features below. For a full * list of features, see: * https://symfony.com/doc/current/frontend.html#adding-more-features */ .cleanupOutputBeforeBuild() .enableBuildNotifications() .enableSourceMaps(!Encore.isProduction()) // enables hashed filenames (e.g. app.abc123.css) .enableVersioning(Encore.isProduction()) // enables Sass/SCSS support .enableSassLoader() .enablePostCssLoader() .addPlugin(new StyleLintPlugin({ context: './assets/css' })) // uncomment if you're having problems with a jQuery plugin .autoProvidejQuery() ; module.exports = Encore.getWebpackConfig();
JavaScript
0.000052
9487c72924169984cd84b6105b48303040347365
Change webpack paths
webpack.config.js
webpack.config.js
var path = require("path"); var webpack = require("webpack"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { cache: true, entry: { webvowl: "./src/webvowl/js/entry.js", "webvowl.app": "./src/app/js/entry.js" }, output: { path: path.join(__dirname, "deploy/"), publicPath: "", filename: "js/[name].js", chunkFilename: "js/[chunkhash].js", libraryTarget: "assign", library: "[name]" }, module: { loaders: [ {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")}, {test: /\.json$/, loader: "file?name=data/[name].[ext]?[hash]"} ] }, plugins: [ new ExtractTextPlugin("css/[name].css"), new webpack.ProvidePlugin({ d3: "d3" }) ], externals: { "d3": "d3" } };
var path = require("path"); var webpack = require("webpack"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { cache: true, entry: { webvowl: "./src/webvowl/js/entry.js", "webvowl.app": "./src/app/js/entry.js" }, output: { path: path.join(__dirname, "deploy/js/"), publicPath: "js/", filename: "[name].js", chunkFilename: "[chunkhash].js", libraryTarget: "assign", library: "[name]" }, module: { loaders: [ {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")}, {test: /\.json$/, loader: "file"} ] }, plugins: [ new ExtractTextPlugin("../css/[name].css"), new webpack.ProvidePlugin({ d3: "d3" }) ], externals: { "d3": "d3" } };
JavaScript
0.000001
cf4a73ea1ee53c55e78ed8c3ced18a6817ecc13f
update webpack config
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var devFlagPlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false')) }); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), devFlagPlugin, new ExtractTextPlugin('app.css') ], module: { loaders: [ { test: /\.jsx?$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: ExtractTextPlugin.extract('css-loader?module!cssnext-loader') } ] }, resolve: { extensions: ['', '.js', '.json'] } };
var path = require('path'); var webpack = require('webpack'); var devFlagPlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false')) }); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), devFlagPlugin ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'src') }] } };
JavaScript
0.000001
cee2275e86c77c87a40ffdd022f3991af6cf6a03
remove 's'
web/js/blog.js
web/js/blog.js
$(".reportComment").click(function(event){ event.preventDefault(); }); function closeDiv(){ $(function(){ $("#reportSuccess").css("display", "none"); }) } function fadeInSuccess(){ $(function(){ $("#success").fadeIn(2000); }) } function inputTitleValidation(){ var input = $("#blogbundle_post_name"); var formGroup = $("#titleGroup"); input.on('keyup keypress blur change', function() { var inputLength = input.val().length; if(inputLength < 5){ formGroup.addClass("has-error") formGroup.removeClass("has-success") } else{ formGroup.addClass("has-success") formGroup.removeClass("has-error") } }); } function setReport(id){ var path = Routing.generate('set_report'); var reportData = {"Comment_ID": id}; $.ajax({ type: "POST", data: reportData, url: path, success: function(data){ if(data){ $("#reportSuccess").fadeIn(1000); } }, error: function(xhr, status, error) { console.log(error); } }); } function deleteComment(id, postId){ var path = Routing.generate('admin_comment_delete'); var commentData = {"Comment_ID": id}; $.ajax({ type: "POST", data: commentData, url: path, success: function(data){ if(data){ $("#deleteSuccess").fadeIn(1000); $("." + id).remove(); getCommentNumber(postId); getReportCommentNumber(postId); } }, error: function(xhr, status, error) { console.log(error); } }); } function getCommentNumber(postId){ var path = Routing.generate('admin_get_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".commentNumber").text(data); if(data > 1){ $(".pluralCommentNumber").text('s'); } else{ $(".pluralCommentNumber").remove(); } }, error: function(xhr, status, error) { console.log(error); } }); } function getReportCommentNumber(postId){ var path = Routing.generate('admin_get_report_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".reportCommentNumber").text(data); if(data > 1){ $(".pluralReportCommentNumber").text('s'); } else{ $(".pluralReportCommentNumber").remove(); } }, error: function(xhr, status, error) { console.log(error); } }); }
$(".reportComment").click(function(event){ event.preventDefault(); }); function closeDiv(){ $(function(){ $("#reportSuccess").css("display", "none"); }) } function fadeInSuccess(){ $(function(){ $("#success").fadeIn(2000); }) } function inputTitleValidation(){ var input = $("#blogbundle_post_name"); var formGroup = $("#titleGroup"); input.on('keyup keypress blur change', function() { var inputLength = input.val().length; if(inputLength < 5){ formGroup.addClass("has-error") formGroup.removeClass("has-success") } else{ formGroup.addClass("has-success") formGroup.removeClass("has-error") } }); } function setReport(id){ var path = Routing.generate('set_report'); var reportData = {"Comment_ID": id}; $.ajax({ type: "POST", data: reportData, url: path, success: function(data){ if(data){ $("#reportSuccess").fadeIn(1000); } }, error: function(xhr, status, error) { console.log(error); } }); } function deleteComment(id, postId){ var path = Routing.generate('admin_comment_delete'); var commentData = {"Comment_ID": id}; $.ajax({ type: "POST", data: commentData, url: path, success: function(data){ if(data){ $("#deleteSuccess").fadeIn(1000); $("." + id).remove(); getCommentNumber(postId); getReportCommentNumber(postId); } }, error: function(xhr, status, error) { console.log(error); } }); } function getCommentNumber(postId){ var path = Routing.generate('admin_get_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".commentNumber").text(data); if(data > 1){ $(".pluralCommentNumber").text('s'); } else{ $(".pluralCommentNumber").removeClass('pluralCommentNumber'); } }, error: function(xhr, status, error) { console.log(error); } }); } function getReportCommentNumber(postId){ var path = Routing.generate('admin_get_report_comments_post'); var commentData = {"Post_ID": postId}; $.ajax({ type: "GET", data: commentData, url: path, success: function(data){ $(".reportCommentNumber").text(data); if(data > 1){ $(".pluralReportCommentNumber").text('s'); } else{ $(".pluralReportCommentNumber").removeClass('pluralReportCommentNumber'); } }, error: function(xhr, status, error) { console.log(error); } }); }
JavaScript
0.998673
8afb1a7707580d4a9c2bcf940f7047d690a39856
Clean up webpack config
webpack.config.js
webpack.config.js
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: { index: './src/index' }, output: { path: './dist', libraryTarget: 'commonjs2', filename: 'index.js' }, resolve: { extensions: ['.js', '.json'], modules: [ path.resolve('./src'), path.resolve('./node_modules'), ] }, plugins: [ new webpack.DefinePlugin({ "global.GENTLY": false }) ], node: { __dirname: true, }, target: 'electron-renderer', module: { rules: [ { test: /\.jsx?$/, use: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader', query: { modules: true } } ] }, { test: /\.png$/, use: 'url-loader' }, { test: /\.json$/, use: 'json-loader' }, { test: /\.s[ac]ss$/, use: ['style-loader','css-loader', 'sass-loader'] } ] } };
const webpack = require('webpack'); const path = require('path'); module.exports = { entry: { index: './src/index' }, output: { path: './dist', libraryTarget: 'commonjs2', filename: 'index.js' }, resolve: { extensions: ['.js', '.json'], modules: [ path.resolve('./src'), path.resolve('./node_modules'), ] }, plugins: [ new webpack.DefinePlugin({ "global.GENTLY": false }) ], node: { __dirname: true, }, target: 'electron-renderer', module: { rules: [{ test: /\.jsx?$/, use: { loader: 'babel-loader' }, exclude: /node_modules/ }, { test: /\.css$/, use: [{ loader: 'style-loader' }, { loader: 'css-loader', query: { modules: true } }] }, { test: /\.png$/, use: { loader: 'url-loader' } }, { test: /\.json$/, use: 'json-loader' }, { test: /\.s[ac]ss$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" }] }] } };
JavaScript
0.000001
16442f24ad2defaa65a1ee783f185332b37b78fe
Update alert
client/src/js/samples/components/Analyses/List.js
client/src/js/samples/components/Analyses/List.js
import React from "react"; import { map, sortBy } from "lodash-es"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { ListGroup, FormGroup, InputGroup, FormControl, Alert } from "react-bootstrap"; import { analyze } from "../../actions"; import { Icon, Button, LoadingPlaceholder, NoneFound, Flex, FlexItem } from "../../../base"; import AnalysisItem from "./Item"; import CreateAnalysis from "./Create"; import {getCanModify} from "../../selectors"; const AnalysesToolbar = ({ onClick, isModified }) => ( <div className="toolbar"> <FormGroup> <InputGroup> <InputGroup.Addon> <Icon name="search" /> </InputGroup.Addon> <FormControl type="text" /> </InputGroup> </FormGroup> <Button icon="new-entry" tip="New Analysis" bsStyle="primary" onClick={onClick} disabled={isModified} /> </div> ); class AnalysesList extends React.Component { constructor (props) { super(props); this.state = { show: false }; } render () { if (this.props.analyses === null) { return <LoadingPlaceholder margin="37px" />; } // The content that will be shown below the "New Analysis" form. let listContent; if (this.props.analyses.length) { // The components that detail individual analyses. listContent = map(sortBy(this.props.analyses, "timestamp").reverse(), (document, index) => <AnalysisItem key={index} {...document} /> ); } else { listContent = <NoneFound noun="analyses" noListGroup />; } let alert; if (this.props.modified_count) { alert = ( <Alert bsStyle="warning"> <Flex alignItems="center"> <Icon name="info" /> <FlexItem pad={5}> <span>The virus database has changed. </span> <Link to="/viruses/indexes">Rebuild the index</Link> <span> to use the changes in further analyses.</span> </FlexItem> </Flex> </Alert> ); } return ( <div> {alert} {this.props.canModify ? <AnalysesToolbar onClick={() => this.setState({show: true})} isModified={!!this.props.modified_count} /> : null} <ListGroup> {listContent} </ListGroup> <CreateAnalysis id={this.props.detail.id} show={this.state.show} onHide={() => this.setState({show: false})} onSubmit={this.props.onAnalyze} /> </div> ); } } const mapStateToProps = (state) => ({ detail: state.samples.detail, analyses: state.samples.analyses, canModify: getCanModify(state), modified_count: state.viruses.modified_count }); const mapDispatchToProps = (dispatch) => ({ onAnalyze: (sampleId, algorithm) => { dispatch(analyze(sampleId, algorithm)); } }); const Container = connect(mapStateToProps, mapDispatchToProps)(AnalysesList); export default Container;
import React from "react"; import { map, sortBy } from "lodash-es"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { ListGroup, FormGroup, InputGroup, FormControl, Alert } from "react-bootstrap"; import { analyze } from "../../actions"; import { Icon, Button, LoadingPlaceholder, NoneFound, Flex, FlexItem } from "../../../base"; import AnalysisItem from "./Item"; import CreateAnalysis from "./Create"; import {getCanModify} from "../../selectors"; import { findIndexes } from "../../../indexes/actions"; const AnalysesToolbar = ({ onClick, isModified }) => ( <div className="toolbar"> <FormGroup> <InputGroup> <InputGroup.Addon> <Icon name="search" /> </InputGroup.Addon> <FormControl type="text" /> </InputGroup> </FormGroup> <Button icon="new-entry" tip="New Analysis" bsStyle="primary" onClick={onClick} disabled={isModified} /> </div> ); class AnalysesList extends React.Component { constructor (props) { super(props); this.state = { show: false }; } /* componentWillMount () { this.props.onFind(); } */ render () { if (this.props.analyses === null) { return <LoadingPlaceholder margin="37px" />; } // The content that will be shown below the "New Analysis" form. let listContent; if (this.props.analyses.length) { // The components that detail individual analyses. listContent = map(sortBy(this.props.analyses, "timestamp").reverse(), (document, index) => <AnalysisItem key={index} {...document} /> ); } else { listContent = <NoneFound noun="analyses" noListGroup />; } let alert; if (this.props.modified_count) { alert = ( <Alert bsStyle="warning"> <Flex alignItems="center"> <Icon name="info" /> <FlexItem pad={5}> <span>The virus database has changed. </span> <Link to="/viruses/indexes">Rebuild the index</Link> <span> to use the changes in further analyses.</span> </FlexItem> </Flex> </Alert> ); } return ( <div> {alert} {this.props.canModify ? <AnalysesToolbar onClick={() => this.setState({show: true})} isModified={!!this.props.modified_count} /> : null} <ListGroup> {listContent} </ListGroup> <CreateAnalysis id={this.props.detail.id} show={this.state.show} onHide={() => this.setState({show: false})} onSubmit={this.props.onAnalyze} /> </div> ); } } const mapStateToProps = (state) => ({ detail: state.samples.detail, analyses: state.samples.analyses, canModify: getCanModify(state), modified_count: state.viruses.modified_count }); const mapDispatchToProps = (dispatch) => ({ onAnalyze: (sampleId, algorithm) => { dispatch(analyze(sampleId, algorithm)); } }); const Container = connect(mapStateToProps, mapDispatchToProps)(AnalysesList); export default Container;
JavaScript
0.000001
93fec369dc6bcee9fbbbab236e46f217ef2ceee7
Write optimization test for font-face
test/font-face.js
test/font-face.js
var assert = require("assert"); var crass = require('../crass'); var filler = 'src:"";foo:bar'; var parity = function(data) { data = data.replace(/\$\$/g, filler); assert.equal(crass.parse(data).toString(), data); assert.equal(crass.parse(crass.parse(data).pretty()).toString(), data); } describe('@font-face', function() { it('should parse font-face blocks', function() { parity('@font-face{$$}'); }); it('should optimize', function() { assert.equal( crass.parse('@font-face{font-weight:bold}').optimize().toString(), '@font-face{font-weight:700}' ); }); });
var assert = require("assert"); var crass = require('../crass'); var filler = 'src:"";foo:bar'; var parity = function(data) { data = data.replace(/\$\$/g, filler); assert.equal(crass.parse(data).toString(), data); assert.equal(crass.parse(crass.parse(data).pretty()).toString(), data); } describe('@font-face', function() { it('should parse font-face blocks', function() { parity('@font-face{$$}'); }); });
JavaScript
0.000039
62849d1cfd10ba2c020544f7fa8d9243a76da82c
Fix tests
test/is-base64.js
test/is-base64.js
var test = require('tape'); var isBase64 = require('../is-base64'); test('isBase64', function (t) { t.plan(7); var pngString = 'iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var pngStringWithMime = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var jpgString = '/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k=' var jpgStringWithMime = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k='; t.equal(isBase64(pngString), true); t.equal(isBase64(pngStringWithMime), true); t.equal(isBase64(jpgString), true); t.equal(isBase64(jpgStringWithMime), true); t.equal(isBase64('1342234'), false); t.equal(isBase64('afQ$%rfew'), false); t.equal(isBase64('dfasdfr342'), false); });
var test = require('tape'); var isBase64 = require('../is-base64'); test('isBase64', function (t) { t.plan(7); var pngString = 'iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var pngStringWithMime = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAALQAQMAAAD1s08VAAAAA1BMVEX/AAAZ4gk3AAAAh0lEQVR42u3BMQEAAADCoPVPbQlPoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB4GsTfAAGc95RKAAAAAElFTkSuQmCC'; var jpgString = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k=' var jpgStringWithMime = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEACAhITMkM1EwMFFCLy8vQiccHBwcJyIXFxcXFyIRDAwMDAwMEQwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBIjMzNCY0IhgYIhQODg4UFA4ODg4UEQwMDAwMEREMDAwMDAwRDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDP/AABEIAAYABgMBIgACEQEDEQH/xABVAAEBAAAAAAAAAAAAAAAAAAAAAxAAAQQCAwEAAAAAAAAAAAAAAgABAxQEIxIkMxMBAQAAAAAAAAAAAAAAAAAAAAARAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AIE7MwkbOUJDJWx+ZjXATitx2/h2bEWvX5Y0npQ7aIiD/9k='; t.equal(isBase64(pngString), true); t.equal(isBase64(pngStringWithMime), true); t.equal(isBase64(jpgString), true); t.equal(isBase64(jpgStringWithMime), true); t.equal(isBase64('1342234'), false); t.equal(isBase64('afQ$%rfew'), false); t.equal(isBase64('dfasdfr342'), false); });
JavaScript
0.000003
5610038d24a316ffc14de2c854233de5b1e44954
Fix path tests. Add new tests.
lib/axiom/fs/path.test.js
lib/axiom/fs/path.test.js
// Copyright 2015 Google Inc. All rights reserved. // // 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 Path from 'axiom/fs/path'; var failTest = function(error) { expect(error).toBeUndefined(); }; describe('Path', function () { it('should be available as a module', function () { expect(Path).toBeDefined(); }); it('should not allow undefined path', function () { expect(function() { /** @type {string} */ var x; var p = new Path(x); }).toThrow(); }); it('should allow empty path', function () { var p = new Path('fs:'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); }); it('should allow root path', function () { var p = new Path('fs:/'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual([]); }); it('should return null for parent of root path', function () { var p = new Path('fs:/').getParentPath(); expect(p).toBe(null); }); it('should split path with multiple elements', function () { var p = new Path('fs:foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should split path with multiple elements', function () { var p = new Path('fs:/foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should return the base name as a string', function () { var p = new Path('fs:/foo/bar/blah').getBaseName(); expect(p).toBeDefined(); expect(p).toEqual('blah'); }); it('should combine root with simple relative paths', function () { var p = new Path('fs:').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:/foo'); }); it('should combine simple relative paths', function () { var p = new Path('fs:bar').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:/bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('./foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:/bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('../foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:/foo'); }); it('should resolve paths relative to current fs', function () { var p = Path.abs('fs:bar', '/foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:/foo'); }); });
// Copyright 2015 Google Inc. All rights reserved. // // 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 Path from 'axiom/fs/path'; var failTest = function(error) { expect(error).toBeUndefined(); }; describe('Path', function () { it('should be available as a module', function () { expect(Path).toBeDefined(); }); it('should not allow undefined path', function () { expect(function() { /** @type {string} */ var x; var p = new Path(x); }).toThrow(); }); it('should allow empty path', function () { var p = new Path('fs:'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); }); it('should allow root path', function () { var p = new Path('fs:/'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual([]); }); it('should return null for parent of root path', function () { var p = new Path('fs:/').getParentPath(); expect(p).toBe(null); }); it('should split path with multiple elements', function () { var p = new Path('fs:foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should split path with multiple elements', function () { var p = new Path('fs:/foo/bar'); expect(p).toBeDefined(); expect(p.isValid).toBe(true); expect(p.elements).toEqual(['foo', 'bar']); }); it('should return the base name as a string', function () { var p = new Path('fs:/foo/bar/blah').getBaseName(); expect(p).toBeDefined(); expect(p).toEqual('blah'); }); it('should combine root with simple relative paths', function () { var p = new Path('fs:').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:foo'); }); it('should combine simple relative paths', function () { var p = new Path('fs:bar').combine('foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('./foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:bar/foo'); }); it('should combine dotted relative paths', function () { var p = new Path('fs:bar').combine('../foo'); expect(p).toBeDefined(); expect(p.spec).toEqual('fs:foo'); }); });
JavaScript
0
258e32547481adc71c21b0b09166501ef9090281
remove hover effects on mobile
client/js/views/TaskView.js
client/js/views/TaskView.js
/*global define */ define([ 'marionette', 'templates', 'underscore', 'app' ], function (Marionette, templates, _, app) { 'use strict'; return Marionette.ItemView.extend({ className: 'task-view item', template: templates.task, ui: { 'remove': '.remove', 'edit': '.edit', 'task': '.task', 'editTask': '.edit-task', 'newTitle': '.new-title', 'newAmount': '.new-amount' }, events: { 'click .task': 'onClickTask', 'click .remove': 'onClickRemove', 'click .edit': 'onClickEdit', 'click .save-task': 'onClickSaveTask', 'mouseover': 'onHover', 'mouseout': 'onStopHover' }, onRender: function() { if (!this.model.get('doable')) { $(this.el).addClass('disabled'); } this.ui.remove.hide(); this.ui.edit.hide(); this.ui.editTask.hide(); // event listener }, onClickTask: function(e) { e.preventDefault(); if (this.model.get('doable')) { this.model.set('completed', true); this.model.save(); var user = window.app.user, bank_amt = user.get("bank"); user.set("bank", bank_amt + this.model.get("amount")); this.destroy(); } }, onClickRemove: function(e) { e.preventDefault(); e.stopPropagation(); this.model.destroy(); this.destroy(); }, onClickEdit: function(e) { e.preventDefault(); e.stopPropagation(); this.ui.task.hide(); this.ui.editTask.show(); }, onClickSaveTask: function(e) { e.preventDefault(); this.model.set('title', this.ui.newTitle.val()); this.model.set('amount', this.ui.newAmount.val()); this.model.save(); this.render(); }, onHover: function() { if(!window.mobile) { this.ui.remove.show(); this.ui.edit.show(); } }, onStopHover: function() { if (!window.mobile) { this.ui.remove.hide(); this.ui.edit.hide(); } } }); });
/*global define */ define([ 'marionette', 'templates', 'underscore', 'app' ], function (Marionette, templates, _, app) { 'use strict'; return Marionette.ItemView.extend({ className: 'task-view item', template: templates.task, ui: { 'remove': '.remove', 'edit': '.edit', 'task': '.task', 'editTask': '.edit-task', 'newTitle': '.new-title', 'newAmount': '.new-amount' }, events: { 'click .task': 'onClickTask', 'click .remove': 'onClickRemove', 'click .edit': 'onClickEdit', 'click .save-task': 'onClickSaveTask', 'mouseover': 'onHover', 'mouseout': 'onStopHover' }, onRender: function() { if (!this.model.get('doable')) { $(this.el).addClass('disabled'); } this.ui.remove.hide(); this.ui.edit.hide(); this.ui.editTask.hide(); // event listener }, onClickTask: function(e) { e.preventDefault(); if (this.model.get('doable')) { this.model.set('completed', true); this.model.save(); var user = window.app.user, bank_amt = user.get("bank"); user.set("bank", bank_amt + this.model.get("amount")); this.destroy(); } }, onClickRemove: function(e) { e.preventDefault(); e.stopPropagation(); this.model.destroy(); this.destroy(); }, onClickEdit: function(e) { e.preventDefault(); e.stopPropagation(); this.ui.task.hide(); this.ui.editTask.show(); }, onClickSaveTask: function(e) { e.preventDefault(); this.model.set('title', this.ui.newTitle.val()); this.model.set('amount', this.ui.newAmount.val()); this.model.save(); this.render(); }, onHover: function() { this.ui.remove.show(); this.ui.edit.show(); }, onStopHover: function() { this.ui.remove.hide(); this.ui.edit.hide(); } }); });
JavaScript
0.000001
7b123ab0934aa9304dc9a9bf334dac8bfbbe1e04
change ETH language
lib/blockchain/install.js
lib/blockchain/install.js
const fs = require('fs') const path = require('path') const process = require('process') const os = require('os') const makeDir = require('make-dir') const inquirer = require('inquirer') const _ = require('lodash/fp') const coinUtils = require('../coin-utils') const common = require('./common') const doVolume = require('./do-volume') const cryptos = coinUtils.cryptoCurrencies() const logger = common.logger const PLUGINS = { BTC: require('./bitcoin.js'), LTC: require('./litecoin.js'), ETH: require('./ethereum.js'), DASH: require('./dash.js'), ZEC: require('./zcash.js'), BCH: require('./bitcoincash.js') } module.exports = {run} function installedVolumeFilePath (crypto) { return path.resolve(coinUtils.cryptoDir(crypto), '.installed') } function isInstalledVolume (crypto) { return fs.existsSync(installedVolumeFilePath(crypto)) } function isInstalledSoftware (crypto) { return common.isInstalledSoftware(crypto) } function processCryptos (codes) { if (_.isEmpty(codes)) { logger.info('No cryptos selected. Exiting.') process.exit(0) } logger.info('Thanks! Installing: %s. Will take a while...', _.join(', ', codes)) const goodVolume = doVolume.prepareVolume() if (!goodVolume) { logger.error('There was an error preparing the disk volume. Exiting.') process.exit(1) } const selectedCryptos = _.map(code => _.find(['code', code], cryptos), codes) _.forEach(setupCrypto, selectedCryptos) common.es('sudo service supervisor restart') const blockchainDir = coinUtils.blockchainDir() const backupDir = path.resolve(os.homedir(), 'backups') const rsyncCmd = `( \ (crontab -l 2>/dev/null || echo -n "") | grep -v "@daily rsync ".*"wallet.dat"; \ echo "@daily rsync -r --prune-empty-dirs --include='*/' \ --include='wallet.dat' \ --exclude='*' ${blockchainDir} ${backupDir} > /dev/null" \ ) | crontab -` common.es(rsyncCmd) logger.info('Installation complete.') } function setupCrypto (crypto) { logger.info(`Installing ${crypto.display}...`) const cryptoDir = coinUtils.cryptoDir(crypto) makeDir.sync(cryptoDir) const cryptoPlugin = plugin(crypto) const oldDir = process.cwd() const tmpDir = '/tmp/blockchain-install' makeDir.sync(tmpDir) process.chdir(tmpDir) common.es('rm -rf *') common.fetchAndInstall(crypto) cryptoPlugin.setup(cryptoDir) common.writeFile(installedVolumeFilePath(crypto), '') process.chdir(oldDir) } function plugin (crypto) { const plugin = PLUGINS[crypto.cryptoCode] if (!plugin) throw new Error(`No such plugin: ${crypto.cryptoCode}`) return plugin } function run () { const choices = _.map(c => { const checked = isInstalledSoftware(c) && isInstalledVolume(c) return { name: c.display, value: c.code, checked, disabled: c.cryptoCode === 'ETH' ? 'Use admin\'s Infura plugin' : checked && 'Installed' } }, cryptos) const questions = [] questions.push({ type: 'checkbox', name: 'crypto', message: 'Which cryptocurrencies would you like to install?', choices }) inquirer.prompt(questions) .then(answers => processCryptos(answers.crypto)) }
const fs = require('fs') const path = require('path') const process = require('process') const os = require('os') const makeDir = require('make-dir') const inquirer = require('inquirer') const _ = require('lodash/fp') const coinUtils = require('../coin-utils') const common = require('./common') const doVolume = require('./do-volume') const cryptos = coinUtils.cryptoCurrencies() const logger = common.logger const PLUGINS = { BTC: require('./bitcoin.js'), LTC: require('./litecoin.js'), ETH: require('./ethereum.js'), DASH: require('./dash.js'), ZEC: require('./zcash.js'), BCH: require('./bitcoincash.js') } module.exports = {run} function installedVolumeFilePath (crypto) { return path.resolve(coinUtils.cryptoDir(crypto), '.installed') } function isInstalledVolume (crypto) { return fs.existsSync(installedVolumeFilePath(crypto)) } function isInstalledSoftware (crypto) { return common.isInstalledSoftware(crypto) } function processCryptos (codes) { if (_.isEmpty(codes)) { logger.info('No cryptos selected. Exiting.') process.exit(0) } logger.info('Thanks! Installing: %s. Will take a while...', _.join(', ', codes)) const goodVolume = doVolume.prepareVolume() if (!goodVolume) { logger.error('There was an error preparing the disk volume. Exiting.') process.exit(1) } const selectedCryptos = _.map(code => _.find(['code', code], cryptos), codes) _.forEach(setupCrypto, selectedCryptos) common.es('sudo service supervisor restart') const blockchainDir = coinUtils.blockchainDir() const backupDir = path.resolve(os.homedir(), 'backups') const rsyncCmd = `( \ (crontab -l 2>/dev/null || echo -n "") | grep -v "@daily rsync ".*"wallet.dat"; \ echo "@daily rsync -r --prune-empty-dirs --include='*/' \ --include='wallet.dat' \ --exclude='*' ${blockchainDir} ${backupDir} > /dev/null" \ ) | crontab -` common.es(rsyncCmd) logger.info('Installation complete.') } function setupCrypto (crypto) { logger.info(`Installing ${crypto.display}...`) const cryptoDir = coinUtils.cryptoDir(crypto) makeDir.sync(cryptoDir) const cryptoPlugin = plugin(crypto) const oldDir = process.cwd() const tmpDir = '/tmp/blockchain-install' makeDir.sync(tmpDir) process.chdir(tmpDir) common.es('rm -rf *') common.fetchAndInstall(crypto) cryptoPlugin.setup(cryptoDir) common.writeFile(installedVolumeFilePath(crypto), '') process.chdir(oldDir) } function plugin (crypto) { const plugin = PLUGINS[crypto.cryptoCode] if (!plugin) throw new Error(`No such plugin: ${crypto.cryptoCode}`) return plugin } function run () { const choices = _.map(c => { const checked = isInstalledSoftware(c) && isInstalledVolume(c) return { name: c.display, value: c.code, checked, disabled: c.cryptoCode === 'ETH' ? 'Installed, use Infura option' : checked && 'Installed' } }, cryptos) const questions = [] questions.push({ type: 'checkbox', name: 'crypto', message: 'Which cryptocurrencies would you like to install?', choices }) inquirer.prompt(questions) .then(answers => processCryptos(answers.crypto)) }
JavaScript
0.998663
dbff6c1cc9d0deb3f23f80d941898e901b88ee11
fix copyTemplate editor path
lib/copyTemplateAssets.js
lib/copyTemplateAssets.js
'use strict'; const File = require( 'vinyl' ); const fs = require( 'fs' ); const copyTemplateAssets = function ( stream ) { let cssSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.css', { encoding: 'utf-8' } ); let css = new File( { path: '_template/_template.css', contents: new Buffer( cssSrc ) } ); stream.push( css ); let jsSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.js', { encoding: 'utf-8' } ); let js = new File( { path: '_template/_template.js', contents: new Buffer( jsSrc ) } ); stream.push( js ); var fontSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.woff' ); let fontFile = new File( { path: '_template/_template.woff', contents: new Buffer( fontSrc ) } ); stream.push( fontFile ); // editor let editorHtmlSrc = fs.readFileSync( __dirname + '/editor/build/_editor.html', { encoding: 'utf-8' } ); let editorHtml = new File( { path: '_editor.html', contents: new Buffer( editorHtmlSrc ) } ); stream.push( editorHtml ); let editorCssSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.css', { encoding: 'utf-8' } ); let editorCss = new File( { path: '_editor/_editor.css', contents: new Buffer( editorCssSrc ) } ); stream.push( editorCss ); let editorJsSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.js', { encoding: 'utf-8' } ); let editorJs = new File( { path: '_editor/_editor.js', contents: new Buffer( editorJsSrc ) } ); stream.push( editorJs ); } module.exports = copyTemplateAssets;
'use strict'; const File = require( 'vinyl' ); const fs = require( 'fs' ); const copyTemplateAssets = function ( stream ) { let cssSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.css', { encoding: 'utf-8' } ); let css = new File( { path: '_template/_template.css', contents: new Buffer( cssSrc ) } ); stream.push( css ); let jsSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.js', { encoding: 'utf-8' } ); let js = new File( { path: '_template/_template.js', contents: new Buffer( jsSrc ) } ); stream.push( js ); var fontSrc = fs.readFileSync( __dirname + '/template/build/_template/_template.woff' ); let fontFile = new File( { path: '_template/_template.woff', contents: new Buffer( fontSrc ) } ); stream.push( fontFile ); // editor let editorHtmlSrc = fs.readFileSync( __dirname + '/editor/build/_editor.html', { encoding: 'utf-8' } ); let editorHtml = new File( { path: '_editor.html', contents: new Buffer( editorHtmlSrc ) } ); stream.push( editorHtml ); let editorCssSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.css', { encoding: 'utf-8' } ); let editorCss = new File( { path: '_editor/_editor.css', contents: new Buffer( editorCssSrc ) } ); stream.push( editorCss ); let editorJsSrc = fs.readFileSync( __dirname + '/editor/build/_editor/_editor.Js', { encoding: 'utf-8' } ); let editorJs = new File( { path: '_editor/_editor.js', contents: new Buffer( editorJsSrc ) } ); stream.push( editorJs ); } module.exports = copyTemplateAssets;
JavaScript
0
4232a776869073f6aa1ec0c7ac166499d1fbf0a3
fix #11 always waiting for WDS
src/DatePicker2.js
src/DatePicker2.js
import React, { Component, PropTypes } from 'react'; import { default as ReactDatePicker } from 'react-datepicker'; import moment from 'moment'; /** * DatePicker2控件 */ export default class DatePicker2 extends Component { static defaultProps = { dateFormat: 'YYYY-MM-DD' } static propTypes = { /** * 日期格式<br> * 遵循moment.js格式<br> * <a href="https://momentjs.com/docs/#/displaying/format/">Moment.js文档</a> */ dateFormat: PropTypes.string, /** * value 请使用ISO 8061格式 */ value: PropTypes.string, showMonthDropdown: PropTypes.bool, showYearDropdown: PropTypes.bool, /** * 参数: * - value: ISO 8061格式时间字符串 * - formattedValue: 按照用户指定格式进行了格式化后的字符串 * - momentDate: moment.js对象 */ onChange: PropTypes.func }; state = { }; constructor(props) { super(props); } // date参数是moment.js生成的时间格式 handleChange(date) { if (this.props.onChange) { this.props.onChange( date.toDate().toISOString(), // ISO 8601 date.format(this.props.dateFormat), // 使用moment.js按照用户指定的格式进行格式化 date ); } } render() { // 之前使用otherProps获取react-datepicker的属性,然后往下传 // 但是出现了bug#11 const { value, showMonthDropdown, showYearDropdown } = this.props; return (<ReactDatePicker showMonthDropdown={showMonthDropdown} showYearDropdown={showYearDropdown} selected={moment(value)} onChange={this.handleChange.bind(this)} />); } }
import React, { Component, PropTypes } from 'react'; import { default as ReactDatePicker } from 'react-datepicker'; import moment from 'moment'; /** * DatePicker2控件 */ export default class DatePicker2 extends Component { static defaultProps = { dateFormat: 'YYYY-MM-DD' } static propTypes = { /** * 日期格式<br> * 遵循moment.js格式<br> * <a href="https://momentjs.com/docs/#/displaying/format/">Moment.js文档</a> */ dateFormat: PropTypes.string, /** * value 请使用ISO 8061格式 */ value: PropTypes.string, showMonthDropdown: PropTypes.bool, showYearDropdown: PropTypes.bool, /** * 参数: * - value: ISO 8061格式时间字符串 * - formattedValue: 按照用户指定格式进行了格式化后的字符串 * - momentDate: moment.js对象 */ onChange: PropTypes.func }; state = { }; constructor(props) { super(props); } // date参数是moment.js生成的时间格式 handleChange(date) { if (this.props.onChange) { this.props.onChange( date.toDate().toISOString(), // ISO 8601 date.format(this.props.dateFormat), // 使用moment.js按照用户指定的格式进行格式化 date ); } } render() { // 使用otherProps获取react-datepicker的属性,然后往下传 const { value, ...otherProps } = this.props; return (<ReactDatePicker {...otherProps} selected={moment(value)} onChange={this.handleChange.bind(this)} />); } }
JavaScript
0
a04aa685cc69ef792a7e2d1f457ba065d7f11b57
Fix lint errors in client parser
lib/html-to-dom-client.js
lib/html-to-dom-client.js
'use strict'; /** * Module dependencies. */ var utilities = require('./utilities'); var formatDOM = utilities.formatDOM; /** * Parse HTML string to DOM nodes. * This uses the browser DOM API. * * @param {String} html - The HTML. * @return {Object} - The DOM nodes. */ function parseDOM(html) { if (typeof html !== 'string') { throw new TypeError('First argument must be a string.'); } // try to match the tags var match = html.match(/<[^\/](.+?)>/g); var nodes; if (match && match.length) { var tagMatch = match[0]; // directive matched if (/<![^-]/.test(tagMatch)) { var directive = ( // remove angle brackets tagMatch .substring(1, tagMatch.length - 1) .trim() ); // tag name can no longer be first match item tagMatch = match[1]; // remove directive from html html = html.substring(html.indexOf('>') + 1); } // first tag name matched if (tagMatch) { var tagName = ( // keep only tag name tagMatch .substring(1, tagMatch.indexOf(' ')) .trim() .toLowerCase() ) } } // create html document to parse top-level nodes if (['html', 'head', 'body'].indexOf(tagName) > -1) { var doc; // `new DOMParser().parseFromString()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Parsing_an_SVG_or_HTML_document if (window.DOMParser) { doc = new window.DOMParser().parseFromString(html, 'text/html'); // `DOMImplementation.createHTMLDocument()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument } else if (document.implementation.createHTMLDocument) { doc = document.implementation.createHTMLDocument(); doc.documentElement.innerHTML = html; doc.removeChild(doc.childNodes[0]); // remove doctype } // html if (tagName === 'html') { nodes = doc.childNodes; // head and body } else { nodes = ( // do this so attributes are kept // but there may be an extra head/body node doc.getElementsByTagName(tagName)[0] .parentNode .childNodes ); } // `innerHTML` approach } else { var container = document.createElement('body'); container.innerHTML = html; nodes = container.childNodes; } return formatDOM(nodes, null, directive); } /** * Export HTML to DOM parser (client). */ module.exports = parseDOM;
'use strict'; /** * Module dependencies. */ var utilities = require('./utilities'); var formatDOM = utilities.formatDOM; /** * Parse HTML string to DOM nodes. * This uses the browser DOM API. * * @param {String} html - The HTML. * @return {Object} - The DOM nodes. */ function parseDOM(html) { if (typeof html !== 'string') { throw new TypeError('First argument must be a string.'); } // try to match the tags var match = html.match(/<[^\/](.+?)>/g); var container; var parentNode; var nodes; if (match && match.length) { var tagMatch = match[0]; // directive matched if (/<![^-]/.test(tagMatch)) { var directive = ( // remove angle brackets tagMatch .substring(1, tagMatch.length - 1) .trim() ); // tag name can no longer be first match item tagMatch = match[1]; // remove directive from html html = html.substring(html.indexOf('>') + 1); } // first tag name matched if (tagMatch) { var tagName = ( // keep only tag name tagMatch .substring(1, tagMatch.indexOf(' ')) .trim() .toLowerCase() ) } } // create html document to parse top-level nodes if (['html', 'head', 'body'].indexOf(tagName) > -1) { var doc; // `new DOMParser().parseFromString()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Parsing_an_SVG_or_HTML_document if (window.DOMParser) { doc = new window.DOMParser().parseFromString(html, 'text/html'); // `DOMImplementation.createHTMLDocument()` // https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createHTMLDocument } else if (document.implementation.createHTMLDocument) { doc = document.implementation.createHTMLDocument(); doc.documentElement.innerHTML = html; doc.removeChild(doc.childNodes[0]); // remove doctype } // html if (tagName === 'html') { nodes = doc.childNodes; // head and body } else { nodes = ( // do this so attributes are kept // but there may be an extra head/body node doc.getElementsByTagName(tagName)[0] .parentNode .childNodes ); } // `innerHTML` approach } else { var container = document.createElement('body'); container.innerHTML = html; nodes = container.childNodes; } return formatDOM(nodes, null, directive); } /** * Export HTML to DOM parser (client). */ module.exports = parseDOM;
JavaScript
0.000012
48b88c98178c079b5eae3261752605bc10004c18
Fix typo
assets/static/js/tipuesearch_set.js
assets/static/js/tipuesearch_set.js
/* Tipue Search 5.0 Copyright (c) 2015 Tipue Tipue Search is released under the MIT License http://www.tipue.com/search */ /* Stop words list from http://www.ranks.nl/stopwords/german */ var tipuesearch_stop_words = ["aber", "als", "am", "an", "auch", "auf", "aus", "bei", "bin", "bis", "bist", "da", "dadurch", "daher", "darum", "das", "daß", "dass", "dein", "deine", "dem", "den", "der", "des", "dessen", "deshalb", "die", "dies", "dieser", "dieses", "doch", "dort", "du", "durch", "ein", "eine", "einem", "einen", "einer", "eines", "er", "es", "euer", "eure", "für", "hatte", "hatten", "hattest", "hattet", "hier", "hinter", "ich", "ihr", "ihre", "im", "in", "ist", "ja", "jede", "jedem", "jeden", "jeder", "jedes", "jener", "jenes", "jetzt", "kann", "kannst", "können", "könnt", "machen", "mein", "meine", "mit", "muß", "mußt", "musst", "müssen", "müßt", "nach", "nachdem", "nein", "nicht", "nun", "oder", "seid", "sein", "seine", "sich", "sie", "sind", "soll", "sollen", "sollst", "sollt", "sonst", "soweit", "sowie", "und", "unser", "unsere", "unter", "vom", "von", "vor", "wann", "warum", "was", "weiter", "weitere", "wenn", "wer", "werde", "werden", "werdet", "weshalb", "wie", "wieder", "wieso", "wir", "wird", "wirst", "wo", "woher", "wohin", "zu", "zum", "zur", "über"]; var tipuesearch_replace = {'words': []}; var tipuesearch_weight = {'weight': []}; var tipuesearch_stem = {'words': []}; var tipuesearch_string_1 = 'Kein Title'; var tipuesearch_string_2 = 'Resultate für'; var tipuesearch_string_3 = 'Suche stattdessen nach'; var tipuesearch_string_4 = '1 Resultat'; var tipuesearch_string_5 = 'Resultate'; var tipuesearch_string_6 = 'Vorherige'; var tipuesearch_string_7 = 'Nächste'; var tipuesearch_string_8 = 'Nichts gefunden.'; var tipuesearch_string_9 = 'Häufig verwendete Begriffe werden weitgehend ignoriert'; var tipuesearch_string_10 = 'Suchbegriff zu kurz'; var tipuesearch_string_11 = 'Sollte mindestens ein Zeichen sein'; var tipuesearch_string_12 = 'Sollte'; var tipuesearch_string_13 = 'Zeichen oder mehr';
/* Tipue Search 5.0 Copyright (c) 2015 Tipue Tipue Search is released under the MIT License http://www.tipue.com/search */ /* Stop words list from http://www.ranks.nl/stopwords/german */ var tipuesearch_stop_words = ["aber", "als", "am", "an", "auch", "auf", "aus", "bei", "bin", "bis", "bist", "da", "dadurch", "daher", "darum", "das", "daß", "dass", "dein", "deine", "dem", "den", "der", "des", "dessen", "deshalb", "die", "dies", "dieser", "dieses", "doch", "dort", "du", "durch", "ein", "eine", "einem", "einen", "einer", "eines", "er", "es", "euer", "eure", "für", "hatte", "hatten", "hattest", "hattet", "hier", "hinter", "ich", "ihr", "ihre", "im", "in", "ist", "ja", "jede", "jedem", "jeden", "jeder", "jedes", "jener", "jenes", "jetzt", "kann", "kannst", "können", "könnt", "machen", "mein", "meine", "mit", "muß", "mußt", "musst", "müssen", "müßt", "nach", "nachdem", "nein", "nicht", "nun", "oder", "seid", "sein", "seine", "sich", "sie", "sind", "soll", "sollen", "sollst", "sollt", "sonst", "soweit", "sowie", "und", "unser", "unsere", "unter", "vom", "von", "vor", "wann", "warum", "was", "weiter", "weitere", "wenn", "wer", "werde", "werden", "werdet", "weshalb", "wie", "wieder", "wieso", "wir", "wird", "wirst", "wo", "woher", "wohin", "zu", "zum", "zur", "über"]; var tipuesearch_replace = {'words': []}; var tipuesearch_weight = {'weight': []}; var tipuesearch_stem = {'words': []}; var tipuesearch_string_1 = 'Kein Title'; var tipuesearch_string_2 = 'Resultate für'; var tipuesearch_string_3 = 'Suche stattdessen nach'; var tipuesearch_string_4 = '1 Resultat'; var tipuesearch_string_5 = 'Resultate'; var tipuesearch_string_6 = 'Vorherige'; var tipuesearch_string_7 = 'Nächste'; var tipuesearch_string_8 = 'Nichts gefunden.'; var tipuesearch_string_9 = 'Häufig verwendete Begriffe werden weitgehend ignoriert'; var tipuesearch_string_10 = 'Suchbegriff zu kuzr'; var tipuesearch_string_11 = 'Sollte mindestens ein Zeichen sein'; var tipuesearch_string_12 = 'Sollte'; var tipuesearch_string_13 = 'Zeichen oder mehr';
JavaScript
0.999999
4ac850b7bfbda143572942ec8f962632fd48f22b
Fix session being sought on res
lib/middleware/authBot.js
lib/middleware/authBot.js
var r = require('rethinkdb'); var redditBot = require('../reddit/contexts/bot.js'); module.exports = function authBotCtor(cfg, env) { var botAuthReddit = redditBot(cfg); return function authBot(req, res, next) { botAuthReddit.auth(req.query.code).then(function (refreshToken) { return botAuthReddit.deauth() .then(function(){ return r.table('users').get(cfg.botName) .update({refreshToken: refreshToken}).run(env.conn); }) .then(function () { // "log out" and redirect to the index // so we can log in as ourselves delete req.session.username; delete req.session.bot; res.redirect('/'); },next); }); }; };
var r = require('rethinkdb'); var redditBot = require('../reddit/contexts/bot.js'); module.exports = function authBotCtor(cfg, env) { var botAuthReddit = redditBot(cfg); return function authBot(req, res, next) { botAuthReddit.auth(req.query.code).then(function (refreshToken) { return botAuthReddit.deauth() .then(function(){ return r.table('users').get(cfg.botName) .update({refreshToken: refreshToken}).run(env.conn); }) .then(function () { // "log out" and redirect to the index // so we can log in as ourselves delete res.session.username; delete res.session.bot; res.redirect('/'); },next); }); }; };
JavaScript
0
61a79ee4d9eebea667fc5398d7b73b2bb4efc03b
Fix the bug of css()
lib/plugins/helper/css.js
lib/plugins/helper/css.js
var extend = require('../../extend'), root = hexo.config.root; extend.helper.register('css', function(path){ if (!Array.isArray(path)) path = [path]; var result = []; path.forEach(function(item){ if (item.substr(item.length - 4, 4) !== '.css') item += '.css'; if (item.substr(0, 1) !== '/') item = root + item; result.push('<link rel="stylesheet" href="' + item + '" type="text/css">'); }); return result.join('\n'); });
var extend = require('../../extend'), root = hexo.config.root; extend.helper.register('css', function(path){ if (!Array.isArray) path = [path]; var result = []; path.forEach(function(item){ if (item.substr(item.length - 4, 4) !== '.css') item += '.css'; if (item.substr(0, 1) !== '/') item += root; result.push('<link rel="stylesheet" href="' + item + '" type="text/css">'); }); return result.join('\n'); });
JavaScript
0.00005
3cd20707461c14205a7d5889d52f7128785d2f35
Reverted the hardcoded UUID
lib/startup/SetupAdmin.js
lib/startup/SetupAdmin.js
var UserManager = require('../UserManager') , orm = require('../orm') , magnetId = require('node-uuid'); var SetupAdmin = function(){ orm.model('User').find({ where : { email : "manager1@magnetapi.com" } }).success(function(user){ if(!user){ // create a test user if it does not already exist UserManager.create({ email : "manager1@magnetapi.com", firstName : "Manager", lastName : "One", companyName : "Magnet Systems, Inc.", password : "test", userType : 'admin', magnetId : magnetId.v1() }, function(e){ if(e){ console.error('User: error creating test user: '+e); }else{ console.info('User: test user created: manager1@magnetapi.com/test'); } }); } }); }; new SetupAdmin();
var UserManager = require('../UserManager') , orm = require('../orm') , magnetId = require('node-uuid'); var SetupAdmin = function(){ orm.model('User').find({ where : { email : "manager1@magnetapi.com" } }).success(function(user){ if(!user){ // create a test user if it does not already exist UserManager.create({ email : "manager1@magnetapi.com", firstName : "Manager", lastName : "One", companyName : "Magnet Systems, Inc.", password : "test", userType : 'admin', magnetId : '72150120-2746-11e3-acbe-71879d0cf3c3' }, function(e){ if(e){ console.error('User: error creating test user: '+e); }else{ console.info('User: test user created: manager1@magnetapi.com/test'); } }); } }); }; new SetupAdmin();
JavaScript
0.99983
b35e30fecd3023e2b8a6596cdc3641eaea99a1c9
make z-index work with overworld
lib/systems/draw-image.js
lib/systems/draw-image.js
"use strict"; function drawEntity(data, entity, context) { var image = data.images.get(entity.image.name); if (!image) { console.error("No such image", entity.image.name); return; } try { context.drawImage( image, entity.image.sourceX, entity.image.sourceY, entity.image.sourceWidth, entity.image.sourceHeight, entity.image.destinationX + entity.position.x, entity.image.destinationY + entity.position.y, entity.image.destinationWidth, entity.image.destinationHeight ); } catch (e) { console.error("Error drawing image", entity.image.name, e); } } module.exports = function(ecs, data) { ecs.add(function(entities, context) { var keys = Object.keys(entities); keys.sort(function(a, b) { var za = (entities[a].zindex || {zindex:0}).zindex; var zb = (entities[b].zindex || {zindex:0}).zindex; return za - zb; }); for (var i = 0; i < keys.length; i++) { var entity = entities[keys[i]]; if (entity.image === undefined || entity.position === undefined) { continue; } drawEntity(data, entity, context); } }); };
"use strict"; function drawEntity(data, entity, context) { var image = data.images.get(entity.image.name); if (!image) { console.error("No such image", entity.image.name); return; } try { context.drawImage( image, entity.image.sourceX, entity.image.sourceY, entity.image.sourceWidth, entity.image.sourceHeight, entity.image.destinationX + entity.position.x, entity.image.destinationY + entity.position.y, entity.image.destinationWidth, entity.image.destinationHeight ); } catch (e) { console.error("Error drawing image", entity.image.name, e); } } module.exports = function(ecs, data) { ecs.add(function(entities, context) { var keys = Object.keys(entities); keys.sort(function(a, b) { var za = entities[a].zindex || 0; var zb = entities[b].zindex || 0; return za - zb; }); for (var i = 0; i < keys.length; i++) { var entity = entities[keys[i]]; if (entity.image === undefined || entity.position === undefined) { continue; } drawEntity(data, entity, context); } }); };
JavaScript
0.000001
57a02c2735c3e015f6c813085724284bf45fd71b
fix lib/topic-filter/sorts.js for es5
lib/topic-filter/sorts.js
lib/topic-filter/sorts.js
module.exports = { 'closing-soon': { name: 'closing-soon', label: 'sorts.closing-soon', sort: function (a, b) { if (!a.closingAt && !b.closingAt) { // If closingAt isn't defined in both, they're equal return 0; } // undefined closingAt always goes last // b goes first in this case if (!a.closingAt) { return 1; } // undefined closingAt always goes last // a goes first in this case if (!b.closingAt) { return -1; } // Closest date first return new Date(a.closingAt) - new Date(b.closingAt); } }, 'newest-first': { name: 'newest-first', label: 'sorts.newest-first', sort: function (a, b) { // Newest dates first return new Date(b.publishedAt) - new Date(a.publishedAt); } }, 'oldest-first': { name: 'oldest-first', label: 'sorts.oldest-first', sort: function (a, b) { // Oldest dates first return new Date(a.publishedAt) - new Date(b.publishedAt); } }, 'recently-updated': { name: 'recently-updated', label: 'sorts.recently-updated', sort: function (a, b) { // Newest dates first return new Date(b.updatedAt) - new Date(a.updatedAt); } } };
export default { 'closing-soon': { name: 'closing-soon', label: 'sorts.closing-soon', sort: function (a, b) { if (!a.closingAt && !b.closingAt) { // If closingAt isn't defined in both, they're equal return 0; } // undefined closingAt always goes last // b goes first in this case if (!a.closingAt) { return 1; } // undefined closingAt always goes last // a goes first in this case if (!b.closingAt) { return -1; } // Closest date first return new Date(a.closingAt) - new Date(b.closingAt); } }, 'newest-first': { name: 'newest-first', label: 'sorts.newest-first', sort: function (a, b) { // Newest dates first return new Date(b.publishedAt) - new Date(a.publishedAt); } }, 'oldest-first': { name: 'oldest-first', label: 'sorts.oldest-first', sort: function (a, b) { // Oldest dates first return new Date(a.publishedAt) - new Date(b.publishedAt); } }, 'recently-updated': { name: 'recently-updated', label: 'sorts.recently-updated', sort: function (a, b) { // Newest dates first return new Date(b.updatedAt) - new Date(a.updatedAt); } } };
JavaScript
0.000002
11df970342d2e3c05ab9f234ea39265e80f72139
Update tr_TR.js
lib/translations/tr_TR.js
lib/translations/tr_TR.js
// Turkish jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ], monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ], weekdaysFull: [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ], weekdaysShort: [ 'Pzr', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cmt' ], today: 'Bugün', clear: 'Sil', firstDay: 1, format: 'dd mmmm yyyy dddd', formatSubmit: 'yyyy/mm/dd' });
// Turkish jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ], monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ], weekdaysFull: [ 'Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi' ], weekdaysShort: [ 'Pzr', 'Pzt', 'Sal', 'Çrş', 'Prş', 'Cum', 'Cmt' ], today: 'bugün', clear: 'sil', firstDay: 1, format: 'dd mmmm yyyy dddd', formatSubmit: 'yyyy/mm/dd' });
JavaScript
0.000001
88043722b223b8fd1c9cb82bf55a484ba68d637b
increase port polling timeout (#638)
lib/utils/port-polling.js
lib/utils/port-polling.js
'use strict'; const net = require('net'); const errors = require('../errors'); module.exports = function portPolling(options) { options = Object.assign({ timeoutInMS: 2000, maxTries: 20, delayOnConnectInMS: 3 * 2000, logSuggestion: 'ghost log', socketTimeoutInMS: 1000 * 60 }, options || {}); if (!options.port) { return Promise.reject(new errors.CliError({ message: 'Port is required.' })); } const connectToGhostSocket = (() => { return new Promise((resolve, reject) => { const ghostSocket = net.connect(options.port); let delayOnConnectTimeout; // inactivity timeout ghostSocket.setTimeout(options.socketTimeoutInMS); ghostSocket.on('timeout', (() => { if (delayOnConnectTimeout) { clearTimeout(delayOnConnectTimeout); } ghostSocket.destroy(); // force retry const err = new Error(); err.retry = true; reject(err); })); ghostSocket.on('connect', (() => { if (options.delayOnConnectInMS) { let ghostDied = false; // CASE: client closes socket ghostSocket.on('close', (() => { ghostDied = true; })); delayOnConnectTimeout = setTimeout(() => { ghostSocket.destroy(); if (ghostDied) { reject(new Error('Ghost died.')); } else { resolve(); } }, options.delayOnConnectInMS); return; } ghostSocket.destroy(); resolve(); })); ghostSocket.on('error', ((err) => { ghostSocket.destroy(); err.retry = true; reject(err); })); }); }); const startPolling = (() => { return new Promise((resolve, reject) => { let tries = 0; (function retry() { connectToGhostSocket() .then(() => { resolve(); }) .catch((err) => { if (err.retry && tries < options.maxTries) { tries = tries + 1; setTimeout(retry, options.timeoutInMS); return; } reject(new errors.GhostError({ message: 'Ghost did not start.', suggestion: options.logSuggestion, err: err })); }); }()); }); }); return startPolling(); };
'use strict'; const net = require('net'); const errors = require('../errors'); module.exports = function portPolling(options) { options = Object.assign({ timeoutInMS: 1000, maxTries: 20, delayOnConnectInMS: 3 * 1000, logSuggestion: 'ghost log', socketTimeoutInMS: 1000 * 30 }, options || {}); if (!options.port) { return Promise.reject(new errors.CliError({ message: 'Port is required.' })); } const connectToGhostSocket = (() => { return new Promise((resolve, reject) => { const ghostSocket = net.connect(options.port); let delayOnConnectTimeout; // inactivity timeout ghostSocket.setTimeout(options.socketTimeoutInMS); ghostSocket.on('timeout', (() => { if (delayOnConnectTimeout) { clearTimeout(delayOnConnectTimeout); } ghostSocket.destroy(); // force retry const err = new Error(); err.retry = true; reject(err); })); ghostSocket.on('connect', (() => { if (options.delayOnConnectInMS) { let ghostDied = false; // CASE: client closes socket ghostSocket.on('close', (() => { ghostDied = true; })); delayOnConnectTimeout = setTimeout(() => { ghostSocket.destroy(); if (ghostDied) { reject(new Error('Ghost died.')); } else { resolve(); } }, options.delayOnConnectInMS); return; } ghostSocket.destroy(); resolve(); })); ghostSocket.on('error', ((err) => { ghostSocket.destroy(); err.retry = true; reject(err); })); }); }); const startPolling = (() => { return new Promise((resolve, reject) => { let tries = 0; (function retry() { connectToGhostSocket() .then(() => { resolve(); }) .catch((err) => { if (err.retry && tries < options.maxTries) { tries = tries + 1; setTimeout(retry, options.timeoutInMS); return; } reject(new errors.GhostError({ message: 'Ghost did not start.', suggestion: options.logSuggestion, err: err })); }); }()); }); }); return startPolling(); };
JavaScript
0
9668ea0efae86ab6426b0edffa4890a35fd65c7e
update config file
config/config.js
config/config.js
var path = require('path'), rootPath = path.normalize(__dirname + '/..'); module.exports = function (app) { app.site = { name : "{{name}}", // the name of you app } app.config = { port : 3000, // port to run the server on prettify : { html : true, // whether to pretify html }, engines : { html: "{{html}}", // options: [jade|ejs|haml|hjs|jshtml] css: "{{css}}", // options: [stylus|sass|less] }, root : rootPath, db : { url : "mongodb://localhost/db-name" // url to database }, jsonp : true, // allow jsonp requests secret : 'MYAPPSECRET', protocol : 'http://', autoLoad : false, // whether to autoload controllers & models } // some default meta setting for head app.site.meta = { description : '', keywords : '', viewport : 'width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0', encoding : "utf-8" } }
var path = require('path'), rootPath = path.normalize(__dirname + '/..'); module.exports = function (app) { app.site = { name : "{{name}}", // the name of you app } app.config = { port : 3000, // port to run the server on prettify : { html : true, // whether to pretify html }, engines : { html: "{{html}}", // jade, ejs, haml, hjs (hogan) css: "{{css}}", // styles, sass, less }, root : rootPath, db : { url : "mongodb://localhost/db-name" // url to database }, jsonp : true, // allow jsonp requests secret : 'MYAPPSECRET', protocol : 'http://', autoLoad : false, // whether to autoload controllers & models } // some default meta setting for head app.site.meta = { description : '', keywords : '', viewport : 'width=device-width, user-scalable=yes, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0', encoding : "utf-8" } }
JavaScript
0.000001
4679901133f017feb3ec7d29faabd238681d833e
clean up
config/config.js
config/config.js
module.exports = { development: { db: 'mongodb://localhost/wo', app: { name: 'WO Portal' }, smtp: '', //smtp server used for pass reset/newsletter recap_pbk: '', //recaptcha public key recap_prk: '', //recaptcha private key oauth: { tokenLife: 3600 } } };
module.exports = { development: { db: 'mongodb://localhost/wo', app: { name: 'WO Portal' }, smtp: 'smtp.ecs.soton.ac.uk', //smtp server used for pass reset/newsletter recap_pbk: '6LfwcOoSAAAAACeZnHuWzlnOCbLW7AONYM2X9K-H', //recaptcha public key recap_prk: '6LfwcOoSAAAAAGFI7h_SJoCBwUkvpDRf7_r8ZA_D', //recaptcha private key facebook: { clientID: "", //clientID clientSecret: "", //clientSecret callbackURL: "" //http://localhost:3000/auth/facebook/callback }, oauth: { tokenLife: 3600 } } };
JavaScript
0.000001
c7ac33659bc02b1229b188d8296e44e399cfa85a
Fix vote import
cli/_lib/votes.js
cli/_lib/votes.js
// Import forum votes // 'use strict'; const Promise = require('bluebird'); const co = require('co'); const mongoose = require('mongoose'); const progress = require('./utils').progress; const POST = 1; // content type for posts module.exports = co.wrap(function* (N) { // // Establish MySQL connection // let conn = yield N.vbconvert.getConnection(); // // Fetch all users // let users = {}; (yield N.models.users.User.find().lean(true)).forEach(user => { users[user.hid] = user; }); let rows = yield conn.query('SELECT count(*) AS count FROM votes'); let bar = progress(' votes :current/:total [:bar] :percent', rows[0].count); let userids = yield conn.query(` SELECT fromuserid FROM votes GROUP BY fromuserid ORDER BY fromuserid ASC `); yield Promise.map(userids, co.wrap(function* (userid_row) { let fromuserid = userid_row.fromuserid; // ignore votes casted by deleted users if (!users[fromuserid]) return; let rows = yield conn.query(` SELECT targetid,vote,fromuserid,touserid,date FROM votes WHERE fromuserid = ? AND contenttypeid = ? `, [ fromuserid, POST ]); let bulk = N.models.users.Vote.collection.initializeUnorderedBulkOp(); let count = 0; for (let i = 0; i < rows.length; i++) { let row = rows[i]; bar.tick(); // ignore votes casted for deleted users if (!users[row.touserid]) continue; let post_mapping = yield N.models.vbconvert.PostMapping.findOne({ mysql_id: row.targetid }).lean(true); // voted for non-existent or not imported post if (!post_mapping) continue; count++; bulk.find({ from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST }).upsert().update({ $setOnInsert: { _id: new mongoose.Types.ObjectId(row.date), from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST, hb: users[row.fromuserid].hb, value: Number(row.vote) } }); } if (!count) return; yield new Promise((resolve, reject) => { bulk.execute(err => err ? reject(err) : resolve()); }); }), { concurrency: 100 }); bar.terminate(); conn.release(); N.logger.info('Vote import finished'); });
// Import forum votes // 'use strict'; const Promise = require('bluebird'); const co = require('co'); const mongoose = require('mongoose'); const progress = require('./utils').progress; const POST = 1; // content type for posts module.exports = co.wrap(function* (N) { // // Establish MySQL connection // let conn = yield N.vbconvert.getConnection(); // // Fetch all users // let users = {}; (yield N.models.users.User.find().lean(true)).forEach(user => { users[user.hid] = user; }); let rows = yield conn.query('SELECT count(*) AS count FROM votes'); let bar = progress(' votes :current/:total [:bar] :percent', rows[0].count); let userids = yield conn.query(` SELECT fromuserid FROM votes GROUP BY fromuserid ORDER BY fromuserid ASC `); yield Promise.map(userids, co.wrap(function* (row) { // ignore votes casted by deleted users if (!users[row.fromuserid]) return; let rows = yield conn.query(` SELECT targetid,vote,fromuserid,touserid,date FROM votes WHERE fromuserid = ? AND contenttypeid = ? `, [ row.fromuserid, POST ]); let bulk = N.models.users.Vote.collection.initializeUnorderedBulkOp(); let count = 0; for (var i = 0; i < rows; i++) { bar.tick(); // ignore votes casted for deleted users if (!users[row.touserid]) continue; let post_mapping = yield N.models.vbconvert.PostMapping.findOne({ mysql_id: row.targetid }).lean(true); count++; bulk.find({ from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST }).upsert().update({ $setOnInsert: { _id: new mongoose.Types.ObjectId(row.date), from: users[row.fromuserid]._id, to: users[row.touserid]._id, 'for': post_mapping.post_id, type: N.models.users.Vote.types.FORUM_POST, hb: users[row.fromuserid].hb, value: Number(row.vote) } }); } if (!count) return; yield new Promise((resolve, reject) => { bulk.execute(err => err ? reject(err) : resolve()); }); }), { concurrency: 100 }); bar.terminate(); conn.release(); N.logger.info('Vote import finished'); });
JavaScript
0.000001
1bd50fab517a8644973f20fbe0a007b0497a3416
Add some comments to index.
lib/Index.js
lib/Index.js
var runCallback = require('./common.js').runCallback; var crypto = require('crypto'); /** * XXX THIS CLASS IS NOT READY. DO NOT USE. * Todo: figure out how to clean up when an indexed field changes value. (I.e. delete the old entry.) * Todo: implement purge * Note: this adds a private property for original index value in _indexValues * Note: Index value removal is done asynchronously because its result doesn't matter (much). */ function Index(obj, field) { /* Back up functions we're wrapping */ var save = obj.prototype.save; var fromObject = obj.prototype.fromObject; var del = obj.prototype.delete; /* A local value to store the existing value of the indexed field. */ var indexValue; /* The name of the getter we're adding */ var getter = "getBy" + field.substr(0, 1).toUpperCase() + field.substr(1); /** * Key the key at which the index for the field and value will be stored. */ function getKey(value) { var hash = crypto.createHash('sha256'); hash.update(value || indexValue); var bucket = hash.digest('hex').substr(0, 8); return obj.getKey("ix:" + field + ":" + bucket); } /** * Wrap the save function with a function that adds to the index. */ obj.prototype.save = function(callback) { var self = this; save.call(self, function(err, result) { if (err) return runCallback(callback, err, result); /* Try to remove the old index. Failure is non-fatal. */ if (indexValue && indexValue != self[field]) { obj.client.srem(getKey(), self.id); } indexValue = self[field]; /* Track the new value */ obj.client.sadd(getKey(), self.id, function(err, result) { if (err) return runCallback(callback, err, result); runCallback(callback, err, true); }); }); }; obj.prototype.fromObject = function(src) { indexValue = (typeof(src[field]) !== undefined) ? src[field] : undefined; fromObject.call(this, src); }; obj.prototype.delete = function(callback) { /* Remove the index key. Failure is non-fatal. */ obj.client.srem(getKey(), this.id); del.call(this, callback); }; /**/ obj[getter] = function(value, callback) { obj.client.smembers(getKey(value), function(err, result) { if (err) return runCallback(callback, err, result); if (!result.length) return runCallback(callback, err, result); obj.get(result, function(err, result) { var instances = []; for (var i = 0; i < result.length; i++) { if (!result[i]) continue; /* No longer exists. */ if (result[i][field] == value) { instances.push(result[i]); } } runCallback(callback, err, instances); }); }); } } module.exports = Index;
var runCallback = require('./common.js').runCallback; var crypto = require('crypto'); /** * XXX THIS CLASS IS NOT READY. DO NOT USE. * Todo: figure out how to clean up when an indexed field changes value. (I.e. delete the old entry.) * Todo: implement purge * Note: this adds a private property for original index value in _indexValues * Note: Index value removal is done asynchronously because its result doesn't matter (much). */ function Index(obj, field) { var save = obj.prototype.save; var fromObject = obj.prototype.fromObject; var del = obj.prototype.delete; var indexValue; var getter = "getBy" + field.substr(0, 1).toUpperCase() + field.substr(1); /** * Key the key at which the index for the field and value will be stored. */ function getKey(value) { var hash = crypto.createHash('sha256'); hash.update(value || indexValue); var bucket = hash.digest('hex').substr(0, 8); return obj.getKey("ix:" + field + ":" + bucket); } /** * Wrap the save function with a function that adds to the index. */ obj.prototype.save = function(callback) { var self = this; save.call(self, function(err, result) { if (err) return runCallback(callback, err, result); /* Try to remove the old index. Failure is non-fatal. */ if (indexValue && indexValue != self[field]) { obj.client.srem(getKey(), self.id); } indexValue = self[field]; /* Track the new value */ obj.client.sadd(getKey(), self.id, function(err, result) { if (err) return runCallback(callback, err, result); runCallback(callback, err, true); }); }); }; obj.prototype.fromObject = function(src) { indexValue = (typeof(src[field]) !== undefined) ? src[field] : undefined; fromObject.call(this, src); }; obj.prototype.delete = function(callback) { /* Remove the index key. Failure is non-fatal. */ obj.client.srem(getKey(), this.id); del.call(this, callback); }; /**/ obj[getter] = function(value, callback) { obj.client.smembers(getKey(value), function(err, result) { if (err) return runCallback(callback, err, result); if (!result.length) return runCallback(callback, err, result); obj.get(result, function(err, result) { var instances = []; for (var i = 0; i < result.length; i++) { if (!result[i]) continue; /* No longer exists. */ if (result[i][field] == value) { instances.push(result[i]); } } runCallback(callback, err, instances); }); }); } } module.exports = Index;
JavaScript
0
4383067a6f6b34f768340725b9d37ea240b4bc1a
make check show originalGameId
cli/cmds/check.js
cli/cmds/check.js
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var gameInfo = require('../../lib/gameinfo'); var path = require('path'); var Promise = require('promise'); var check = function(args) { return new Promise(function(resolve, reject) { try { var runtimeInfo = gameInfo.readGameInfo(process.cwd()); } catch (e) { console.error(e); reject(); return; } console.log("name : " + runtimeInfo.info.name); console.log("gameId : " + runtimeInfo.originalGameId); console.log("runtimeId : " + runtimeInfo.info.happyFunTimes.gameId); console.log("type : " + runtimeInfo.info.happyFunTimes.gameType); console.log("version : " + runtimeInfo.info.version); console.log("api version: " + runtimeInfo.info.happyFunTimes.apiVersion); console.log(""); console.log("looks ok"); resolve(); }); }; exports.usage = { prepend: "check's the game in the current folder some requirements", options: [ ] }; exports.cmd = check;
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var gameInfo = require('../../lib/gameinfo'); var path = require('path'); var Promise = require('promise'); var check = function(args) { return new Promise(function(resolve, reject) { try { var runtimeInfo = gameInfo.readGameInfo(process.cwd()); } catch (e) { console.error(e); reject(); return; } console.log("name : " + runtimeInfo.info.name); console.log("gameId : " + runtimeInfo.info.happyFunTimes.gameId); console.log("type : " + runtimeInfo.info.happyFunTimes.gameType); console.log("version : " + runtimeInfo.info.version); console.log("api version: " + runtimeInfo.info.happyFunTimes.apiVersion); console.log(""); console.log("looks ok"); resolve(); }); }; exports.usage = { prepend: "check's the game in the current folder some requirements", options: [ ] }; exports.cmd = check;
JavaScript
0
0c33f054ffb968c9f3fc81d4d74fe1050c2ac5ab
Improve comment
lib/Space.js
lib/Space.js
// // Space. The root item. // var Path = require('./geom/Path') var Vector = require('./geom/Vector') var IPath = require('./geom/IPath') var AbstractPlane = require('./AbstractPlane') var extend = require('extend') var Space = function () { AbstractPlane.call(this) // Space has constant identity transformation _T } var p = extend({}, AbstractPlane.prototype) Space.prototype = p p.atMid = function () { // Get a Vector to the centroid of the bounding convex hull. // Rather computationally intensive. return this.getHull().atMid() } p.setParent = function () { // Remove possibility to add to parent. throw new Error('Space cannot have a parent.') } p.remove = function () { // Silent, already removed. Otherwise would throw the error in setParent } p.getHull = function () { // Get bounding box as an IPath. Equals the convex hull // of the children. Iterates over all children AbstractNodes so keep // an eye on efficiency. // // Return // IPath // If no children, returns a path with single point at origin. // var children = this.getChildren() if (children.length < 1) { return new IPath(new Path([new Vector(0, 0)]), this) } var ip = children.reduce(function (acc, child) { return acc.add(child.getHull()) }, new IPath()) return ip.getHull() } module.exports = Space
// // Space. The root item. // var Path = require('./geom/Path') var Vector = require('./geom/Vector') var IPath = require('./geom/IPath') var AbstractPlane = require('./AbstractPlane') var extend = require('extend') var Space = function () { AbstractPlane.call(this) // Space has constant identity transformation _T } var p = extend({}, AbstractPlane.prototype) Space.prototype = p p.atMid = function () { // Get a Vector to the centroid of the bounding convex hull. // Rather computationally intensive. return this.getHull().atMid() } p.setParent = function () { // Remove possibility to add to parent. throw new Error('Space cannot have a parent.') } p.remove = function () { // Silent, already removed. Otherwise would throw the error in setParent } p.getHull = function () { // Get bounding box as an IPath. Equals the convex hull // of the children. Iterates over all children AbstractNodes so keep an eye on // efficiency. // // Return // IPath // If no children, returns a path with single point at origin. // var children = this.getChildren() if (children.length < 1) { return new IPath(new Path([new Vector(0, 0)]), this) } var ip = children.reduce(function (acc, child) { return acc.add(child.getHull()) }, new IPath()) return ip.getHull() } module.exports = Space
JavaScript
0
ff2aa48b8d221080ae9901f94622e5dbc32807e9
Implement billy.build
lib/billy.js
lib/billy.js
var combine = require('./jsCombine'), fs = require('fs'), templateUtil = require('./templateUtil'); function loadConfig(path) { return JSON.parse(fs.readFileSync(path, 'utf8')); } function explodeViews(module, config) { var views = config.views, loadedTemplates = {}, ret = []; for (var i = 0, len = module.length; i < len; i++) { var resource = module[i]; ret.push(resource); if (views[resource]) { views[resource].forEach(function(template) { var generator = function(callback) { templateUtil.loadTemplate(template, config.templateCache, callback); }; generator.sourceFile = template; ret.push(generator); }); } } return ret; } exports.init = function(configFile, outdir) { var config = loadConfig(configFile), moduleList = []; for (var name in config.modules) { moduleList.push(name); } return { build: function(moduleName, callback) { var modules = moduleName ? [moduleName] : moduleList; modules.forEach(function(name) { var resources = explodeViews(config.modules[name], config), moduleName = outdir + '/' + name + '.js'; combine.combine(resources, moduleName, callback); }); }, watch: function(moduleName, callback) { } }; };
var fs = require('fs'); function loadConfig(path) { return JSON.parse(fs.readFileSync(path, 'utf8')); } exports.init = function(configFile, outdir) { var config = loadConfig(configFile), moduleList = []; for (var name in config.modules) { moduleList.push(name); } return { build: function(moduleName, callback) { }, watch: function(moduleName, callback) { } }; };
JavaScript
0.000012
2bcfcb5b628fe3a602dffdecbedb58c8264664f5
Clean up delta labels
cd/src/pipeline-events-handler/deltas/deltas.js
cd/src/pipeline-events-handler/deltas/deltas.js
const getStackFamily = require('./stack-family'); const getChangeSetFamily = require('./change-set-family'); const deltaArrow = require('./delta-arrow'); const deltaValue = require('./delta-value'); /** * Returns a multi-line string describing the parameters that have changed * @param {ParameterDeltas} deltas * @returns {String} */ function parameterDeltasList(deltas) { if (!deltas.length) { return 'This change set contained no meaningful parameter deltas.'; } // Text blocks within attachments have a 3000 character limit. If the text is // too large, try creating the list without links to reduce the size. const withLinks = deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue); const arrow = deltaArrow(d); const newValue = deltaValue(d.parameter, d.changeSetValue); const label = d.stackName.includes('-root-') ? d.parameter : `${d.stackName}::${d.parameter}`; return `*${label}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); if (withLinks.length < 2900) { return withLinks; } else { return deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue, true); const arrow = deltaArrow(d, true); const newValue = deltaValue(d.parameter, d.changeSetValue, true); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); } } module.exports = { async nestedParameterDeltaText(stackName, changeSetName) { const stackFamily = await getStackFamily(stackName); const changeSetFamily = await getChangeSetFamily(stackName, changeSetName); /** @type {ParameterDeltas} */ const deltas = []; // Iterate through all existing stack parameters and create a delta for // each one, which includes the current value. for (const stack of stackFamily) { for (const param of stack.Parameters || []) { deltas.push({ stackName: stack.StackName, stackId: stack.StackId, parameter: param.ParameterKey, stackValue: param.ResolvedValue || param.ParameterValue, changeSetValue: null, }); } } // Iterate through all the change set parameters. If a delta already exists // for a given stack+parameter key, add the value from the change set to // that delta. If not, make a new delta. for (const changeSet of changeSetFamily) { for (const param of changeSet.Parameters || []) { const delta = deltas.find( (d) => param.ParameterKey === d.parameter && changeSet.StackName === d.stackName, ); if (delta) { delta.changeSetValue = param.ResolvedValue || param.ParameterValue; } else { deltas.push({ stackName: changeSet.StackName, stackId: changeSet.StackId, parameter: param.ParameterKey, stackValue: null, changeSetValue: param.ResolvedValue || param.ParameterValue, }); } } } // Filter down to only deltas where the values are different const changeDeltas = deltas.filter( (d) => d.stackValue !== d.changeSetValue, ); // When using nested change sets, not all parameters in nested stacks are // correctly resolved. Any parameter values that depend on a stack or // resource output will be included in the change set parameters with an // unresolved value that looks like "{{IntrinsicFunction:…". Unless or until // AWS makes nested change sets smarter, we have to just ignore these, // because there's no way to compare the actual existing value from the stack // to the hypothetical future value that will be resolved when the change set // executes. // // Any parameters effected by this limitation are filtered out. const cleanedDeltas = changeDeltas.filter( (d) => !(d.changeSetValue || '').match(/\{\{IntrinsicFunction\:/), ); const allowedDeltas = cleanedDeltas.filter( (d) => !['PipelineExecutionNonce', 'TemplateUrlBase'].includes(d.parameter), ); return parameterDeltasList(allowedDeltas); }, };
const getStackFamily = require('./stack-family'); const getChangeSetFamily = require('./change-set-family'); const deltaArrow = require('./delta-arrow'); const deltaValue = require('./delta-value'); /** * Returns a multi-line string describing the parameters that have changed * @param {ParameterDeltas} deltas * @returns {String} */ function parameterDeltasList(deltas) { if (!deltas.length) { return 'This change set contained no meaningful parameter deltas.'; } // Text blocks within attachments have a 3000 character limit. If the text is // too large, try creating the list without links to reduce the size. const withLinks = deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue); const arrow = deltaArrow(d); const newValue = deltaValue(d.parameter, d.changeSetValue); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); if (withLinks.length < 2900) { return withLinks; } else { return deltas .map((d) => { const oldValue = deltaValue(d.parameter, d.stackValue, true); const arrow = deltaArrow(d, true); const newValue = deltaValue(d.parameter, d.changeSetValue, true); return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`; }) .join('\n'); } } module.exports = { async nestedParameterDeltaText(stackName, changeSetName) { const stackFamily = await getStackFamily(stackName); const changeSetFamily = await getChangeSetFamily(stackName, changeSetName); /** @type {ParameterDeltas} */ const deltas = []; // Iterate through all existing stack parameters and create a delta for // each one, which includes the current value. for (const stack of stackFamily) { for (const param of stack.Parameters || []) { deltas.push({ stackName: stack.StackName, stackId: stack.StackId, parameter: param.ParameterKey, stackValue: param.ResolvedValue || param.ParameterValue, changeSetValue: null, }); } } // Iterate through all the change set parameters. If a delta already exists // for a given stack+parameter key, add the value from the change set to // that delta. If not, make a new delta. for (const changeSet of changeSetFamily) { for (const param of changeSet.Parameters || []) { const delta = deltas.find( (d) => param.ParameterKey === d.parameter && changeSet.StackName === d.stackName, ); if (delta) { delta.changeSetValue = param.ResolvedValue || param.ParameterValue; } else { deltas.push({ stackName: changeSet.StackName, stackId: changeSet.StackId, parameter: param.ParameterKey, stackValue: null, changeSetValue: param.ResolvedValue || param.ParameterValue, }); } } } // Filter down to only deltas where the values are different const changeDeltas = deltas.filter( (d) => d.stackValue !== d.changeSetValue, ); // When using nested change sets, not all parameters in nested stacks are // correctly resolved. Any parameter values that depend on a stack or // resource output will be included in the change set parameters with an // unresolved value that looks like "{{IntrinsicFunction:…". Unless or until // AWS makes nested change sets smarter, we have to just ignore these, // because there's no way to compare the actual existing value from the stack // to the hypothetical future value that will be resolved when the change set // executes. // // Any parameters effected by this limitation are filtered out. const cleanedDeltas = changeDeltas.filter( (d) => !(d.changeSetValue || '').match(/\{\{IntrinsicFunction\:/), ); const allowedDeltas = cleanedDeltas.filter( (d) => !['PipelineExecutionNonce', 'TemplateUrlBase'].includes(d.parameter), ); return parameterDeltasList(allowedDeltas); }, };
JavaScript
0.000003
3ccabac61d19a71d302542add314c1aa20489b02
Fix typo
lib/buddy.js
lib/buddy.js
var assert = require('assert'); var debug = require('debug')('alloc:buddy'); var util = require('util'); function log2(x) { return Math.log(x) / Math.LN2; } function power2(x) { return 1 << (log2(x - 1) + 1); } var BuddyAllocator = function(buffer, options) { if (typeof buffer == 'number') { buffer = new Buffer(power2(buffer)); } assert(buffer.length > 1 && !(buffer.length & (buffer.length - 1)), 'Buffer length must be a positive power of 2'); options = util._extend({minSize: 1}, options); this.buffer = buffer; this.minRank = log2(options.minSize) | 0; this.minSize = 1 << this.minRank; // Maintain fragmentation statistics. this.bytesTotal = this.buffer.length; this.bytesAllocated = 0; this.bytesWasted = 0; // Maintain a free list for each block size. this.freelist = []; for (var i = 0; i < log2(this.buffer.length) - this.minRank; i++) { this.freelist.push([]); } this.freelist.push([0]); }; BuddyAllocator.prototype.rank = function(x) { return Math.max(0, ((log2(x - 1) + 1) | 0) - this.minRank); }; BuddyAllocator.prototype.alloc = function(size) { // Find the first unallocated block of sufficient size. for (var i = this.rank(size); i < this.freelist.length; i++) { if (this.freelist[i].length) { var offset = this.freelist[i].pop(); var half; // Split the block recursively until it is just big enough. for (half = 1 << (i + this.minRank - 1); half >= size && i > 0; half >>= 1) { var buddy = offset + half; this.freelist[--i].push(buddy); debug('split @%d, buddy @%d', offset, buddy); } var wasted = (half << 1) - size; this.bytesAllocated += size; this.bytesWasted += wasted; debug('alloc @%d, used %d bytes, wasted %d bytes', offset, size, wasted); return this.buffer.slice(offset, offset + size); } } return null; }; BuddyAllocator.prototype.free = function(block) { // Find the offset within parent buffer. var offset = block.offset - this.buffer.offset; var rank = this.rank(block.length); var reclaimed = 1 << (rank + this.minRank); this.bytesAllocated -= block.length; this.bytesWasted -= reclaimed - block.length; debug('free @%d, reclaiming %d bytes', offset, reclaimed); // Merge recursively until we exhaust all unallocated buddies. for (var i = rank; i < this.freelist.length - 1; i++) { var buddy = offset ^ (1 << (i + this.minRank)); var merged = false; for (var j = 0; j < this.freelist[i].length; j++) { if (this.freelist[i][j] == buddy) { debug('merge @%d, buddy @%d', offset, buddy); merged = this.freelist[i].splice(j, 1); if (offset > buddy) { offset = buddy; } break; } } if (!merged) { break; } } this.freelist[i].push(offset); }; module.exports = BuddyAllocator;
var assert = require('assert'); var debug = require('debug')('alloc:buddy'); var util = require('util'); function log2(x) { return Math.log(x) / Math.LN2; } function power2(x) { return 1 << (log2(x - 1) + 1); } var BuddyAllocator = function(buffer, options) { if (typeof buffer == 'number') { buffer = new Buffer(power2(buffer)); } assert(buffer.length > 1 && !(buffer.length & (buffer.length - 1)), 'Buffer length must be a positive power of 2'); options = util._extend({minBuddySize: 1}, options); this.buffer = buffer; this.minRank = log2(options.minSize) | 0; this.minSize = 1 << this.minRank; // Maintain fragmentation statistics. this.bytesTotal = this.buffer.length; this.bytesAllocated = 0; this.bytesWasted = 0; // Maintain a free list for each block size. this.freelist = []; for (var i = 0; i < log2(this.buffer.length) - this.minRank; i++) { this.freelist.push([]); } this.freelist.push([0]); }; BuddyAllocator.prototype.rank = function(x) { return Math.max(0, ((log2(x - 1) + 1) | 0) - this.minRank); }; BuddyAllocator.prototype.alloc = function(size) { // Find the first unallocated block of sufficient size. for (var i = this.rank(size); i < this.freelist.length; i++) { if (this.freelist[i].length) { var offset = this.freelist[i].pop(); var half; // Split the block recursively until it is just big enough. for (half = 1 << (i + this.minRank - 1); half >= size && i > 0; half >>= 1) { var buddy = offset + half; this.freelist[--i].push(buddy); debug('split @%d, buddy @%d', offset, buddy); } var wasted = (half << 1) - size; this.bytesAllocated += size; this.bytesWasted += wasted; debug('alloc @%d, used %d bytes, wasted %d bytes', offset, size, wasted); return this.buffer.slice(offset, offset + size); } } return null; }; BuddyAllocator.prototype.free = function(block) { // Find the offset within parent buffer. var offset = block.offset - this.buffer.offset; var rank = this.rank(block.length); var reclaimed = 1 << (rank + this.minRank); this.bytesAllocated -= block.length; this.bytesWasted -= reclaimed - block.length; debug('free @%d, reclaiming %d bytes', offset, reclaimed); // Merge recursively until we exhaust all unallocated buddies. for (var i = rank; i < this.freelist.length - 1; i++) { var buddy = offset ^ (1 << (i + this.minRank)); var merged = false; for (var j = 0; j < this.freelist[i].length; j++) { if (this.freelist[i][j] == buddy) { debug('merge @%d, buddy @%d', offset, buddy); merged = this.freelist[i].splice(j, 1); if (offset > buddy) { offset = buddy; } break; } } if (!merged) { break; } } this.freelist[i].push(offset); }; module.exports = BuddyAllocator;
JavaScript
0.999999
7f5735f30e133c937cad495bbf527ca4d305d777
return promise rejection in build.js
lib/build.js
lib/build.js
var mkdirp = require('mkdirp') var Promise = require('es6-promise').Promise var fs = require('fs') var path = require('path') function writeFile (page) { return new Promise(function (resolve, reject) { var dir = path.dirname(page.dest) mkdirp(dir, function (err) { if (err) { return reject(err) } fs.writeFile(page.dest, page.contents, function (err) { if (err) { return reject(err) } return resolve(page.dest) }) }) }) } function build (pages) { var builtPages = pages.map(writeFile) return Promise.all(builtPages) } module.exports = build
var mkdirp = require('mkdirp') var Promise = require('es6-promise').Promise var fs = require('fs') var path = require('path') function writeFile (page) { return new Promise(function (resolve, reject) { var dir = path.dirname(page.dest) mkdirp(dir, function (err) { if (err) { return reject(err) } fs.writeFile(page.dest, page.contents, function (err) { if (err) { reject(err) } return resolve(page.dest) }) }) }) } function build (pages) { var builtPages = pages.map(writeFile) return Promise.all(builtPages) } module.exports = build
JavaScript
0.000001
a850c39f00d3d942c657dac9483139940bdeca9d
converted to entities
js/fireworks-2d.js
js/fireworks-2d.js
'use strict'; function draw_logic(){ for(var entity in core_entities){ canvas_buffer.fillStyle = core_entities[entity]['color']; canvas_buffer.fillRect( core_entities[entity]['x'], core_entities[entity]['y'], core_entities[entity]['width'], core_entities[entity]['height'] ); } } function launch(firework){ var firework = firework || {}; firework['children'] = firework['children'] !== void 0 ? firework['children'] : 10; firework['color'] = firework['color'] || '#' + core_random_hex(); firework['dx'] = firework['dx'] || Math.random() * 4 - 2; firework['dy'] = firework['dy'] || -Math.random() * 2 - canvas_height / 200; firework['height'] = firework['height'] || 4; firework['timer'] = firework['timer'] || core_random_integer({ 'max': 200, }) + 100; firework['width'] = firework['width'] || 4; firework['x'] = firework['x'] || core_mouse['x']; firework['y'] = firework['y'] || canvas_height; core_entity_create({ 'properties': firework, }); } function logic(){ if(core_mouse['down']){ launch(); } for(var entity in core_entities){ core_entities[entity]['x'] += core_entities[entity]['dx']; core_entities[entity]['y'] += core_entities[entity]['dy']; core_entities[entity]['dy'] += .02; core_entities[entity]['dx'] *= .99; core_entities[entity]['timer'] -= 1; if(core_entities[entity]['timer'] <= 0){ if(core_entities[entity]['children'] > 0){ var loop_counter = core_entities[entity]['children'] - 1; do{ launch({ 'children': 0, 'dx': Math.random() * 3 - 1.5, 'dy': Math.random() * 3 - 1.5, 'x': core_entities[entity]['x'], 'timer': core_random_integer({ 'max': 90, }) + 40, 'y': core_entities[entity]['y'], }); }while(loop_counter--); } core_entity_remove({ 'entities': [ entity, ], }); } } } function repo_init(){ core_repo_init({ 'keybinds': { 'all': { 'todo': function(){ launch(); }, }, }, 'title': 'Fireworks-2D.htm', }); canvas_init(); }
'use strict'; function draw_logic(){ for(var firework in fireworks){ canvas_buffer.fillStyle = fireworks[firework]['color']; canvas_buffer.fillRect( fireworks[firework]['x'], fireworks[firework]['y'], fireworks[firework]['width'], fireworks[firework]['height'] ); } } function launch(firework){ var firework = firework || {}; firework['children'] = firework['children'] !== void 0 ? firework['children'] : 10; firework['color'] = firework['color'] || '#' + core_random_hex(); firework['dx'] = firework['dx'] || Math.random() * 4 - 2; firework['dy'] = firework['dy'] || -Math.random() * 2 - canvas_height / 200; firework['height'] = firework['height'] || 4; firework['timer'] = firework['timer'] || core_random_integer({ 'max': 200, }) + 100; firework['width'] = firework['width'] || 4; firework['x'] = firework['x'] || core_mouse['x']; firework['y'] = firework['y'] || canvas_height; fireworks.push(firework); } function logic(){ if(core_mouse['down']){ launch(); } for(var firework in fireworks){ fireworks[firework]['x'] += fireworks[firework]['dx']; fireworks[firework]['y'] += fireworks[firework]['dy']; fireworks[firework]['dy'] += .02; fireworks[firework]['dx'] *= .99; fireworks[firework]['timer'] -= 1; if(fireworks[firework]['timer'] <= 0){ if(fireworks[firework]['children'] > 0){ var loop_counter = fireworks[firework]['children'] - 1; do{ launch({ 'children': 0, 'dx': Math.random() * 3 - 1.5, 'dy': Math.random() * 3 - 1.5, 'x': fireworks[firework]['x'], 'timer': core_random_integer({ 'max': 90, }) + 40, 'y': fireworks[firework]['y'], }); }while(loop_counter--); } fireworks.splice( firework, 1 ); } } } function repo_init(){ core_repo_init({ 'keybinds': { 'all': { 'todo': launch, }, }, 'title': 'Fireworks-2D.htm', }); canvas_init(); } var fireworks = [];
JavaScript
0.999999
b4f6b28b70f0806650576e9ab03b61c297ae66ce
fix email links
lib/email.js
lib/email.js
var url = require('url'); var path = require('path'); var _ = require('underscore'); var nodemailer = require('nodemailer'); var swig = require('swig'); module.exports = function(app) { var config = app.loadConfig('email'); return { sendWelcome: function(user) { sendMessage(config.templates.signup, user); }, resendVerification: function(user) { sendMessage(config.templates.resend, user); }, sendForgot: function(user) { sendMessage(config.templates.forgot, user); } } function createTransport() { var cfg = config.mailer; // console.log("Creating mailer with transport:" + cfg.transport); // console.log(cfg); return nodemailer.createTransport(cfg.transport, cfg.config); } function sendMessage(template, user) { var appurl = app.getExternalUrl(); var emailVars = _.defaults(config.templateVars || {}, { 'appurl': appurl }); // XXX should use route resolution fns if (user.local.signupToken) { emailVars.signupLink = appurl + "/verification/" + user.local.signupToken; } if (user.local.resetToken) { emailVars.resetLink = appurl + "/forgot/" + user.local.resetToken; } var msgSubject = swig.render(template.subject, {locals:emailVars}); var msgBody = swig.renderFile(template.templatePath, emailVars); var transport = createTransport(); var message = { generateTextFromHTML: true, from: config.from, to: user.local.email, subject: msgSubject, html: msgBody } // console.log(message); // XXX what to do with error callbacks here? // these are operational issues that should be logged so alerts can be triggered transport.sendMail(message, function(error, response) { if (error) { console.log("Error sending mail!") console.log(error); } else { console.log("Message sent: " + response.message); console.log(JSON.stringify(response)); } transport.close(); // shut down the connection pool, no more messages }); } };
var url = require('url'); var path = require('path'); var _ = require('underscore'); var nodemailer = require('nodemailer'); var swig = require('swig'); module.exports = function(app) { var config = app.loadConfig('email'); return { sendWelcome: function(user) { sendMessage(config.templates.signup, user); }, resendVerification: function(user) { sendMessage(config.templates.resend, user); }, sendForgot: function(user) { sendMessage(config.templates.forgot, user); } } function createTransport() { var cfg = config.mailer; // console.log("Creating mailer with transport:" + cfg.transport); // console.log(cfg); return nodemailer.createTransport(cfg.transport, cfg.config); } function sendMessage(template, user) { var appurl = app.getExternalUrl(); var emailVars = _.defaults(config.templateVars || {}, { 'appurl': appurl }); // XXX should use route resolution fns if (user.local.signupToken) { emailVars.signupLink = path.join(appurl, "verification", user.local.signupToken); } if (user.local.resetToken) { emailVars.resetLink = path.join(appurl, "forgot", user.local.resetToken); } var msgSubject = swig.render(template.subject, {locals:emailVars}); var msgBody = swig.renderFile(template.templatePath, emailVars); var transport = createTransport(); var message = { generateTextFromHTML: true, from: config.from, to: user.local.email, subject: msgSubject, html: msgBody } // console.log(message); // XXX what to do with error callbacks here? // these are operational issues that should be logged so alerts can be triggered transport.sendMail(message, function(error, response) { if (error) { console.log("Error sending mail!") console.log(error); } else { console.log("Message sent: " + response.message); console.log(JSON.stringify(response)); } transport.close(); // shut down the connection pool, no more messages }); } };
JavaScript
0.000003
fa364759f24249ff54dd73295a3b763e9acc92e8
rename callback to iteratee (consistent with underscorejs)
baseview.js
baseview.js
(function(root, factory) { // Set up BaseView appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'backbone', 'exports'], function(_, $, Backbone, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.BaseView = factory(root, exports, _, $, Backbone); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $ = require('jquery'), Backbone = require('backbone'); factory(root, exports, _, $, Backbone); // Finally, as a browser global. } else { root.BaseView = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone); } }(this, function(root, BaseView, _, $, Backbone) { var BaseView = Backbone.View.extend({ constructor: function(options) { options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this.children = options.children || {}; this.collections = options.collections || {}; this.models = options.models || {}; this.setTemplate(this.template || ''); Backbone.View.apply(this, arguments); }, _ensureElement: function() { var el = this.el, mid = _.result(this, 'mid'), attributes = {}; Backbone.View.prototype._ensureElement.apply(this, arguments); if (el) { return; } attributes['data-cid'] = this.cid; if (mid) { attributes['data-mid'] = mid; this.$el.addClass(this.toClassName(mid)); } this.$el.attr(attributes); }, toClassName: function(className) { return className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g, '').join('-').replace(/[\/\_]/g, '-').toLowerCase(); }, remove: function() { Backbone.View.prototype.remove.apply(this, arguments); this.invoke('remove'); }, compileTemplate: function(str) { return _.template(str) }, renderTemplate: function() { var interpolated = this.ctemplate.apply(null, arguments); this.trigger('render:template', this, interpolated, arguments); return interpolated; }, renderTemplateDefer: function() { _.defer.apply(null, [this.renderTemplate.bind(this)].concat(Array.prototype.slice.call(arguments))); }, renderTemplateDebounce: function() { if (!this._renderTemplateDebounce) { this._renderTemplateDebounce = _.debounce(this.renderTemplate.bind(this)); } this._renderTemplateDebounce.apply(this, arguments); }, setTemplate: function(template) { this.ctemplate = this.compileTemplate(template); this.template = template; }, traverse: function(iteratee, options) { options || (options = {}); var view = options.view || this; view.each(function(child) { iteratee.call(this, view, child); this.traverse(iteratee, {view: child}); }, this); } }); var array = []; var slice = array.slice; //List of view options to be merged as properties. var viewOptions = ['template', 'mid']; var childMethods = ['each', 'where', 'findWhere', 'invoke', 'pluck', 'size', 'keys', 'values', 'pairs', 'pick', 'omit', 'defaults', 'clone', 'tap', 'has', 'propertyOf', 'isEmpty']; _.each(childMethods, function(method) { if (!_[method]) { return; } BaseView.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.children); return _[method].apply(_, args); }; }); return BaseView; }));
(function(root, factory) { // Set up BaseView appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'backbone', 'exports'], function(_, $, Backbone, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.BaseView = factory(root, exports, _, $, Backbone); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $ = require('jquery'), Backbone = require('backbone'); factory(root, exports, _, $, Backbone); // Finally, as a browser global. } else { root.BaseView = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone); } }(this, function(root, BaseView, _, $, Backbone) { var BaseView = Backbone.View.extend({ constructor: function(options) { options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this.children = options.children || {}; this.collections = options.collections || {}; this.models = options.models || {}; this.setTemplate(this.template || ''); Backbone.View.apply(this, arguments); }, _ensureElement: function() { var el = this.el, mid = _.result(this, 'mid'), attributes = {}; Backbone.View.prototype._ensureElement.apply(this, arguments); if (el) { return; } attributes['data-cid'] = this.cid; if (mid) { attributes['data-mid'] = mid; this.$el.addClass(this.toClassName(mid)); } this.$el.attr(attributes); }, toClassName: function(className) { return className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g, '').join('-').replace(/[\/\_]/g, '-').toLowerCase(); }, remove: function() { Backbone.View.prototype.remove.apply(this, arguments); this.invoke('remove'); }, compileTemplate: function(str) { return _.template(str) }, renderTemplate: function() { var interpolated = this.ctemplate.apply(null, arguments); this.trigger('render:template', this, interpolated, arguments); return interpolated; }, renderTemplateDefer: function() { _.defer.apply(null, [this.renderTemplate.bind(this)].concat(Array.prototype.slice.call(arguments))); }, renderTemplateDebounce: function() { if (!this._renderTemplateDebounce) { this._renderTemplateDebounce = _.debounce(this.renderTemplate.bind(this)); } this._renderTemplateDebounce.apply(this, arguments); }, setTemplate: function(template) { this.ctemplate = this.compileTemplate(template); this.template = template; }, traverse: function(callback, options) { options || (options = {}); var view = options.view || this; view.each(function(child) { callback.call(this, view, child); this.traverse(callback, {view: child}); }, this); } }); var array = []; var slice = array.slice; //List of view options to be merged as properties. var viewOptions = ['template', 'mid']; var childMethods = ['each', 'where', 'findWhere', 'invoke', 'pluck', 'size', 'keys', 'values', 'pairs', 'pick', 'omit', 'defaults', 'clone', 'tap', 'has', 'propertyOf', 'isEmpty']; _.each(childMethods, function(method) { if (!_[method]) { return; } BaseView.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.children); return _[method].apply(_, args); }; }); return BaseView; }));
JavaScript
0
4ceb812cc7d6f39b04c34ac4a831ca5d21bb20fd
Revert "Probably solves this issue #26"
lib/error.js
lib/error.js
/* * The MIT License * * Copyright 2014 Timo Behrmann, Guillaume Chauvet. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var assert = require('assert'); module.exports.handle = function (errors, req, res, options, next) { if(options.errorHandler) { if(typeof(options.errorHandler) === 'function') { return options.errorHandler(res, errors); } else { return res.send(new options.errorHandler(errors)); } } else { return res.send (400, { status: 'validation failed', errors: errors }); } };
/* * The MIT License * * Copyright 2014 Timo Behrmann, Guillaume Chauvet. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var assert = require('assert'); module.exports.handle = function (errors, req, res, options, next) { if(options.errorHandler && typeof(options.errorHandler) === 'function') { return res.send(new options.errorHandler(errors)); } else { return res.send (400, { status: 'validation failed', errors: errors }); } };
JavaScript
0
3cd43c2857fa09a72af72be4594734c77674101a
Update emailTransports when seeding
config/models.js
config/models.js
'use strict'; var _ = require("lodash"); var async = require("async"); /** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ connection: process.env.DB_ADAPTER || 'localDiskDb', migrate: 'alter', updateOrCreate: function(criteria, values, cb){ var self = this; // reference for use by callbacks // If no values were specified, use criteria if (!values) values = criteria.where ? criteria.where : criteria; this.findOne(criteria, function (err, result){ if(err) return cb(err, false); if(result){ self.update(criteria, values, cb); }else{ self.create(values, cb); } }); }, /** * This method adds records to the database * * To use add a variable 'seedData' in your model and call the * method in the bootstrap.js file */ seed: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); if (!self.seedData) { sails.log.debug('No data avaliable to seed ' + modelName); callback(); return; } self.count().exec(function (err, count) { if(err) { sails.log.error("Failed to seed " + modelName, error); return callback(); } if(count === 0) { sails.log.debug('Seeding ' + modelName + '...'); if (self.seedData instanceof Array) { self.seedArray(callback); } else { self.seedObject(callback); } }else{ if(modelName === 'Emailtransport') { // Update records self.updateRecords(callback); }else{ sails.log.debug(modelName + ' had models, so no seed needed'); return callback(); } } }); }, updateRecords : function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.find({}).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { var data = []; self.seedData.forEach(function (seed) { data.push(_.merge(_.filter(results,function (item) { return item.name === seed.name })[0] || {},seed)) }) var fns = []; sails.log("!!!!!!!!!!!!!!!!!!!!!!!", data) data.forEach(function (item) { fns.push(function(cb){ self.update({ id :item.id },_.omit(item, ["id"])).exec(cb) }) }) async.series(fns,function (err,data) { if (err) { sails.log.debug(err); callback(); }else{ sails.log.debug(modelName + ' seeds updated', data); callback(); } }) } }); }, seedArray: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.createEach(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); }, seedObject: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.create(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); } };
'use strict'; /** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ connection: process.env.DB_ADAPTER || 'localDiskDb', migrate: 'alter', updateOrCreate: function(criteria, values, cb){ var self = this; // reference for use by callbacks // If no values were specified, use criteria if (!values) values = criteria.where ? criteria.where : criteria; this.findOne(criteria, function (err, result){ if(err) return cb(err, false); if(result){ self.update(criteria, values, cb); }else{ self.create(values, cb); } }); }, /** * This method adds records to the database * * To use add a variable 'seedData' in your model and call the * method in the bootstrap.js file */ seed: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); if (!self.seedData) { sails.log.debug('No data avaliable to seed ' + modelName); callback(); return; } self.count().exec(function (err, count) { if (!err && count === 0) { sails.log.debug('Seeding ' + modelName + '...'); if (self.seedData instanceof Array) { self.seedArray(callback); } else { self.seedObject(callback); } } else { sails.log.debug(modelName + ' had models, so no seed needed'); callback(); } }); }, seedArray: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.createEach(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); }, seedObject: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.create(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); } };
JavaScript
0
28cf0b946cde925c7ee09ed53243c277e6282955
Fix calendar popup
src/components/Transaction/Filter/Calendar.js
src/components/Transaction/Filter/Calendar.js
import React from 'react' import { Modal, Button } from 'semantic-ui-react' import DayPicker, { DateUtils } from 'react-day-picker' import 'react-day-picker/lib/style.css' const currentYear = new Date().getFullYear() const fromMonth = new Date(currentYear - 8, 0) const toMonth = new Date(currentYear + 2, 11) function YearMonthForm({ date, localeUtils, onChange }) { const months = localeUtils.getMonths() const years = [] for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) { years.push(i) } const handleChange = function handleChange(e) { const { year, month } = e.target.form onChange(new Date(year.value, month.value)) } return ( <form className="DayPicker-Caption"> <select name="month" onChange={handleChange} value={date.getMonth()}> {months.map((month, i) => ( <option key={i} value={i}> {month} </option> ))} </select> <select name="year" onChange={handleChange} value={date.getFullYear()}> {years.map((year, i) => ( <option key={i} value={year}> {year} </option> ))} </select> </form> ) } class Calendar extends React.Component { state = { month: null, from: null, to: null } handleDayClick = day => { const range = DateUtils.addDayToRange(day, this.state) this.setState(range) } handleYearMonthChange = month => { this.setState({ month }) } handleResetClick = () => { this.setState({ month: null, from: null, to: null }) } handleApplyClick = () => { const { from, to } = this.state this.props.changeFilterDate({ dateStart: from.setHours(0, 0, 0), dateEnd: (to && to.setHours(23, 59, 59)) || from.setHours(23, 59, 59) }) this.props.toggleFilterCalendar() } render() { const { month, from, to } = this.state return ( <Modal open={this.props.isCalendarOpen} onClose={this.props.toggleFilterCalendar} className="transactions-filter-modal" closeIcon size="small" > <Modal.Header>Show transactions in range</Modal.Header> <Modal.Content> <DayPicker className="Range" fixedWeeks enableOutsideDays numberOfMonths={this.props.isMobile ? 1 : 2} selectedDays={[from, { from, to }]} month={month} captionElement={ <YearMonthForm onChange={this.handleYearMonthChange} /> } onDayClick={this.handleDayClick} /> </Modal.Content> <Modal.Actions> <Button content="Reset" onClick={this.handleResetClick} /> <Button content="Apply" onClick={this.handleApplyClick} positive disabled={this.state.from === null && this.state.to === null} /> </Modal.Actions> </Modal> ) } } export default Calendar
import React from 'react' import { Modal, Button } from 'semantic-ui-react' import DayPicker, { DateUtils } from 'react-day-picker' import 'react-day-picker/lib/style.css' const currentYear = new Date().getFullYear() const fromMonth = new Date(currentYear - 8, 0) const toMonth = new Date(currentYear + 2, 11) function YearMonthForm({ date, localeUtils, onChange }) { const months = localeUtils.getMonths() const years = [] for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) { years.push(i) } const handleChange = function handleChange(e) { const { year, month } = e.target.form onChange(new Date(year.value, month.value)) } return ( <form className="DayPicker-Caption"> <select name="month" onChange={handleChange} value={date.getMonth()}> {months.map((month, i) => ( <option key={i} value={i}> {month} </option> ))} </select> <select name="year" onChange={handleChange} value={date.getFullYear()}> {years.map((year, i) => ( <option key={i} value={year}> {year} </option> ))} </select> </form> ) } class Calendar extends React.Component { state = { month: null, from: null, to: null } handleDayClick = day => { const range = DateUtils.addDayToRange(day, this.state) this.setState(range) } handleYearMonthChange = month => { this.setState({ month }) } handleResetClick = () => { this.setState({ month: null, from: null, to: null }) } handleApplyClick = () => { const { from, to } = this.state this.props.changeFilterDate({ dateStart: from.setHours(0, 0, 0), dateEnd: (to && to.setHours(23, 59, 59)) || from.setHours(23, 59, 59) }) this.props.toggleFilterCalendar() } render() { const { month, from, to } = this.state return ( <Modal open={this.props.isCalendarOpen} onClose={this.props.toggleFilterCalendar} className="transactions-filter-modal" closeIcon size="tiny" > <Modal.Header>Show transactions in range</Modal.Header> <Modal.Content> <DayPicker className="Range" enableOutsideDays numberOfMonths={this.props.isMobile ? 1 : 2} selectedDays={[from, { from, to }]} month={month} captionElement={ <YearMonthForm onChange={this.handleYearMonthChange} /> } onDayClick={this.handleDayClick} /> </Modal.Content> <Modal.Actions> <Button content="Reset" onClick={this.handleResetClick} /> <Button content="Apply" onClick={this.handleApplyClick} positive disabled={this.state.from === null && this.state.to === null} /> </Modal.Actions> </Modal> ) } } export default Calendar
JavaScript
0.000001
44ee430f5b38237332e62759176ab0d357c16f99
add twitter search ui
src/components/TwitterSearch/TwitterSearch.js
src/components/TwitterSearch/TwitterSearch.js
import React, { Component } from 'react'; class TwitterSearch extends Component { render () { return ( <div> <form> <input type="text"/> <button type="submit">Search</button> </form> </div> ); } }; export default TwitterSearch;
import React, { Component } from 'react'; class TwitterSearch extends Component { render () { return ( <p>Twitter Search Component</p> ); } }; export default TwitterSearch;
JavaScript
0
e129678682990f0f98b1b5f30730319beb7308a8
Fix callback
js/net/facebook.js
js/net/facebook.js
var fbUser; function setUser(response) { FB.getLoginStatus(function(response) { if (response.status === 'connected') { // Logged into CRUDbrain and Facebook. fbUser = { id: response.authResponse.userID, access_token: response.authResponse.accessToken }; } }); } function facebookSdk(callback, redirect) { window.fbAsyncInit = function() { FB.init({ appId : '1642565209312684', // Inkling (PRODUCTION) //appId : '1643906175845254', // CRUDbrain (test) cookie : true, xfbml : true, // parse social plugins on this page version : 'v2.2' }); FB.getLoginStatus(function(response) { setUser(response); if (!fbUser) { if (redirect) { window.location.replace('/'); } } else { callback(); } }); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; // PRODUCTION //js.src = "http://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }
var fbUser; function setUser(response) { FB.getLoginStatus(function(response) { if (response.status === 'connected') { // Logged into CRUDbrain and Facebook. fbUser = { id: response.authResponse.userID, access_token: response.authResponse.accessToken }; } }); } function facebookSdk(callback, redirect) { window.fbAsyncInit = function() { FB.init({ appId : '1642565209312684', // Inkling (PRODUCTION) //appId : '1643906175845254', // CRUDbrain (test) cookie : true, xfbml : true, // parse social plugins on this page version : 'v2.2' }); FB.getLoginStatus(function(response) { setUser(response); if (redirect) { if (!fbUser) { window.location.replace('/'); } else { callback(); } } }); }; // Load the SDK asynchronously (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; // PRODUCTION //js.src = "http://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }
JavaScript
0.000003
bcedd28023238d4c07f39b00b735872765147e5b
Fix typo
lib/index.js
lib/index.js
'use strict'; class TeamcityReporter { constructor(emitter, reporterOptions, options) { this.reporterOptions = reporterOptions; this.options = options; const events = 'start beforeIteration iteration beforeItem item beforePrerequest prerequest beforeScript script beforeRequest request beforeTest test beforeAssertion assertion console exception beforeDone done'.split(' '); events.forEach((e) => { if (typeof this[e] == 'function') emitter.on(e, (err, args) => this[e](err, args)) }); } start(err, args) { console.log(`##teamcity[testSuiteStarted name='${this.options.collection.name}']`); } beforeItem(err, args) { this.currItem = {name: args.item.name, passed: true, failedAssertions: []}; console.log(`##teamcity[testStarted name='${this.currItem.name}' captureStandardOutput='true']`); } beforeRequest(err, args) { console.log(args.request.method, args.request.url.toString()); } request(err, args) { if (err) { console.log('request error'); } else { const sizeObj = args.response.size(); const size = sizeObj && (sizeObj.header || 0) + (sizeObj.body || 0) || 0; console.log(`Response code: ${args.response.code}, duration: ${args.response.responseTime}ms, size: ${size} bytes`); this.currItem.response = args.response; } } assertion(err, args) { if (err) { this.currItem.passed = false; this.currItem.failedAssertions.push(args.assertion); } } item(err, args) { if (!this.currItem.passed) { const msg = this.currItem.failedAssertions.join(", "); const details = `Response code: ${this.currItem.response.code}, reason: ${this.currItem.response.reason()}`; console.log(`##teamcity[testFailed name='${args.item.name}' message='${msg}' details='${msg} - ${details}']`); let body; try { body = JSON.parse(this.currItem.response.body) } catch (e) { body = '' }; console.log('Response body:', body); } console.log(`##teamcity[testFinished name='${args.item.name}' duration='${this.currItem.response.responseTime}']`); } done(err, args) { console.log(`##teamcity[testSuiteFinished name='${this.options.collection.name}']`); } } module.exports = TeamcityReporter;
'use strict'; class TeamcityReporter { constructor(emitter, reporterOptions, options) { this.reporterOptions = reporterOptions; this.options = options; const events = 'start beforeIteration iteration beforeItem item beforePrerequest prerequest beforeScript script beforeRequest request beforeTest test beforeAssertion assertion console exception beforeDone done'.split(' '); events.forEach((e) => { if (typeof this[e] == 'function') emitter.on(e, (err, args) => this[e](err, args)) }); } start(err, args) { console.log(`##teamcity[testSuiteStarted name='${this.options.collection.name}']`); } beforeItem(err, args) { this.currItem = {name: args.item.name, passed: true, failedAssertions: []}; console.log(`##teamcity[testStarted name='${this.currItem.name}' captureStandardOutput='true']`); } beforeRequest(err, args) { console.log(args.request.method, args.request.url.toString()); } request(err, args) { if (err) { console.log('request error'); } else { const sizeObj = args.response.size(); const size = sizeObj && (sizeObj.header || 0) + (sizeObj.body || 0) || 0; console.log(`Response code: ${args.response.code}, duration: ${args.response.responseTime}ms, size: ${size} bytes`); this.currItem.response = args.response; } } assertion(err, args) { if (err) { this.currItem.passed = false; this.currItem.failedAssertions.push(args.assertion); } } item(err, args) { if (!this.currItem.passed) { const msg = this.currItem.failedAssertions.join(", "); const details = `Response code: ${this.currItem.response.code}, reason: ${this.currItem.response.reason()}`; console.log(`##teamcity[testFailed name='${args.item.name}' message='${msg}' details='${msg} - ${details}']`); let body; try { body = JSON.parse(this.currItem.response) } catch (e) { body = '' }; console.log('Response body:', body); } console.log(`##teamcity[testFinished name='${args.item.name}' duration='${this.currItem.response.responseTime}']`); } done(err, args) { console.log(`##teamcity[testSuiteFinished name='${this.options.collection.name}']`); } } module.exports = TeamcityReporter;
JavaScript
0.999999
70d4f13df4af2187cffa46e585348d02a1fe65b5
add UTC per @bamos' issue
js/reading-list.js
js/reading-list.js
// http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/ function getTemplateAjax(path, callback) { var source; var template; $.ajax({ url: path, success: function(data) { source = data; template = Handlebars.compile(source); //execute the callback if passed if (callback) callback(template); } }); } function loadYAML(name, f) { var client = new XMLHttpRequest(); client.open('GET', 'data/' + name + '.yaml'); client.onreadystatechange = function() { if (client.readyState == 3) { var yaml = jsyaml.load(client.responseText); if (yaml) { f(yaml); } } } client.send(); } function loadLists() { getTemplateAjax('templates/currently-reading.hbars.html', function(tmpl) { loadYAML("currently-reading", function(yaml) { $("#currently-reading").html(tmpl(yaml)); }); }); getTemplateAjax('templates/up-next.hbars.html', function(tmpl) { loadYAML("up-next", function(yaml) { $("#up-next").html(tmpl(yaml)); }); }); getTemplateAjax('templates/to-read.hbars.html', function(tmpl) { loadYAML("to-read", function(yaml) { $("#to-read").html(tmpl(yaml)); }); }); getTemplateAjax('templates/finished.hbars.html', function(tmpl) { loadYAML("finished", function(yaml) { yaml.sort(function(a,b) { if (a.finished > b.finished) return -1; if (a.finished < b.finished) return 1; return 0; }); function dateString(d) { return d.getUTCFullYear().toString() + "/" + (d.getUTCMonth() + 1).toString() + "/" + (d.getUTCDate() + 1).toString(); } var len = yaml.length; for (var i = 0; i < len; i++) { yaml[i].finished = dateString(yaml[i].finished); } $("#finished").html(tmpl(yaml)); finished_yaml = yaml; loadTimeline(yaml); }); }); } function showModal(title,yaml,idx) { if (quotes_body_tmpl) { bootbox.dialog({ message: quotes_body_tmpl(yaml[idx]), title: title, onEscape: function() {} }); } } // Close the modal dialog if the background of the document is clicked. // Reference: https://github.com/makeusabrew/bootbox/issues/210 $(document).on('click', '.bootbox', function(){ var classname = event.target.className; if(classname && !$('.' + classname).parents('.modal-dialog').length) bootbox.hideAll(); }); function loadTimeline(finished_yaml) { var books = [] $.each(finished_yaml, function(idx, book) { books.push({ "startDate": book.finished.replace(/\//g,","), "headline": book.author + ": " + book.title }); }); var timelineData = { "timeline": { "type": "default", "date": books }}; createStoryJS({ width: "100%", height: "400", source: timelineData, embed_id: 'finished-timeline', start_at_end: true, start_zoom_adjust: 3 }); } $(document).ready(function() { quotes_body_tmpl = null; getTemplateAjax('templates/quotes-body.hbars.html', function(tmpl) { quotes_body_tmpl = tmpl; }); Handlebars.registerHelper('for', function(from, to, block) { var accum = ''; for(var i = from; i < to; ++i) { accum += block.fn(i); } return accum; }); Handlebars.registerHelper('escape', function(variable) { return variable.replace(/(['"])/g, '\\$1'); }); loadLists(); })
// http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/ function getTemplateAjax(path, callback) { var source; var template; $.ajax({ url: path, success: function(data) { source = data; template = Handlebars.compile(source); //execute the callback if passed if (callback) callback(template); } }); } function loadYAML(name, f) { var client = new XMLHttpRequest(); client.open('GET', 'data/' + name + '.yaml'); client.onreadystatechange = function() { if (client.readyState == 3) { var yaml = jsyaml.load(client.responseText); if (yaml) { f(yaml); } } } client.send(); } function loadLists() { getTemplateAjax('templates/currently-reading.hbars.html', function(tmpl) { loadYAML("currently-reading", function(yaml) { $("#currently-reading").html(tmpl(yaml)); }); }); getTemplateAjax('templates/up-next.hbars.html', function(tmpl) { loadYAML("up-next", function(yaml) { $("#up-next").html(tmpl(yaml)); }); }); getTemplateAjax('templates/to-read.hbars.html', function(tmpl) { loadYAML("to-read", function(yaml) { $("#to-read").html(tmpl(yaml)); }); }); getTemplateAjax('templates/finished.hbars.html', function(tmpl) { loadYAML("finished", function(yaml) { yaml.sort(function(a,b) { if (a.finished > b.finished) return -1; if (a.finished < b.finished) return 1; return 0; }); function dateString(d) { return d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/" + (d.getDate() + 1).toString(); } var len = yaml.length; for (var i = 0; i < len; i++) { yaml[i].finished = dateString(yaml[i].finished); } $("#finished").html(tmpl(yaml)); finished_yaml = yaml; loadTimeline(yaml); }); }); } function showModal(title,yaml,idx) { if (quotes_body_tmpl) { bootbox.dialog({ message: quotes_body_tmpl(yaml[idx]), title: title, onEscape: function() {} }); } } // Close the modal dialog if the background of the document is clicked. // Reference: https://github.com/makeusabrew/bootbox/issues/210 $(document).on('click', '.bootbox', function(){ var classname = event.target.className; if(classname && !$('.' + classname).parents('.modal-dialog').length) bootbox.hideAll(); }); function loadTimeline(finished_yaml) { var books = [] $.each(finished_yaml, function(idx, book) { books.push({ "startDate": book.finished.replace(/\//g,","), "headline": book.author + ": " + book.title }); }); var timelineData = { "timeline": { "type": "default", "date": books }}; createStoryJS({ width: "100%", height: "400", source: timelineData, embed_id: 'finished-timeline', start_at_end: true, start_zoom_adjust: 3 }); } $(document).ready(function() { quotes_body_tmpl = null; getTemplateAjax('templates/quotes-body.hbars.html', function(tmpl) { quotes_body_tmpl = tmpl; }); Handlebars.registerHelper('for', function(from, to, block) { var accum = ''; for(var i = from; i < to; ++i) { accum += block.fn(i); } return accum; }); Handlebars.registerHelper('escape', function(variable) { return variable.replace(/(['"])/g, '\\$1'); }); loadLists(); })
JavaScript
0
1eda6012862b58927c02f60f5089c0c8166d4ef5
Fix some mixups between the parsed data and contained videos
lib/saved.js
lib/saved.js
var fs = require('fs'); var YoutubeTrack = require('./youtube-track.js'); var exports = { saved: { videos: {}, }, }; var FILENAME = 'lethe-data.json'; exports.read = function() { try { fs.readFile(FILENAME, 'utf8', (err, data) => { if (err) { if (err.message.indexOf('ENOENT') > -1) { // File doesn't exist console.log(`The lethe-data.json file doesn't exist! This is not an error.`); } else { console.log(err); } } else { var savedVideos = JSON.parse(data).videos; exports.saved.videos = {}; for (var key in savedVideos) { if (savedVideos.hasOwnProperty(key)) { exports.saved.videos[key] = new YoutubeTrack(savedVideos[key].vid, savedVideos[key]); } } } }); } catch (e) { console.log(e); } }; exports.write = function() { fs.writeFile(FILENAME, JSON.stringify(exports.saved), (err) => { if (err) { console.log(err); } }); }; exports.possiblyRetrieveVideo = function(argument) { if (exports.saved.videos.hasOwnProperty(argument)) return exports.saved.videos[argument].vid; else return argument; }; exports.isVideoSaved = function(vid) { for (var key in exports.saved.videos) { if (exports.saved.videos.hasOwnProperty(key)) { var dupe = exports.saved.videos[key]; if (dupe.vid === vid) { return key; } } } return false; }; module.exports = exports;
var fs = require('fs'); var YoutubeTrack = require('./youtube-track.js'); var exports = { saved: { videos: {}, }, }; var FILENAME = 'lethe-data.json'; exports.read = function() { try { fs.readFile(FILENAME, 'utf8', (err, data) => { if (err) { if (err.message.indexOf('ENOENT') > -1) { // File doesn't exist console.log(`The lethe-data.json file doesn't exist! This is not an error.`); } else { console.log(err); } } else { var parsed = JSON.parse(data); exports.saved.videos = {}; for (var key in parsed) { if (parsed.hasOwnProperty(key)) { exports.saved.videos[key] = new YoutubeTrack(parsed[key].vid, parsed[key]); } } } }); } catch (e) { console.log(e); } }; exports.write = function() { fs.writeFile(FILENAME, JSON.stringify(exports.saved), (err) => { if (err) { console.log(err); } }); }; exports.possiblyRetrieveVideo = function(argument) { if (exports.saved.videos.hasOwnProperty(argument)) return exports.saved.videos[argument].vid; else return argument; }; exports.isVideoSaved = function(vid) { for (var key in exports.saved.videos) { if (exports.saved.videos.hasOwnProperty(key)) { var dupe = exports.saved.videos[key]; if (dupe.vid === vid) { return key; } } } return false; }; module.exports = exports;
JavaScript
0.000003
d13f4b9cf81a83d492a589c45a7586d57ee7b9dd
add compare_fn, banner to utils
lib/utils.js
lib/utils.js
/* * yfm * https://github.com/assemble/yfm * Copyright (c) 2013 Jon Schlinkert, contributors. * Licensed under the MIT license. */ var assemble = require('assemble'); var grunt = require('grunt'); var path = require('path'); var fs = require('fs'); var _ = grunt.util._; // The module to be exported. var Utils = module.exports = exports = {}; /** * Accepts two objects (a, b), * @param {Object} a * @param {Object} b * @return {Number} returns 1 if (a >= b), otherwise -1 */ Utils.compareFn = function(a, b) { return a.index >= b.index ? 1 : -1; } /** * This helper is meant to be instructive. You can add additional * properties to the content object to return whatever data you need. * @param {[type]} src [description] * @return {[type]} [description] */ Utils.globBasenames = function(src) { var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { path: path }; }).map(function(obj) { return path.basename(obj.path); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; /* * Returns front matter from files expanded from globbing patterns. * can be used with a single file or many. */ Utils.globFrontMatter = function(src, options) { options = options || {fromFile: true}; var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { content: assemble.data.readYFM(path, options).context }; }).map(function(obj) { return JSON.stringify(obj.content, null, 2); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; Utils.getCurrentYFM = function(src) { var content = assemble.data.readYFM(path, {fromFile: true}).context; return JSON.stringify(content, null, 2); }; Utils.parseYFM = function(options) { var data = assemble.data.readYFM(path, {fromFile: true}).context; return options.fn(JSON.parse(data)); };
var assemble = require('assemble'); var grunt = require('grunt'); var path = require('path'); var fs = require('fs'); var _ = grunt.util._; // The module to be exported. var Utils = module.exports = exports = {}; /** * This helper is meant to be instructive. You can add additional * properties to the content object to return whatever data you need. * @param {[type]} src [description] * @return {[type]} [description] */ Utils.globBasenames = function(src) { var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { path: path }; }).map(function(obj) { return path.basename(obj.path); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; /* * Returns front matter from files expanded from globbing patterns. * can be used with a single file or many. */ Utils.globFrontMatter = function(src) { var content = void 0; return content = grunt.file.expand(src).map(function(path) { return { content: assemble.data.readYFM(path, {fromFile: true}).context }; }).map(function(obj) { return JSON.stringify(obj.content, null, 2); }).join(grunt.util.normalizelf(grunt.util.linefeed)); }; Utils.getCurrentYFM = function(src) { var content = assemble.data.readYFM(path, {fromFile: true}).context; return JSON.stringify(content, null, 2); }; Utils.parseYFM = function(options) { var data = assemble.data.readYFM(path, {fromFile: true}).context; return options.fn(JSON.parse(data)); };
JavaScript
0
33c96a2d97753e55b79bb3ceeea691b284a60691
add Crm-fetch scenario
client/src/app.js
client/src/app.js
import 'bootstrap'; /*import 'bootstrap/css/bootstrap.css!';*/ import {inject} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import AppRouterConfig from 'app.router.config'; import HttpClientConfig from 'aurelia-auth/app.httpClient.config'; //import FetchConfig from 'aurelia-auth/app.fetch-httpClient.config'; import {FetchConfig} from 'aurelia-auth'; @inject(Router,HttpClientConfig,FetchConfig, AppRouterConfig ) export class App { constructor(router, httpClientConfig, fetchConfig, appRouterConfig){ this.router = router; this.httpClientConfig = httpClientConfig; this.appRouterConfig = appRouterConfig; this.fetchConfig = fetchConfig; } activate(){ this.httpClientConfig.configure(); this.appRouterConfig.configure(); this.fetchConfig.configure(); } }
import 'bootstrap'; /*import 'bootstrap/css/bootstrap.css!';*/ import {inject} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import AppRouterConfig from 'app.router.config'; import HttpClientConfig from 'aurelia-auth/app.httpClient.config'; import FetchConfig from 'aurelia-auth/app.fetch-httpClient.config'; @inject(Router,HttpClientConfig,FetchConfig, AppRouterConfig ) export class App { constructor(router, httpClientConfig, fetchConfig, appRouterConfig){ this.router = router; this.httpClientConfig = httpClientConfig; this.appRouterConfig = appRouterConfig; this.fetchConfig = fetchConfig; } activate(){ this.httpClientConfig.configure(); this.appRouterConfig.configure(); this.fetchConfig.configure(); } }
JavaScript
0.000001
912a564e356e0a9904d70da2dafbee78db369383
enable compression on bf hashset
sensor/IntelLocalCachePlugin.js
sensor/IntelLocalCachePlugin.js
/* Copyright 2016 Firewalla LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const log = require('../net2/logger.js')(__filename); const Sensor = require('./Sensor.js').Sensor; const sem = require('../sensor/SensorEventManager.js').getInstance(); const extensionManager = require('./ExtensionManager.js') const f = require('../net2/Firewalla.js'); const updateInterval = 2 * 24 * 3600 * 1000 // once per two days const hashKey = "gsb:bloomfilter:compressed"; const BloomFilter = require('../vendor_lib/bloomfilter.js').BloomFilter; const urlhash = require("../util/UrlHash.js"); const _ = require('lodash'); const bone = require("../lib/Bone.js"); const jsonfile = require('jsonfile'); const zlib = require('zlib'); const Promise = require('bluebird'); const inflateAsync = Promise.promisify(zlib.inflate); class IntelLocalCachePlugin extends Sensor { async loadCacheFromBone() { log.info(`Loading intel cache from cloud...`); const data = await bone.hashsetAsync(hashKey) try { const buffer = Buffer.from(data, 'base64'); const decompressedData = await inflateAsync(buffer); const decompressedString = decompressedData.toString(); const payload = JSON.parse(decompressedString); // jsonfile.writeFileSync("/tmp/x.json", payload); this.bf = new BloomFilter(payload, 16); log.info(`Intel cache is loaded successfully! cache size ${decompressedString.length}`); } catch (err) { log.error(`Failed to load intel cache from cloud, err: ${err}`); this.bf = null; } } async run() { await this.loadCacheFromBone(); setInterval(() => { this.loadCacheFromBone(); }, updateInterval); } checkUrl(url) { // for testing only if(this.config && this.config.testURLs && this.config.testURLs.includes(url)) { return true; } if(!this.bf) { return false; } const hashes = urlhash.canonicalizeAndHashExpressions(url); const matchedHashes = hashes.filter((hash) => { if(!hash) { return false; } const prefix = hash[1]; if(!prefix) { return false; } const prefixHex = this.toHex(prefix); const testResult = this.bf.test(prefixHex); return testResult; }); return !_.isEmpty(matchedHashes); } toHex(base64) { return Buffer.from(base64, 'base64').toString('hex'); } } module.exports = IntelLocalCachePlugin;
/* Copyright 2016 Firewalla LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const log = require('../net2/logger.js')(__filename); const Sensor = require('./Sensor.js').Sensor; const sem = require('../sensor/SensorEventManager.js').getInstance(); const extensionManager = require('./ExtensionManager.js') const f = require('../net2/Firewalla.js'); const updateInterval = 2 * 24 * 3600 * 1000 // once per two days const hashKey = "gsb:bloomfilter"; const BloomFilter = require('../vendor_lib/bloomfilter.js').BloomFilter; const urlhash = require("../util/UrlHash.js"); const _ = require('lodash'); const bone = require("../lib/Bone.js"); const jsonfile = require('jsonfile'); class IntelLocalCachePlugin extends Sensor { async loadCacheFromBone() { log.info(`Loading intel cache from cloud...`); const data = await bone.hashsetAsync(hashKey) try { const payload = JSON.parse(data); // jsonfile.writeFileSync("/tmp/x.json", payload); this.bf = new BloomFilter(payload, 16); log.info("Intel cache is loaded successfully!"); } catch (err) { log.error(`Failed to load intel cache from cloud, err: ${err}`); this.bf = null; } } async run() { await this.loadCacheFromBone(); setInterval(() => { this.loadCacheFromBone(); }, updateInterval); } checkUrl(url) { // for testing only if(this.config && this.config.testURLs && this.config.testURLs.includes(url)) { return true; } if(!this.bf) { return false; } const hashes = urlhash.canonicalizeAndHashExpressions(url); const matchedHashes = hashes.filter((hash) => { if(!hash) { return false; } const prefix = hash[1]; if(!prefix) { return false; } const prefixHex = this.toHex(prefix); const testResult = this.bf.test(prefixHex); return testResult; }); return !_.isEmpty(matchedHashes); } toHex(base64) { return Buffer.from(base64, 'base64').toString('hex'); } } module.exports = IntelLocalCachePlugin;
JavaScript
0
4fa1e22a18b9299f3f05def0b01edc5aa6fbfa16
the new constructor functions: class
docs/class.js
docs/class.js
"use strict" // CLASSES /* classes function just like prototypes in our earlier topic, If you have taken. It's not necessary but if you have a knowdge of prototypes, classes should be a piece of cake. Both of them are just ways to create inheritances on objects. with class enabling th create an adhoc object. Class combines the power of constructor functions and prototypes. */ // the new fancy imports . import obj from "./object" class Polygon{ // this lets you call the class like a constructor function. constructor (height=10, width=10){ this._height = height; this._width = width; } // get in front of a function lets you define a function but call it as a property. get area () { return this.height * this.width } get perimeter(){ return (2 * this.height) + (2 * this.width) } get width(){ return this._width; } get height(){ return this._height; } // the set keyword functions just like the opposite of the get keyword. // lets you set values to Class properties as though you are defining a variable. set height(value){ this._height = value; } set width(value) { this._width = value; } // this means that you can get this method on the Polygon class without instantiating the class using the // 'new' keyword. static get get_height() { return "this is static method on the Rect Object"; } } //NB: the name of the getter and the setter should not be a property on the object itself. // to use getters and setters make the property you are getting or setting inaccessible. class Maths{ constructor (number) { this.number = number; } } // using a prototype for this class object inheritance. Maths.prototype = Math; var math = new Maths(5); console.log(math.number); console.log(math.random()); var r = new Polygon(5, 10) console.log(r.area) console.log(r.width) console.log(Polygon.get_height) console.log(r.perimeter) console.log(obj.foo); // INHERTANCE IN CLASSES. class Rectangle extends Polygon { constructor(length=1, width=1) { super(); Polygon.call(this, length, width); } } var rect = new Rectangle(5, 5); console.log(rect); console.log(rect.area); //NB: this code does not work. debug it if you can. // It raises typeError. this is not a date object. /* class MyDate extends Date { constructor() { super(); } getFormattedDate() { var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear(); } } var aDate = new MyDate(); console.log(aDate.getTime()); console.log(aDate.getFormattedDate()); */
// CLASSES /* classes function just like prototypes in our earlier topic, If you have taken. It's not necessary but if you have a knowdge of prototypes, classes should be a piece of cake. Both of them are just ways to create inheritances on objects. with class enabling th create an adhoc object. Class combines the power of constructor functions and prototypes. */ // the new fancy imports . import obj from "./object" class Polygon{ // this lets you call the class like a constructor function. constructor (height=10, width=10){ this._height = height; this._width = width; } // get in front of a function lets you define a function but call it as a property. get area () { return this.height * this.width } get perimeter(){ return (2 * this.height) + (2 * this.width) } get width(){ return this._width; } get height(){ return this._height; } // the set keyword functions just like the opposite of the get keyword. // lets you set values to Class properties as though you are defining a variable. set height(value){ this._height = value; } set width(value) { this._width = value; } // this means that you can get this method on the Polygon class without instantiating the class using the // 'new' keyword. static get get_height() { return "this is static method on the Rect Object"; } } //NB: the name of the getter and the setter should not be a property on the object itself. // to use getters and setters make the property you are getting or setting inaccessible. class Maths{ constructor (number) { this.number = number; } } // using a prototype for this class object inheritance. Maths.prototype = Math; var math = new Maths(5); console.log(math.number); console.log(math.random()); var r = new Polygon(5, 10) console.log(r.area) console.log(r.width) console.log(Polygon.get_height) console.log(r.perimeter) console.log(obj.foo); // INHERTANCE IN CLASSES. class Rectangle extends Polygon { constructor(length=1, width=1) { super(); Polygon.call(this, length, width); } } var rect = new Rectangle(5, 5); console.log(rect); console.log(rect.area);
JavaScript
0.99984
49af337a75b4c97b7abeeb267a949cfafd9ff7dd
fix baseurl
docs/index.js
docs/index.js
var base = document.baseURI; Jenie.setup({ module: { modules: [ { name: 'one', method: function () { return 1; } }, { name: 'two', method: function () { return 2; } }, { name: 'sum', dependencies: ['one', 'two'], method: function (one, two) { return one + two; } } ] }, router: { routes: [ { title: 'Root', path: '/', component: 'v-root', componentUrl: base + 'views/v-root.js' }, { title: 'Test', path: '/test', component: 'v-test', componentUrl: base + 'views/v-test.html' }, { title: '404', path: '/{*}', component: 'v-404', componentUrl: base + 'views/v-404.html' } ] } }); Jenie.module.export('say', ['sum'], function (sum) { return function (string) { console.log(string); console.log(sum); }; });
Jenie.setup({ module: { modules: [ { name: 'one', method: function () { return 1; } }, { name: 'two', method: function () { return 2; } }, { name: 'sum', dependencies: ['one', 'two'], method: function (one, two) { return one + two; } } ] }, router: { base: '/jenie', routes: [ { title: 'Root', path: '/', component: 'v-root', componentUrl: '/views/v-root.js' }, { title: 'Test', path: '/test', component: 'v-test', componentUrl: '/views/v-test.html' }, { title: '404', path: '/{*}', component: 'v-404', componentUrl: '/views/v-404.html' } ] } }); Jenie.module.export('say', ['sum'], function (sum) { return function (string) { console.log(string); console.log(sum); }; });
JavaScript
0
6838eaf66b94445e314f087ec407d7e2b5bf1fb5
remove cruft from wallaby config
.wallaby.js
.wallaby.js
'use strict'; module.exports = () => { return { files: [ 'index.js', 'lib/**/*.{js,json}', 'test/setup.js', 'test/assertions.js', { pattern: 'test/node-unit/**/*.fixture.js', instrument: false }, { pattern: 'test/unit/**/*.fixture.js', instrument: false }, 'package.json', 'test/opts/mocha.opts', 'mocharc.yml' ], filesWithNoCoverageCalculated: [ 'test/**/*.fixture.js', 'test/setup.js', 'test/assertions.js', 'lib/browser/**/*.js' ], tests: ['test/unit/**/*.spec.js', 'test/node-unit/**/*.spec.js'], env: { type: 'node', runner: 'node' }, workers: {recycle: true}, testFramework: {type: 'mocha', path: __dirname}, setup(wallaby) { // running mocha instance is not the same as mocha under test, // running mocha is the project's source code mocha, mocha under test is instrumented version of the source code const runningMocha = wallaby.testFramework; runningMocha.timeout(1000); // to expose it/describe etc. on the mocha under test const MochaUnderTest = require('./'); const mochaUnderTest = new MochaUnderTest(); mochaUnderTest.suite.emit( MochaUnderTest.Suite.constants.EVENT_FILE_PRE_REQUIRE, global, '', mochaUnderTest ); require('./test/setup'); }, debug: true }; };
'use strict'; module.exports = () => { return { files: [ 'index.js', 'lib/**/*.{js,json}', 'test/setup.js', 'test/assertions.js', { pattern: 'test/node-unit/**/*.fixture.js', instrument: false }, { pattern: 'test/unit/**/*.fixture.js', instrument: false }, 'package.json', 'test/opts/mocha.opts', 'mocharc.yml' ], filesWithNoCoverageCalculated: [ 'test/**/*.fixture.js', 'test/setup.js', 'test/assertions.js', 'lib/browser/**/*.js' ], tests: ['test/unit/**/*.spec.js', 'test/node-unit/**/*.spec.js'], env: { type: 'node', runner: 'node' }, workers: {recycle: true}, testFramework: {type: 'mocha', path: __dirname}, setup(wallaby) { // running mocha instance is not the same as mocha under test, // running mocha is the project's source code mocha, mocha under test is instrumented version of the source code const runningMocha = wallaby.testFramework; runningMocha.timeout(200); // to expose it/describe etc. on the mocha under test const MochaUnderTest = require('./'); const mochaUnderTest = new MochaUnderTest(); mochaUnderTest.suite.emit( MochaUnderTest.Suite.constants.EVENT_FILE_PRE_REQUIRE, global, '', mochaUnderTest ); // to make test/node-unit/color.spec.js pass, we need to run mocha in the project's folder context const childProcess = require('child_process'); const execFile = childProcess.execFile; childProcess.execFile = function() { let opts = arguments[2]; if (typeof opts === 'function') { opts = {}; Array.prototype.splice.call(arguments, 2, 0, opts); } opts.cwd = wallaby.localProjectDir; return execFile.apply(this, arguments); }; require('./test/setup'); }, debug: true }; };
JavaScript
0
1963dddb4c4b85bac510c1f9fb930e3402dbf30b
use different value for rest input
test/bq-translator.test.js
test/bq-translator.test.js
// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*- var assert = require('chai').assert; var BooleanQueryTranslator = require('../lib/bq-translator').BooleanQueryTranslator; function testQuery(label, expected, query) { test('query: ' + label + ': ' + '<' + query + '> -> <' + expected + '>', function() { var translator = new BooleanQueryTranslator(); assert.equal(expected, translator.translate(query)); }); } function testExpression(label, expectedScriptGrnExpr, expectedOffset, expression) { test('expression: ' + label + ': ' + '<' + expression + '> -> <' + expectedScriptGrnExpr + '>', function() { var translator = new BooleanQueryTranslator(); var context = { defaultField: "field", offset: 0 }; var actualScriptGrnExpr = translator.translateExpression(expression, context); assert.deepEqual({ scriptGrnExpr: expectedScriptGrnExpr, offset: expectedOffset }, { scriptGrnExpr: actualScriptGrnExpr, offset: context.offset }); }); } suite('BoolanQueryTranslator', function() { testQuery("expression", 'type:"ModelName"', "type:'ModelName'"); testQuery("group: raw expressions", 'query query type:"ModelName"', "(and query query type:'ModelName')"); testQuery("group: quoted expression", '"query query" type:"ModelName"', "(and 'query query' type:'ModelName')"); testExpression("value only: stirng", "field @ \"keyword1 keyword2\"", "'keyword1 keyword2'".length, "'keyword1 keyword2' 'other keyword'"); testExpression("value only: unsigned integer", "field == 29", "29".length, "29 75"); })
// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*- var assert = require('chai').assert; var BooleanQueryTranslator = require('../lib/bq-translator').BooleanQueryTranslator; function testQuery(label, expected, query) { test('query: ' + label + ': ' + '<' + query + '> -> <' + expected + '>', function() { var translator = new BooleanQueryTranslator(); assert.equal(expected, translator.translate(query)); }); } function testExpression(label, expectedScriptGrnExpr, expectedOffset, expression) { test('expression: ' + label + ': ' + '<' + expression + '> -> <' + expectedScriptGrnExpr + '>', function() { var translator = new BooleanQueryTranslator(); var context = { defaultField: "field", offset: 0 }; var actualScriptGrnExpr = translator.translateExpression(expression, context); assert.deepEqual({ scriptGrnExpr: expectedScriptGrnExpr, offset: expectedOffset }, { scriptGrnExpr: actualScriptGrnExpr, offset: context.offset }); }); } suite('BoolanQueryTranslator', function() { testQuery("expression", 'type:"ModelName"', "type:'ModelName'"); testQuery("group: raw expressions", 'query query type:"ModelName"', "(and query query type:'ModelName')"); testQuery("group: quoted expression", '"query query" type:"ModelName"', "(and 'query query' type:'ModelName')"); testExpression("value only: stirng", "field @ \"keyword1 keyword2\"", "'keyword1 keyword2'".length, "'keyword1 keyword2' 'other keyword'"); testExpression("value only: unsigned integer", "field == 29", "29".length, "29 29"); })
JavaScript
0.00003
7f6bda8aeae435ca4f5d4ab3feec0f88b4a9cb5b
Fix bad test for tabbed nav presence
test/components/AppTest.js
test/components/AppTest.js
const assert = require('assert') const React = require('react') const ReactDOM = require('react-dom') const ReactRedux = require('react-redux') const Redux = require('redux') const TestUtils = require('react-addons-test-utils') const fetchMock = require('fetch-mock') const App = require('../../src/components/App') const reducer = require('../../src/reducers/reducer') const GitHubAuth = require('../../src/models/GitHubAuth') const Filter = require('../../src/models/Filter') const LastFilter = require('../../src/models/LastFilter') const Config = require('../../src/config.json') function renderPage(store) { return TestUtils.renderIntoDocument( <ReactRedux.Provider store={store}> <App /> </ReactRedux.Provider> ) } describe('App', () => { let store describe('when valid auth token is not set', () => { before(() => { store = Redux.createStore(reducer) fetchMock.mock('*', {}) }) after(() => { fetchMock.restore() }) it('renders', () => { const appComponent = renderPage(store) assert(ReactDOM.findDOMNode(appComponent)) }) it('has a tabbed nav', () => { const appComponent = renderPage(store) const app = ReactDOM.findDOMNode(appComponent) assert(app.querySelector('#tabbed-nav')) }) it('does not make request without a token', () => { renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(0, fetchedCalls.length, 'No fetch calls should be made.') }) it('fetches user when auth token is set', () => { GitHubAuth.setToken('test-whee') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(1, fetchedCalls.length, 'Only one fetch call should be made') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) describe('when valid auth token is set', () => { before(() => { store = Redux.createStore(reducer) GitHubAuth.setToken('test-whee') fetchMock.get(`${Config.githubApiUrl}/user`, { login: 'testuser123' }) fetchMock.get(`${Config.githubApiUrl}/search/issues?q=cats`, []) }) after(() => { fetchMock.restore() }) it('fetches user and issues when filter exists', () => { const filter = new Filter('Cool name') filter.store('cats') LastFilter.save('Cool name') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(2, fetchedCalls.length, 'Two fetch calls should be made') assert(fetchedCalls[1][0].match(/\/search\/issues/), 'Fetch call should be to the search issues API') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) })
const assert = require('assert') const React = require('react') const ReactDOM = require('react-dom') const ReactRedux = require('react-redux') const Redux = require('redux') const TestUtils = require('react-addons-test-utils') const fetchMock = require('fetch-mock') const App = require('../../src/components/App') const reducer = require('../../src/reducers/reducer') const GitHubAuth = require('../../src/models/GitHubAuth') const Filter = require('../../src/models/Filter') const LastFilter = require('../../src/models/LastFilter') const Config = require('../../src/config.json') function renderPage(store) { return TestUtils.renderIntoDocument( <ReactRedux.Provider store={store}> <App /> </ReactRedux.Provider> ) } describe('App', () => { let store describe('when valid auth token is not set', () => { before(() => { store = Redux.createStore(reducer) fetchMock.mock('*', {}) }) after(() => { fetchMock.restore() }) it('renders', () => { const appComponent = renderPage(store) assert(ReactDOM.findDOMNode(appComponent)) }) it('has a tabbed nav', () => { const appComponent = renderPage(store) const app = ReactDOM.findDOMNode(appComponent) assert(app.querySelectorAll('tabbed-nav')) }) it('does not make request without a token', () => { renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(0, fetchedCalls.length, 'No fetch calls should be made.') }) it('fetches user when auth token is set', () => { GitHubAuth.setToken('test-whee') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(1, fetchedCalls.length, 'Only one fetch call should be made') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) describe('when valid auth token is set', () => { before(() => { store = Redux.createStore(reducer) GitHubAuth.setToken('test-whee') fetchMock.get(`${Config.githubApiUrl}/user`, { login: 'testuser123' }) fetchMock.get(`${Config.githubApiUrl}/search/issues?q=cats`, []) }) after(() => { fetchMock.restore() }) it('fetches user and issues when filter exists', () => { const filter = new Filter('Cool name') filter.store('cats') LastFilter.save('Cool name') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(2, fetchedCalls.length, 'Two fetch calls should be made') assert(fetchedCalls[1][0].match(/\/search\/issues/), 'Fetch call should be to the search issues API') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) })
JavaScript
0.000001
c5aa570edcc9c0815c304939d9ded20b13a8e56f
Update loader.js
plugins/spoon/project_structure/app/loader.js
plugins/spoon/project_structure/app/loader.js
/*global requirejs*/ requirejs.config({ baseUrl: '/dev/src', paths: { 'mout': '../bower_components/mout/src', 'events-emitter': '../bower_components/events-emitter/src', 'address': '../bower_components/address/src', 'text': '../bower_components/requirejs-text/text', 'has': '../bower_components/has/has', {{paths}} }, shim: { {{shim}} }, map: { '*': { // App config (defaults to dev but changes during build) 'app-config': '../app/config/config_dev', // Spoon 'spoon': '../bower_components/spoonjs/src/index', // Spoon aliases 'spoon/Controller': '../bower_components/spoonjs/src/core/Controller', 'spoon/View': '../bower_components/spoonjs/src/core/View', 'spoon/Joint': '../bower_components/spoonjs/src/core/Joint', // Spoon services 'services/broadcaster': '../bower_components/spoonjs/src/core/Broadcaster/BroadcasterFactory', 'services/address': '../bower_components/spoonjs/src/core/Address/AddressFactory', 'services/state': '../bower_components/spoonjs/src/core/StateRegistry/StateRegistryFactory' } }, packages: [ // CSS plugin { name: 'css', location: '../bower_components/require-css', main: 'css' } ] });
/*global requirejs*/ requirejs.config({ baseUrl: '/dev/src', paths: { 'mout': '../bower_components/mout/src', 'events-emitter': '../bower_components/events-emitter/src', 'address': '../bower_components/address/src', 'text': '../bower_components/requirejs-text/text', 'has': '../bower_components/has/has', {{paths}} }, shim: { {{shim}} }, map: { '*': { // App config (defaults to dev but changes during build) 'app-config': '../app/config/config_dev', // Spoon 'spoon': '../bower_components/spoonjs/src/index', // Spoon aliases 'spoon/Controller': '../bower_components/spoonjs/src/core/Controller', 'spoon/View': '../bower_components/spoonjs/src/core/View', // Spoon services 'services/broadcaster': '../bower_components/spoonjs/src/core/Broadcaster/BroadcasterFactory', 'services/address': '../bower_components/spoonjs/src/core/Address/AddressFactory', 'services/state': '../bower_components/spoonjs/src/core/StateRegistry/StateRegistryFactory' } }, packages: [ // CSS plugin { name: 'css', location: '../bower_components/require-css', main: 'css' } ] });
JavaScript
0.000002
18f957c3a7fd7e70a4e275b2a4f700a5231316ce
add real controller tests
test/factories/debounce.js
test/factories/debounce.js
/*global beforeEach,afterEach,describe,it*/ import debounce from '../../src/factories/debounce' import { reset, check, expect, expectCount } from '../helpers/chaiCounter' import controller from '../helpers/controller' function increaseCount ({ state }) { state.set('count', state.get('count') + 1) } controller.addSignals({ increaseImmediate: {chain: [debounce(1, [increaseCount])], sync: true}, increaseNotImmediate: {chain: [debounce(1, [increaseCount], { immediate: false })], sync: true} }) const signals = controller.getSignals() let tree beforeEach(reset) afterEach(check) describe('debounce()', function () { beforeEach(function () { tree = controller.model.tree tree.set({ count: 0 }) tree.commit() }) it('should not call increase more than twice when immediate', function (done) { signals.increaseImmediate() signals.increaseImmediate() signals.increaseImmediate() signals.increaseImmediate() signals.increaseImmediate() setTimeout(function () { expect(tree.get('count')).to.equal(2) done() }, 10) }) it('should not call increase more than once when not immediate', function (done) { signals.increaseNotImmediate() signals.increaseNotImmediate() signals.increaseNotImmediate() signals.increaseNotImmediate() signals.increaseNotImmediate() setTimeout(function () { expect(tree.get('count')).to.equal(1) done() }, 10) }) it('should not call output more than twice when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should not call output again after timeout when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 3) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should not call output more than once', function (done) { expectCount(1) let terminated = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { expect(terminated).to.equal(4) done() }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should call output again after timeout', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(4) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should respect defaults', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, []) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) })
/*global beforeEach,afterEach,describe,it*/ import debounce from '../../src/factories/debounce' import { reset, check, expect, expectCount } from '../helpers/chaiCounter' beforeEach(reset) afterEach(check) describe('debounce()', function () { it('should not call output more than twice when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should not call output again after timeout when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 3) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should not call output more than once', function (done) { expectCount(1) let terminated = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { expect(terminated).to.equal(4) done() }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should call output again after timeout', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(4) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should respect defaults', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, []) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) })
JavaScript
0.000001
684e42a48c008c1ab7c53e0ba3220db8f5f777dc
revert debugging
stream/osm_filter.js
stream/osm_filter.js
var through = require('through2'), features = require('../features'); function isAddress( item ){ return( item.tags.hasOwnProperty('addr:housenumber') && item.tags.hasOwnProperty('addr:street') ); } function isPOIFromFeatureList( item ){ return( 'string' === typeof item.tags.name && !!features.getFeature( item ) ); } module.exports = function(){ var stream = through.obj( function( item, enc, done ) { // filter items missing requires properties if( !!item && item.hasOwnProperty('id') && (( item.type === 'node' && item.hasOwnProperty('lat') && item.hasOwnProperty('lon') ) || ( item.type === 'way' && Array.isArray( item.refs ) && item.refs.length > 0 )) && 'object' == typeof item.tags && ( isAddress( item ) || isPOIFromFeatureList( item ) )){ this.push( item ); } return done(); }); // catch stream errors stream.on( 'error', console.error.bind( console, __filename ) ); return stream; };
var through = require('through2'), features = require('../features'); function isAddress( item ){ return( item.tags.hasOwnProperty('addr:housenumber') && item.tags.hasOwnProperty('addr:street') ); } function isPOIFromFeatureList( item ){ return( 'string' === typeof item.tags.name && !!features.getFeature( item ) ); } var lastCommit = new Date().getTime(); var c = 0; function inc( type, record ){ c++; var now = new Date().getTime(); if( now >= lastCommit +1000 ){ lastCommit = now; console.log( c ); c = 0; } } module.exports = function(){ var stream = through.obj( function( item, enc, done ) { inc( 'a', item ); // filter items missing requires properties if( !!item && item.hasOwnProperty('id') && (( item.type === 'node' && item.hasOwnProperty('lat') && item.hasOwnProperty('lon') ) || ( item.type === 'way' && Array.isArray( item.refs ) && item.refs.length > 0 )) && 'object' == typeof item.tags && ( isAddress( item ) || isPOIFromFeatureList( item ) )){ this.push( item ); } return done(); }); // catch stream errors stream.on( 'error', console.error.bind( console, __filename ) ); return stream; };
JavaScript
0.000001
b90b374f30fbf043d2ecaa0f87d5911d3b4df4c5
test main reducer handling SET_INTERFACE_FONT_SIZE_SCALING_FACTOR
test/redux/modules/main.js
test/redux/modules/main.js
import test from 'ava'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import mainReducer, {setInterfaceFontSizeScalingFactor, SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, setAppFont, SET_APP_FONT, setAppLocale, SET_APP_LOCALE, setWriteDelay, SET_WRITE_DELAY, setIntl} from './../../../src/redux/modules/main'; import zhTwMessages from './../../../src/langs/zh-TW'; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); test('should create an action to set interface font size scaling factor', (t) => { const interfaceFontSizeScalingFactor = 1; const expectedAction = { type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor }; t.deepEqual(setInterfaceFontSizeScalingFactor(interfaceFontSizeScalingFactor), expectedAction); }); test('should create an action to set app font', (t) => { const appFont = 'Tibetan Machine Uni'; const expectedAction = { type: SET_APP_FONT, appFont }; t.deepEqual(setAppFont(appFont), expectedAction); }); test('should create an action to set app locale', (t) => { const appLocale = 'bo'; const expectedAction = { type: SET_APP_LOCALE, appLocale }; t.deepEqual(setAppLocale(appLocale), expectedAction); }); test('should create an action to set write delay', (t) => { const writeDelay = 25; const expectedAction = { type: SET_WRITE_DELAY, writeDelay }; t.deepEqual(setWriteDelay(writeDelay), expectedAction); }); test('should create an action to set react intl', (t) => { const store = mockStore({}); const locale = 'zh-TW'; const expectedAction = { type: '@@intl/UPDATE', payload: { locale, messages: zhTwMessages } }; const resultAction = store.dispatch(setIntl(locale)); t.deepEqual(resultAction, expectedAction); }); test('main reducer should handle action SET_APP_LOCALE', (t) => { const appLocale = 'en'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_LOCALE, appLocale}); t.deepEqual(result.toJS(), {appLocale}); }); test('main reducer should handle action SET_WRITE_DELAY', (t) => { const writeDelay = 50; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_WRITE_DELAY, writeDelay}); t.deepEqual(result.toJS(), {writeDelay}); }); test('main reducer should handle action SET_APP_FONT', (t) => { const appFont = 'Tibetan Machine Uni'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_FONT, appFont}); t.deepEqual(result.toJS(), {appFont}); }); test('main reducer should handle action SET_INTERFACE_FONT_SIZE_SCALING_FACTOR', (t) => { const interfaceFontSizeScalingFactor = 1.5; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor}); t.deepEqual(result.toJS(), {interfaceFontSizeScalingFactor}); });
import test from 'ava'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import mainReducer, {setInterfaceFontSizeScalingFactor, SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, setAppFont, SET_APP_FONT, setAppLocale, SET_APP_LOCALE, setWriteDelay, SET_WRITE_DELAY, setIntl} from './../../../src/redux/modules/main'; import zhTwMessages from './../../../src/langs/zh-TW'; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); test('should create an action to set interface font size scaling factor', (t) => { const interfaceFontSizeScalingFactor = 1; const expectedAction = { type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor }; t.deepEqual(setInterfaceFontSizeScalingFactor(interfaceFontSizeScalingFactor), expectedAction); }); test('should create an action to set app font', (t) => { const appFont = 'Tibetan Machine Uni'; const expectedAction = { type: SET_APP_FONT, appFont }; t.deepEqual(setAppFont(appFont), expectedAction); }); test('should create an action to set app locale', (t) => { const appLocale = 'bo'; const expectedAction = { type: SET_APP_LOCALE, appLocale }; t.deepEqual(setAppLocale(appLocale), expectedAction); }); test('should create an action to set write delay', (t) => { const writeDelay = 25; const expectedAction = { type: SET_WRITE_DELAY, writeDelay }; t.deepEqual(setWriteDelay(writeDelay), expectedAction); }); test('should create an action to set react intl', (t) => { const store = mockStore({}); const locale = 'zh-TW'; const expectedAction = { type: '@@intl/UPDATE', payload: { locale, messages: zhTwMessages } }; const resultAction = store.dispatch(setIntl(locale)); t.deepEqual(resultAction, expectedAction); }); test('main reducer should handle action SET_APP_LOCALE', (t) => { const appLocale = 'en'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_LOCALE, appLocale}); t.deepEqual(result.toJS(), {appLocale}); }); test('main reducer should handle action SET_WRITE_DELAY', (t) => { const writeDelay = 50; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_WRITE_DELAY, writeDelay}); t.deepEqual(result.toJS(), {writeDelay}); }); test('main reducer should handle action SET_APP_FONT', (t) => { const appFont = 'Tibetan Machine Uni'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_FONT, appFont}); t.deepEqual(result.toJS(), {appFont}); });
JavaScript
0.000002
d311de104685d657427085ba3bb66b20a63d4b04
Fix unit tests
test/spec/CSSUtils-test.js
test/spec/CSSUtils-test.js
/* * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved. */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, waitsFor: false, runs: false, $: false, brackets: false */ define(function (require, exports, module) { 'use strict'; var CSSUtils = require("CSSUtils"), SpecRunnerUtils = require("./SpecRunnerUtils.js"); describe("CSS Utils", function () { var content = ""; beforeEach(function () { var doneReading = false; // Read the contents of bootstrap.css. This will be used for all tests below runs(function () { var testFilePath = SpecRunnerUtils.getTestPath("/spec/CSSUtils-test-files/"); brackets.fs.readFile(testFilePath + "bootstrap.css", "utf8", function (err, fileContents) { content = fileContents; doneReading = true; }); }); waitsFor(function () { return doneReading; }, 1000); }); it("should find the first instance of the h2 selector", function () { var selector = CSSUtils._findAllMatchingSelectorsInText(content, "h2")[0]; expect(selector).not.toBe(null); expect(selector.line).toBe(292); expect(selector.ruleEndLine).toBe(301); }); it("should find all instances of the h2 selector", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "h2"); expect(selectors).not.toBe(null); expect(selectors.length).toBe(2); expect(selectors[0].line).toBe(292); expect(selectors[0].ruleEndLine).toBe(301); expect(selectors[1].line).toBe(318); expect(selectors[1].ruleEndLine).toBe(321); }); it("should return an empty array when findAllMatchingSelectors() can't find any matches", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "NO-SUCH-SELECTOR"); expect(selectors.length).toBe(0); }); }); });
/* * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved. */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, waitsFor: false, runs: false, $: false, brackets: false */ define(function (require, exports, module) { 'use strict'; var CSSUtils = require("CSSUtils"), SpecRunnerUtils = require("./SpecRunnerUtils.js"); describe("CSS Utils", function () { var content = ""; beforeEach(function () { var doneReading = false; // Read the contents of bootstrap.css. This will be used for all tests below runs(function () { var testFilePath = SpecRunnerUtils.getTestPath("/spec/CSSUtils-test-files/"); brackets.fs.readFile(testFilePath + "bootstrap.css", "utf8", function (err, fileContents) { content = fileContents; doneReading = true; }); }); waitsFor(function () { return doneReading; }, 1000); }); it("should find the first instance of the h2 selector", function () { var selector = CSSUtils._findAllMatchingSelectorsInText(content, "h2")[0]; expect(selector).not.toBe(null); expect(selector.line).toBe(292); expect(selector.ruleEndLine).toBe(301); }); it("should find all instances of the h2 selector", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "h2"); expect(selectors).not.toBe(null); expect(selectors.length).toBe(2); expect(selectors[0].start).toBe(292); expect(selectors[0].end).toBe(301); expect(selectors[1].start).toBe(318); expect(selectors[1].end).toBe(321); }); it("should return an empty array when findAllMatchingSelectors() can't find any matches", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "NO-SUCH-SELECTOR"); expect(selectors.length).toBe(0); }); }); });
JavaScript
0.000005
8567710f50eeee9a6bde3039895d1d91bc85b56f
Document ui/ContainerAnnotator.
ui/ContainerAnnotator.js
ui/ContainerAnnotator.js
'use strict'; var oo = require('../util/oo'); var _ = require('../util/helpers'); var Component = require('./Component'); var ContainerEditor = require('./ContainerEditor'); var $$ = Component.$$; /** Represents a flow annotator that manages a sequence of nodes in a container. Needs to be instantiated within a ui/Controller context. Works like a {@link ui/ContainerEditor} but you can only annotate, not edit. @class ContainerAnnotator @component @extends ui/ContainerEditor @prop {String} name unique editor name @prop {String} containerId container id @prop {ui/SurfaceCommand[]} commands array of command classes to be available @example ```js $$(ContainerAnnotator, { name: 'bodySurface', containerId: 'main', doc: doc, commands: [ToggleStrong] }) ``` */ function ContainerAnnotator() { ContainerEditor.apply(this, arguments); } ContainerAnnotator.Prototype = function() { this.render = function() { var doc = this.getDocument(); var containerNode = doc.get(this.props.containerId); var el = $$("div") .addClass('surface container-node ' + containerNode.id) .attr({ spellCheck: false, "data-id": containerNode.id, "contenteditable": false }); // node components _.each(containerNode.nodes, function(nodeId) { el.append(this._renderNode(nodeId)); }, this); return el; }; }; oo.inherit(ContainerAnnotator, ContainerEditor); module.exports = ContainerAnnotator;
'use strict'; var oo = require('../util/oo'); var _ = require('../util/helpers'); var Component = require('./Component'); var ContainerEditor = require('./ContainerEditor'); var $$ = Component.$$; /** Represents a flow annotator that manages a sequence of nodes in a container. Instantiate this class using {@link ui/Component.$$} within the render method of a component. Needs to be instantiated within a {@link ui/Controller} context. @class ContainerAnnotator @component @extends ui/ContainerEditor @example ```js var ContainerAnnotator = require('substance/ui/ContainerAnnotator'); var Component = require('substance/ui/Component'); var ToggleStrong = require('substance/packages/strong/ToggleStrong'); var MyAnnotator = Component.extend({ render: function() { var annotator = $$(ContainerAnnotator, { name: 'main', containerId: 'main', doc: doc, commands: [ToggleStrong] }).ref('annotator'); return $$('div').addClass('my-annotator').append(annotator); } }); ``` */ function ContainerAnnotator() { ContainerEditor.apply(this, arguments); } ContainerAnnotator.Prototype = function() { this.render = function() { var doc = this.getDocument(); var containerNode = doc.get(this.props.containerId); var el = $$("div") .addClass('surface container-node ' + containerNode.id) .attr({ spellCheck: false, "data-id": containerNode.id, "contenteditable": false }); // node components _.each(containerNode.nodes, function(nodeId) { el.append(this._renderNode(nodeId)); }, this); return el; }; }; oo.inherit(ContainerAnnotator, ContainerEditor); module.exports = ContainerAnnotator;
JavaScript
0
e1230f472d33ea79b12e299c8585886686050d89
work with connection logigc
middleware.js
middleware.js
module.exports = { incoming: function (message, args) { console.log(args); console.log('agents') console.log(global.agents); console.log('users'); console.log(global.users); console.log('************'); // WHERE do we create a user? on first run? // WHEN do we update the user's address? Conv id will change. // Store by convo id? // add message to transcript // update last active to help keep track of 'current' convos // TODO: this will BREAK with changing convoIds. fix it if (message.text) { // only execute on message event var userConvo = message.address.conversation.id; if (!message.address.user.isStaff && !global.users[userConvo]) { console.log('I am adding a new user') global.users[userConvo] = new global.User(message); } else if (!message.address.user.isStaff) { global.users[userConvo].transcript += message.text; } else { // TODO make real logic around agent global.agents[userConvo] = new global.User(message); } } else if (message.text === 'bot') { handoffToBot(message.user.conversation.id); } return message; }, outgoing: function (message, args) { // routing info goes here. // or default to user address, just change if they want to talk to a user? // like update addy value. Then we just look for our own entry and route accordingly console.log(message.address); console.log(args); if (!message.address.user.isStaff) { // route user messages to agent if appropriate. Otherwise send to the bot message.address = global.users[message.address.converation.id].routeMessagesTo ? global.users[message.address.converation.id].routeMessagesTo : message.address; } console.log('address'); console.log(message.address); console.log('==========='); return message }, handoffToAgent: function (user) { var agent = Object.keys(global.agents); // TODO choose how to filter for an agent, or factor out to another method // make agnostic enough that this can pass to agent from bot or another agent // keep in mind only letting 1 user talk to 1 agent. 1 agent can talk to many users console.log('handoff to agent'); console.log(agent); global.users[user].routeMessagesTo = global.agents[agent[0]].address; }, handoffToBot: function (user) { // look up user global.users[user].routeMessagesTo = false; }, getCurrentConversations: function () { // return all current conversations }, transcribeConversation: function () { // store all messages between user/bot user/agent // do this in a way that speaker is obvious }, getTranscriptForAgent: function () { // end goal is to populate a webchat window so agent seamlessly joins existing conversation }, }
module.exports = { incoming: function (message, args) { console.log(args); console.log('users') console.log(global.users); console.log('************'); // WHERE do we create a user? on first run? // WHEN do we update the user's address? Conv id will change. // Store by convo id? // add message to transcript // update last active to help keep track of 'current' convos // TODO: this will BREAK with changing convoIds. fix it if (message.text) { // only execute on message event var userConvo = message.address.conversation.id; if (!message.address.user.isStaff && !global.users[userConvo]) { console.log('I am adding a new user') global.users[userConvo] = new global.User(message); } else if (!message.address.user.isStaff) { global.users[userConvo].transcript += message.text; } else { // TODO make real logic around agent global.agents[userConvo] = new global.User(message); } } else if (message.text === 'bot') { handoffToBot(message.user.conversation.id); } return message; }, outgoing: function (message, args) { // routing info goes here. // or default to user address, just change if they want to talk to a user? // like update addy value. Then we just look for our own entry and route accordingly console.log(message.address); console.log(args); if (!message.address.user.isStaff) { // route user messages to agent if appropriate. Otherwise send to the bot message.address = global.users[message.address.converation.id].routeMessagesTo ? global.users[message.address.converation.id].routeMessagesTo : message.address; } console.log('address'); console.log(message.address); console.log('==========='); return message }, handoffToAgent: function (user) { var agent = Object.keys(global.agents); // TODO choose how to filter for an agent, or factor out to another method // make agnostic enough that this can pass to agent from bot or another agent // keep in mind only letting 1 user talk to 1 agent. 1 agent can talk to many users global.users[user].routeMessagesTo = agent[0].address; }, handoffToBot: function (user) { // look up user global.users[user].routeMessagesTo = false; }, getCurrentConversations: function () { // return all current conversations }, transcribeConversation: function () { // store all messages between user/bot user/agent // do this in a way that speaker is obvious }, getTranscriptForAgent: function () { // end goal is to populate a webchat window so agent seamlessly joins existing conversation }, }
JavaScript
0
a23cbe516dc69ffd39c07e4bdf394a51c1374a04
Clarify the copy in the add liquids to deck hint (#2107)
protocol-designer/src/tutorial/hintManifest.js
protocol-designer/src/tutorial/hintManifest.js
// @flow type Hint = {title: string, body: string} const hintManifest: {[string]: Hint} = { add_liquids_and_labware: { title: 'Add Liquids to Deck', body: 'Go to Starting Deck State and hover over labware to specify where liquids start before the robot starts moving.' } } export type HintKey = $Keys<typeof hintManifest> export default hintManifest
// @flow type Hint = {title: string, body: string} const hintManifest: {[string]: Hint} = { add_liquids_and_labware: { title: 'Add Liquids to Deck', body: "Go to 'Labware & Liquids' and specify where liquids start on the deck before the robot starts moving." } } export type HintKey = $Keys<typeof hintManifest> export default hintManifest
JavaScript
0.000001
713c03cd946b03939517e3932ab822b00b95eaf5
fix the auto registering of app services
src/Kernel/Core.js
src/Kernel/Core.js
namespace('Sy.Kernel'); /** * Framework heart * * @package Sy * @subpackage Kernel * @class */ Sy.Kernel.Core = function () { this.config = new Sy.Configurator(); this.container = new Sy.ServiceContainer('sy::core'); }; Sy.Kernel.Core.prototype = Object.create(Object.prototype, { /** * Return the framework config object * * @return {Sy.Configurator} */ getConfig: { value: function () { return this.config; } }, /** * Return the service container object * * @return {Sy.ServiceContainer} */ getServiceContainer: { value: function () { return this.container; } }, /** * Initiate the kernel that will inspect the app and build necessary data * * @return {Sy.Kernel.Core} */ init: { value: function () { var parser = new Sy.Kernel.AppParser(); this.config.set('parameters.app.meta', { bundles: parser.getBundles(), controllers: parser.getControllers(), entities: parser.getEntities(), viewscreens: parser.getViewScreens() }); this.registerServices(parser.getServices()); } }, /** * Register the app services in the global container * * @param {Array} services * * @return {Sy.Kernel.Core} */ registerServices: { value: function (services) { for (var i = 0, l = services.length; i < l; i++) { if (services[i].creator) { this.container.set( services[i].name, services[i].creator ); } else if (typeof services[i].constructor === 'string') { var def = {}, name = services[i].name; delete services[i].name; def[name] = services[i]; this.container.set(def); } } return this; } } });
namespace('Sy.Kernel'); /** * Framework heart * * @package Sy * @subpackage Kernel * @class */ Sy.Kernel.Core = function () { this.config = new Sy.Configurator(); this.container = new Sy.ServiceContainer('sy::core'); }; Sy.Kernel.Core.prototype = Object.create(Object.prototype, { /** * Return the framework config object * * @return {Sy.Configurator} */ getConfig: { value: function () { return this.config; } }, /** * Return the service container object * * @return {Sy.ServiceContainer} */ getServiceContainer: { value: function () { return this.container; } }, /** * Initiate the kernel that will inspect the app and build necessary data * * @return {Sy.Kernel.Core} */ init: { value: function () { var parser = new Sy.Kernel.AppParser(); this.config.set('parameters.app.meta', { bundles: parser.getBundles(), controllers: parser.getControllers(), entities: parser.getEntities(), viewscreens: parser.getViewScreens() }); this.registerServices(parser.getServices()); } }, /** * Register the app services in the global container * * @param {Array} services * * @return {Sy.Kernel.Core} */ registerServices: { value: function (services) { for (var i = 0, l = services.length; i < l; i++) { if (services[i].creator) { this.container.set( services[i].name, services[i].creator ); } else if (typeof services[i].constructor === 'string') { var name = services[i].name; delete services[i].name; this.container.set( name, services[i] ); } } return this; } } });
JavaScript
0.000001
0ebbea0ac8c1b0f6fe435623ae01549bbab7de55
Set element to play area on task detail on element exist
public/javascripts/app/views/projectManager.js
public/javascripts/app/views/projectManager.js
define([ 'Backbone', //Model 'app/models/project', //Collection 'app/collections/projects', //View 'app/views/taskController', 'app/views/projectsController', 'app/views/filterController', 'app/views/playersController', //Templates 'text!templates/project-page/gamePageTemplate.html', 'text!templates/project-page/errorTemplate.html' ], function( Backbone, //Model Project, //Collection Projects, //Views taskController, projectsController, filterController, playersController, //Templates gamePageTemplate, errorTemplate ){ var ProjectManager = Backbone.View.extend({ template: _.template(gamePageTemplate), errorTemplate: _.template(errorTemplate), model: new Project(), initialize: function(){ this.model.clear({silent: true}).off(); this.model.bind('change:error', this.error, this); this.model.bind('change:name', this.render, this); this.model.fetch({data: {id: this.options.projectId}}); this.players = new playersController({ collection: this.options.players, message: this.options.playerMessage, project: this.model }); this.projectsList = new projectsController({ collection: new Projects(), router: this.options.router }); this.taskList = new taskController({ projectId: this.options.projectId }); this.filter = new filterController({ collection: this.taskList.collection }); }, error: function(){ var message = this.model.get('error'); this.$el.html(this.errorTemplate({message: message})); }, render: function(){ var project = this.model.get('name'); var player = this.options.router.account.get('user'); socket.emit('add player', player, project); this.$el.html(this.template({project: {name: project}})); this.taskList.setElement('.js-taskList'); this.filter.setElement('.fn-filter-task'); this.players.setElement('.js-player-list'); this.players.options.message.trigger('change'); this.taskList.collection.fetch(); this.taskList.taskDetail.setElement('#play-area'); if(!$('.projects-list li')[0]){ this.projectsList.setElement('.projects-list').start(); } } }); return ProjectManager; });
define([ 'Backbone', //Model 'app/models/project', //Collection 'app/collections/projects', //View 'app/views/taskController', 'app/views/projectsController', 'app/views/filterController', 'app/views/playersController', //Templates 'text!templates/project-page/gamePageTemplate.html', 'text!templates/project-page/errorTemplate.html' ], function( Backbone, //Model Project, //Collection Projects, //Views taskController, projectsController, filterController, playersController, //Templates gamePageTemplate, errorTemplate ){ var ProjectManager = Backbone.View.extend({ template: _.template(gamePageTemplate), errorTemplate: _.template(errorTemplate), model: new Project(), initialize: function(){ this.model.clear({silent: true}).off(); this.model.bind('change:error', this.error, this); this.model.bind('change:name', this.render, this); this.model.fetch({data: {id: this.options.projectId}}); this.players = new playersController({ collection: this.options.players, message: this.options.playerMessage, project: this.model }); this.projectsList = new projectsController({ collection: new Projects(), router: this.options.router }); this.taskList = new taskController({ projectId: this.options.projectId }); this.filter = new filterController({ collection: this.taskList.collection }); }, error: function(){ var message = this.model.get('error'); this.$el.html(this.errorTemplate({message: message})); }, render: function(){ var project = this.model.get('name'); var player = this.options.router.account.get('user'); socket.emit('add player', player, project); this.$el.html(this.template({project: {name: project}})); this.taskList.setElement('.js-taskList'); this.filter.setElement('.fn-filter-task'); this.players.setElement('.js-player-list'); this.players.options.message.trigger('change'); this.taskList.collection.fetch(); if(!$('.projects-list li')[0]){ this.projectsList.setElement('.projects-list').start(); } } }); return ProjectManager; });
JavaScript
0
8d8240cb90dd646bbf93ad8139bbadb4ed827b80
Remove double 'data' event on write
src/OrbitClient.js
src/OrbitClient.js
'use strict'; const EventEmitter = require('events').EventEmitter; const async = require('asyncawait/async'); const await = require('asyncawait/await'); const ipfsDaemon = require('orbit-common/lib/ipfs-daemon'); const PubSub = require('./PubSub'); const OrbitDB = require('./OrbitDB'); class OrbitClient { constructor(ipfs, daemon) { this._ipfs = ipfs; this._pubsub = null; this.user = null; this.network = null; this.events = new EventEmitter(); this.db = new OrbitDB(this._ipfs); } channel(channel, password, subscribe) { if(password === undefined) password = ''; if(subscribe === undefined) subscribe = true; this.db.use(channel, this.user, password); this.db.events.on('write', this._onWrite.bind(this)); this.db.events.on('sync', this._onSync.bind(this)); if(subscribe) this._pubsub.subscribe(channel, password, async((channel, message) => this.db.sync(channel, message))); return { iterator: (options) => this._iterator(channel, password, options), delete: () => this.db.deleteChannel(channel, password), del: (key) => this.db.del(channel, password, key), add: (data) => this.db.add(channel, password, data), put: (key, data) => this.db.put(channel, password, key, data), get: (key, options) => { const items = this._iterator(channel, password, { key: key }).collect(); return items[0] ? items[0].value : null; }, leave: () => this._pubsub.unsubscribe(channel) } } disconnect() { this._pubsub.disconnect(); this._store = {}; this.user = null; this.network = null; } _onWrite(channel, hash) { this._pubsub.publish(channel, hash) // this.events.emit('data', channel, hash); } _onSync(channel, hash) { this.events.emit('data', channel, hash); } _iterator(channel, password, options) { const messages = this.db.query(channel, password, options); let currentIndex = 0; let iterator = { [Symbol.iterator]() { return this; }, next() { let item = { value: null, done: true }; if(currentIndex < messages.length) { item = { value: messages[currentIndex], done: false }; currentIndex ++; } return item; }, collect: () => messages } return iterator; } _connect(host, port, username, password, allowOffline) { if(allowOffline === undefined) allowOffline = false; try { this._pubsub = new PubSub(this._ipfs); await(this._pubsub.connect(host, port, username, password)); } catch(e) { if(!allowOffline) throw e; } this.user = { username: username, id: 'TODO: user id' } this.network = { host: host, port: port, name: 'TODO: network name' } } } class OrbitClientFactory { static connect(host, port, username, password, allowOffline, ipfs) { if(!ipfs) { let ipfsd = await(ipfsDaemon()); ipfs = ipfsd.ipfs; } const client = new OrbitClient(ipfs); await(client._connect(host, port, username, password, allowOffline)) return client; } } module.exports = OrbitClientFactory;
'use strict'; const EventEmitter = require('events').EventEmitter; const async = require('asyncawait/async'); const await = require('asyncawait/await'); const ipfsDaemon = require('orbit-common/lib/ipfs-daemon'); const PubSub = require('./PubSub'); const OrbitDB = require('./OrbitDB'); class OrbitClient { constructor(ipfs, daemon) { this._ipfs = ipfs; this._pubsub = null; this.user = null; this.network = null; this.events = new EventEmitter(); this.db = new OrbitDB(this._ipfs); } channel(channel, password, subscribe) { if(password === undefined) password = ''; if(subscribe === undefined) subscribe = true; this.db.use(channel, this.user, password); this.db.events.on('write', this._onWrite.bind(this)); this.db.events.on('sync', this._onSync.bind(this)); if(subscribe) this._pubsub.subscribe(channel, password, async((channel, message) => this.db.sync(channel, message))); return { iterator: (options) => this._iterator(channel, password, options), delete: () => this.db.deleteChannel(channel, password), del: (key) => this.db.del(channel, password, key), add: (data) => this.db.add(channel, password, data), put: (key, data) => this.db.put(channel, password, key, data), get: (key, options) => { const items = this._iterator(channel, password, { key: key }).collect(); return items[0] ? items[0].value : null; }, leave: () => this._pubsub.unsubscribe(channel) } } disconnect() { this._pubsub.disconnect(); this._store = {}; this.user = null; this.network = null; } _onWrite(channel, hash) { this._pubsub.publish(channel, hash) this.events.emit('data', channel, hash); } _onSync(channel, hash) { this.events.emit('data', channel, hash); } _iterator(channel, password, options) { const messages = this.db.query(channel, password, options); let currentIndex = 0; let iterator = { [Symbol.iterator]() { return this; }, next() { let item = { value: null, done: true }; if(currentIndex < messages.length) { item = { value: messages[currentIndex], done: false }; currentIndex ++; } return item; }, collect: () => messages } return iterator; } _connect(host, port, username, password, allowOffline) { if(allowOffline === undefined) allowOffline = false; try { this._pubsub = new PubSub(this._ipfs); await(this._pubsub.connect(host, port, username, password)); } catch(e) { if(!allowOffline) throw e; } this.user = { username: username, id: 'TODO: user id' } this.network = { host: host, port: port, name: 'TODO: network name' } } } class OrbitClientFactory { static connect(host, port, username, password, allowOffline, ipfs) { if(!ipfs) { let ipfsd = await(ipfsDaemon()); ipfs = ipfsd.ipfs; } const client = new OrbitClient(ipfs); await(client._connect(host, port, username, password, allowOffline)) return client; } } module.exports = OrbitClientFactory;
JavaScript
0.002583
a01ef325285fdc4f34972c3aa9cc9e0f377f1cff
Update ember-qunit to 0.4.2.
blueprints/ember-cli-qunit/index.js
blueprints/ember-cli-qunit/index.js
module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { return this.addBowerPackagesToProject([ { name: 'qunit', target: '~1.17.1' }, { name: 'ember-cli/ember-cli-test-loader', target: '0.1.3' }, { name: 'ember-qunit-notifications', target: '0.0.7' }, { name: 'ember-qunit', target: '0.4.2' } ]); } };
module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { return this.addBowerPackagesToProject([ { name: 'qunit', target: '~1.17.1' }, { name: 'ember-cli/ember-cli-test-loader', target: '0.1.3' }, { name: 'ember-qunit-notifications', target: '0.0.7' }, { name: 'ember-qunit', target: '0.4.1' } ]); } };
JavaScript
0
ae349eeeb5a5cbd22f6050e3cb1b105ea90bf49a
add the ability to bootstrap an app with no account
blueprints/ember-pagefront/index.js
blueprints/ember-pagefront/index.js
var Promise = require('ember-cli/lib/ext/promise'); var chalk = require('chalk'); var appendFileSync = require('fs').appendFileSync; var API = require('ember-cli-deploy-pagefront/lib/api'); var green = chalk.green; var white = chalk.white; var DEPLOY = 'ember deploy production'; var NEW_LINE = '\n'; var SUCCESS = NEW_LINE + green('Success! Now deploy your app: ') + white(DEPLOY) + NEW_LINE; var COMMAND= '`ember g ember-pagefront --app=YOUR_APP_NAME`'; var MISSING_APP = 'No app was specified. Please run ' + COMMAND + ' to finish setting up.'; var APP_TAKEN = 'Darn. That app name has already been taken. Try again with a new name: ' + COMMAND; var BOOTSTRAP_FAILED = 'Whoops. Something went wrong. Try again: ' + COMMAND; var GITIGNORE = '.gitignore'; var DOT_ENV_FILE = '.env.deploy.*'; var ECD = 'ember-cli-deploy'; var ECD_VERSION = '0.5.1'; var UNPROCESSABLE = 422; function bootstrap(app) { var api = new API(); return api.bootstrapApp({ app: app }); } module.exports = { availableOptions: [ { name: 'app', type: String }, { name: 'key', type: String } ], normalizeEntityName: function() {}, locals: function(options) { return { app: options.app, key: options.key }; }, beforeInstall: function(options, locals) { if (!options.app) { return Promise.reject(MISSING_APP); } if (!options.key) { return bootstrap(options.app).then(function(response) { locals.key = response.key; }, function(response) { if (response.statusCode === UNPROCESSABLE) { throw APP_TAKEN; } else { throw BOOTSTRAP_FAILED } }); } }, afterInstall: function() { var success = this.didSucceed.bind(this); appendFileSync(GITIGNORE, NEW_LINE + DOT_ENV_FILE + NEW_LINE); return this.addPackageToProject(ECD, ECD_VERSION).then(success); }, didSucceed: function() { this.ui.writeLine(SUCCESS); } }
var chalk = require('chalk'); var appendFileSync = require('fs').appendFileSync; var green = chalk.green; var white = chalk.white; var DEPLOY = 'ember deploy production'; var NEW_LINE = '\n'; var MESSAGE = NEW_LINE + green('Success! Now deploy your app: ') + white(DEPLOY) + NEW_LINE; var GITIGNORE = '.gitignore'; var DOT_ENV_FILE = '.env.deploy.*'; module.exports = { normalizeEntityName: function() {}, beforeInstall: function() { return this.addPackageToProject('ember-cli-deploy', '0.5.1'); }, afterInstall: function() { appendFileSync(GITIGNORE, NEW_LINE + DOT_ENV_FILE + NEW_LINE); this.ui.writeLine(MESSAGE); }, locals: function(options) { return { app: options.app, key: options.key }; } }
JavaScript
0.000001
e93b6596dcd9a0b4d16248a106daa586780d2b8c
update passport local strategy to fetch actual user via sql query
config/passport.js
config/passport.js
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const db = require('./database'); const { query } = require('../utils'); passport.use(new LocalStrategy({ usernameField: 'identifier' }, async (idenfier, password, done) => { const getUserWithCredentialsQuery = await query('05-get-user-with-credentials.sql', { identifier, password }); const users = await db.query(getUserWithCredentialsQuery); if (users.rows.length > 0) { const user = users.row[0]; user.avatar = 'static/images/default-avatar.png'; done(null, user); } else { done(null, new Error('User not found.')); } })); passport.serializeUser((user, done) => { done(null, user.email); }); passport.deserializeUser(async (email, done) => { const getUsersWithEmailQuery = await query('03-get-users-with-email.sql', { email }); const users = await db.query(getUsersWithEmailQuery); if (users.rows.length > 0) { const user = users.rows[0]; user.avatar = 'static/images/default-avatar.png'; done(null, users.rows[0]); } else { done(null, new Error('User not found.')); } }); module.exports = passport;
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const db = require('./database'); const { query } = require('../utils'); passport.use(new LocalStrategy({ usernameField: 'identifier' }, (username, password, done) => { const user = { fullname: 'Arnelle Balane', username: 'arnellebalane', email: 'arnellebalane@gmail.com', avatar: 'static/images/default-avatar.png' }; done(null, user); })); passport.serializeUser((user, done) => { done(null, user.email); }); passport.deserializeUser(async (email, done) => { const getUsersWithEmailQuery = await query('03-get-users-with-email.sql', { email }); const users = await db.query(getUsersWithEmailQuery); if (users.rows.length > 0) { const user = users.rows[0]; user.avatar = 'static/images/default-avatar.png'; done(null, users.rows[0]); } else { done(null, new Error('User not found.')); } }); module.exports = passport;
JavaScript
0
99320746931af6f7b5da58aed7f211f85bfc3673
add style changing support
ui/app.js
ui/app.js
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); // XXX use a module for this function loadHash() { var hash = window.location.hash; if (hash && hash[0] === '#') hash = hash.slice(1); var parts = hash.split(';'); var out = {}; parts.forEach(function(part) { var i = part.indexOf('='); if (i === -1) { out[part] = true; } else { var key = part.slice(0, i); var val = part.slice(i + 1); out[key] = val; } }); return out; } var Hash = loadHash(); var style = Hash.style || 'light'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style-' + style + '.css' })); //// var PhraseData = require('./data'); var Engine = require('./engine'); var PhrasePrompt = require('./phrase_prompt'); var eng = new Engine({ complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var prompt = new PhrasePrompt({ generatePhrase: PhraseData.generatePhrase, displayTime: 1500, inputTime: 10000, maxErrorPerWord: 1, repromptDelay: 200, complexity: eng.complexity }); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); prompt.on('stopkey', function(event) { if (event.keyCode === 0x1b) ss.stop(); }); ss.on('start', prompt.start.bind(prompt)); ss.on('stop', prompt.stop.bind(prompt)); ss.on('keypress', function(event) { if (prompt.inputing) return; var char = String.fromCharCode(event.charCode); if (char !== prompt.expected[0]) return; event.stopPropagation(); event.preventDefault(); prompt.showInput(); prompt.inputElement.value = char; prompt.updateInput(); }); ss.addListeners(window); prompt.on('result', eng.onResult.bind(eng)); eng.on('idle', ss.stop.bind(ss));
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); //// var PhraseData = require('./data'); var Engine = require('./engine'); var PhrasePrompt = require('./phrase_prompt'); var eng = new Engine({ complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var prompt = new PhrasePrompt({ generatePhrase: PhraseData.generatePhrase, displayTime: 1500, inputTime: 10000, maxErrorPerWord: 1, repromptDelay: 200, complexity: eng.complexity }); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); prompt.on('stopkey', function(event) { if (event.keyCode === 0x1b) ss.stop(); }); ss.on('start', prompt.start.bind(prompt)); ss.on('stop', prompt.stop.bind(prompt)); ss.on('keypress', function(event) { if (prompt.inputing) return; var char = String.fromCharCode(event.charCode); if (char !== prompt.expected[0]) return; event.stopPropagation(); event.preventDefault(); prompt.showInput(); prompt.inputElement.value = char; prompt.updateInput(); }); ss.addListeners(window); prompt.on('result', eng.onResult.bind(eng)); eng.on('idle', ss.stop.bind(ss));
JavaScript
0.000003
46b9e204203d7ce33cb99630c8a19d1e8d29231b
make maxErrorPerWord and repromptDelay defaults explicit
ui/app.js
ui/app.js
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); //// var fs = require('fs'); var Markov = require('../lib/markov'); var markov = Markov.load(JSON.parse(fs.readFileSync('markov_source.json'))); function generatePhrase(numPhrases, minLength) { var phrase = ''; while (phrase.length < minLength) { phrase = markov.chain(numPhrases).join(' '); } return phrase.toLowerCase(); } var PhrasePrompt = require('./phrase_prompt'); var prompt = new PhrasePrompt({ generatePhrase: generatePhrase, displayTime: 1500, inputTime: 10000, maxErrorPerWord: 2, repromptDelay: 200, complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var PromptLoop = require('./prompt_loop'); var loop = new PromptLoop(prompt); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); var history = []; function onResult(result) { // TODO: prune and/or archive history? history.push(result); var k = 3; // TODO setting var lastK = history.slice(-k); var lastKExpired = lastK .reduce(function(allExpired, result) { return allExpired && Boolean(result.expired); }, lastK.length >= k); if (lastKExpired) return ss.stop(); console.log(result); } ss.on('start', loop.start.bind(loop)); ss.on('stop', loop.stop.bind(loop)); ss.addListeners(window); prompt.on('result', onResult);
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); //// var fs = require('fs'); var Markov = require('../lib/markov'); var markov = Markov.load(JSON.parse(fs.readFileSync('markov_source.json'))); function generatePhrase(numPhrases, minLength) { var phrase = ''; while (phrase.length < minLength) { phrase = markov.chain(numPhrases).join(' '); } return phrase.toLowerCase(); } var PhrasePrompt = require('./phrase_prompt'); var prompt = new PhrasePrompt({ generatePhrase: generatePhrase, displayTime: 1500, inputTime: 10000, complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var PromptLoop = require('./prompt_loop'); var loop = new PromptLoop(prompt); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); var history = []; function onResult(result) { // TODO: prune and/or archive history? history.push(result); var k = 3; // TODO setting var lastK = history.slice(-k); var lastKExpired = lastK .reduce(function(allExpired, result) { return allExpired && Boolean(result.expired); }, lastK.length >= k); if (lastKExpired) return ss.stop(); console.log(result); } ss.on('start', loop.start.bind(loop)); ss.on('stop', loop.stop.bind(loop)); ss.addListeners(window); prompt.on('result', onResult);
JavaScript
0.000001
6a5f92d6d72c8cbe1e15f377de8b377bca79ff30
fix csp modification
chrome-extension/background.js
chrome-extension/background.js
/** * The default content security policy for github.com only allows AJAX posts to white-listed domains. * In order to allow us to post to our server, we intercept the content-security-policy header and whitelist our domain. */ chrome.webRequest.onHeadersReceived.addListener(function(details) { for(var i = 0; i < details.responseHeaders.length; ++i) { if (details.responseHeaders[i].name.toLowerCase() == 'content-security-policy') { console.log("Amending content-security-policy for " + details.url) var csp = details.responseHeaders[i].value; csp = csp.replace('connect-src', 'connect-src whaler-on-fleek.appspot.com'); details.responseHeaders[i].value = csp; } } return {responseHeaders:details.responseHeaders}; }, { urls: [ '*://github.com/*/pull/*' ] }, [ 'blocking', 'responseHeaders' ]); /** * Randomly generates a 24 character string. */ function getRandomToken() { var array = new Uint32Array(10); window.crypto.getRandomValues(array); var text = ""; for (var i = 0; i < array.length; i++) { text += intToChar(array[i] & 255) text += intToChar((array[i] >> 8 ) & 255) text += intToChar((array[i] >> 16) & 255) text += intToChar((array[i] >> 24) & 255) } return text; } function intToChar(input) { var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return possible.charAt(input % possible.length) } /** * Responds to messages posted by the content script. */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.message != "get_session_token") return false; chrome.cookies.get({"url": "https://github.com", "name": "whaler_session"}, function(cookie) { if (cookie == null) { session_id = getRandomToken(); expirationDate = new Date().getTime() / 1000 + 60 * 60 * 24 * 7 // Expire in 1 week chrome.cookies.set({"url": "https://github.com", "name": "whaler_session", "value": session_id, "expirationDate": expirationDate, "secure": true}) } else { session_id = cookie.value } sendResponse({session_token: session_id}); }); return true; // We will respond asynchronously. });
/** * The default content security policy for github.com only allows AJAX posts to white-listed domains. * In order to allow us to post to our server, we intercept the content-security-policy header and whitelist our domain. */ chrome.webRequest.onHeadersReceived.addListener(function(details) { for(var i = 0; i < details.responseHeaders.length; ++i) { if (details.responseHeaders[i].name.toLowerCase() == 'content-security-policy') { console.log("Amending content-security-policy for " + details.url) details.responseHeaders[i].value += " whaler-on-fleek.appspot.com" } } return {responseHeaders:details.responseHeaders}; }, { urls: [ '*://github.com/*/pull/*' ] }, [ 'blocking', 'responseHeaders' ]); /** * Randomly generates a 24 character string. */ function getRandomToken() { var array = new Uint32Array(10); window.crypto.getRandomValues(array); var text = ""; for (var i = 0; i < array.length; i++) { text += intToChar(array[i] & 255) text += intToChar((array[i] >> 8 ) & 255) text += intToChar((array[i] >> 16) & 255) text += intToChar((array[i] >> 24) & 255) } return text; } function intToChar(input) { var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return possible.charAt(input % possible.length) } /** * Responds to messages posted by the content script. */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.message != "get_session_token") return false; chrome.cookies.get({"url": "https://github.com", "name": "whaler_session"}, function(cookie) { if (cookie == null) { session_id = getRandomToken(); expirationDate = new Date().getTime() / 1000 + 60 * 60 * 24 * 7 // Expire in 1 week chrome.cookies.set({"url": "https://github.com", "name": "whaler_session", "value": session_id, "expirationDate": expirationDate, "secure": true}) } else { session_id = cookie.value } sendResponse({session_token: session_id}); }); return true; // We will respond asynchronously. });
JavaScript
0
7025074c082adc146b8b7b9a6db745d0be7d613f
Fix stdin processing
bf/index.js
bf/index.js
var Evaluator = require('./evaluator'); var unescape = function unescape(value){ return String(value) .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); } module.exports = function(argv, channel, response, logger) { var input = unescape(argv.slice(1).join('')), inputSplit = input.split(/\"/g); code = inputSplit[0], stdin = (inputSplit[1] || '').split('').map(function(c) { return c.charCodeAt(0); }); logger.log('evaluating', code); try { result = ''; Evaluator.bfEval(code, { input: function() { return stdin.shift() || 0; }, output: function(value) { result += String.fromCharCode(value); } }); response.end(result || 'Program produced no output'); } catch(e) { logger.error(e); response.end('Invalid BF program'); } };
var Evaluator = require('./evaluator'); var unescape = function unescape(value){ return String(value) .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); } module.exports = function(argv, channel, response, logger) { var input = unescape(argv.slice(1).join('')), inputSplit = input.split(/\"/g); code = inputSplit[0], stdin = inputSplit[1].split('').map(function(c) { return c.charCodeAt(0); }); logger.log('evaluating', code); try { result = ''; Evaluator.bfEval(code, { input: function() { return stdin.shift() || 0; }, output: function(value) { result += String.fromCharCode(value); } }); response.end(result || 'Program produced no output'); } catch(e) { logger.error(e); response.end('Invalid BF program'); } };
JavaScript
0.000087
d113834c865f6ef9a5e94c9824d09e4e1742b983
Fix unnamed function ESLint warning
jest.shim.js
jest.shim.js
if (!global.requestAnimationFrame) { global.requestAnimationFrame = function requestAnimationFrame(callback) { setTimeout(callback, 0); }; }
if (!global.requestAnimationFrame) { global.requestAnimationFrame = function(callback) { setTimeout(callback, 0); }; }
JavaScript
0.999617
3dfdc465212392c3f137377e7831eeff4147bf50
Update player when width or height changes
src/ReactPlayer.js
src/ReactPlayer.js
import 'es6-promise' import React, { Component } from 'react' import { propTypes, defaultProps } from './props' import players from './players' export default class ReactPlayer extends Component { static displayName = 'ReactPlayer' static propTypes = propTypes static defaultProps = defaultProps static canPlay (url) { return players.some(player => player.canPlay(url)) } componentDidMount () { this.progress() } componentWillUnmount () { clearTimeout(this.progressTimeout) } shouldComponentUpdate (nextProps) { return ( this.props.url !== nextProps.url || this.props.playing !== nextProps.playing || this.props.volume !== nextProps.volume || this.props.height !== nextProps.height || this.props.width !== nextProps.width ) } seekTo = fraction => { const player = this.refs.player if (player) { player.seekTo(fraction) } } progress = () => { if (this.props.url && this.refs.player) { const loaded = this.refs.player.getFractionLoaded() const played = this.refs.player.getFractionPlayed() if (loaded || played) { this.props.onProgress({ loaded, played }) } } this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency) } renderPlayer = Player => { const active = Player.canPlay(this.props.url) const { youtubeConfig, soundcloudConfig, vimeoConfig, fileConfig, ...activeProps } = this.props const props = active ? { ...activeProps, ref: 'player' } : {} return ( <Player key={Player.displayName} youtubeConfig={youtubeConfig} soundcloudConfig={soundcloudConfig} vimeoConfig={vimeoConfig} fileConfig={fileConfig} {...props} /> ) } render () { const style = { width: this.props.width, height: this.props.height } return ( <div style={style} className={this.props.className}> {players.map(this.renderPlayer)} </div> ) } }
import 'es6-promise' import React, { Component } from 'react' import { propTypes, defaultProps } from './props' import players from './players' export default class ReactPlayer extends Component { static displayName = 'ReactPlayer' static propTypes = propTypes static defaultProps = defaultProps static canPlay (url) { return players.some(player => player.canPlay(url)) } componentDidMount () { this.progress() } componentWillUnmount () { clearTimeout(this.progressTimeout) } shouldComponentUpdate (nextProps) { return ( this.props.url !== nextProps.url || this.props.playing !== nextProps.playing || this.props.volume !== nextProps.volume ) } seekTo = fraction => { const player = this.refs.player if (player) { player.seekTo(fraction) } } progress = () => { if (this.props.url && this.refs.player) { let progress = {} const loaded = this.refs.player.getFractionLoaded() const played = this.refs.player.getFractionPlayed() if (loaded !== null && loaded !== this.prevLoaded) { progress.loaded = this.prevLoaded = loaded } if (played !== null && played !== this.prevPlayed && this.props.playing) { progress.played = this.prevPlayed = played } if (progress.loaded || progress.played) { this.props.onProgress(progress) } } this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency) } renderPlayer = Player => { const active = Player.canPlay(this.props.url) const { youtubeConfig, soundcloudConfig, vimeoConfig, fileConfig, ...activeProps } = this.props const props = active ? { ...activeProps, ref: 'player' } : {} return ( <Player key={Player.displayName} youtubeConfig={youtubeConfig} soundcloudConfig={soundcloudConfig} vimeoConfig={vimeoConfig} fileConfig={fileConfig} {...props} /> ) } render () { const style = { width: this.props.width, height: this.props.height } return ( <div style={style} className={this.props.className}> {players.map(this.renderPlayer)} </div> ) } }
JavaScript
0
27f918f76634d500fe2856a61d93741a8db5e487
update tests
frontend/test/unit/specs/people/OrganizationAdd.spec.js
frontend/test/unit/specs/people/OrganizationAdd.spec.js
import { shallow, createLocalVue } from '@vue/test-utils' import Vuex from 'vuex' import OrganizationAdd from '@/registry/components/people/OrganizationAdd.vue' const localVue = createLocalVue() localVue.use(Vuex) describe('OrganizationAdd.vue', () => { let store let getters let mutations let actions beforeEach(() => { getters = { error: () => null } store = new Vuex.Store({ getters, actions, mutations }) }) it('has a title', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) expect(wrapper.find('h5.modal-title').text()).toEqual('Add a Company') }) it('form has a reset button that clears fields', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) wrapper.vm.orgForm.name = 'Big Drilling Co' expect(wrapper.vm.orgForm.name).toEqual('Big Drilling Co') wrapper.find('#orgFormResetButton').trigger('reset') expect(wrapper.vm.orgForm.name).toEqual('') }) })
import { shallow, createLocalVue } from '@vue/test-utils' import Vuex from 'vuex' import OrganizationAdd from '@/registry/components/people/OrganizationAdd.vue' const localVue = createLocalVue() localVue.use(Vuex) describe('OrganizationAdd.vue', () => { let store let getters let mutations let actions beforeEach(() => { getters = { error: () => null } store = new Vuex.Store({ getters, actions, mutations }) }) it('has a title', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) expect(wrapper.find('h5.modal-title').text()).toEqual('Add an Organization') }) it('form has a reset button that clears fields', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) wrapper.vm.orgForm.name = 'Big Drilling Co' expect(wrapper.vm.orgForm.name).toEqual('Big Drilling Co') wrapper.find('#orgFormResetButton').trigger('reset') expect(wrapper.vm.orgForm.name).toEqual('') }) })
JavaScript
0.000001
ec2e279626ed62572843f92cc872d4ed0d4eb7eb
Update SetState.js
routes/redis/SetState.js
routes/redis/SetState.js
/** * Created by Kun on 6/28/2015. */ //http://www.sitepoint.com/using-redis-node-js/ var express = require("express"); var Q = require('q'); var router = express.Router(); impredis = require("../../imp_services/impredis.js"); //TODO Make sure navigation object stringifies and parses stateObject request and response router.route('/:stateObject').get(function(req, res) { impredis.set(req.cookies.IMPId, "stateObject",req.params.stateObject,function(result, error){ if(error){ res.send("error: " + error); } else{ res.send("Success"); } }) }); module.exports = router;
/** * Created by Kun on 6/28/2015. */ //http://www.sitepoint.com/using-redis-node-js/ var express = require("express"); var Q = require('q'); var router = express.Router(); impredis = require("../../imp_services/impredis.js"); router.route('/:stateObject').get(function(req, res) { impredis.set(req.cookies.IMPId, "stateObject",req.params.stateObject,function(result, error){ if(error){ res.send("error: " + error); } else{ res.send("Success"); } }) }); module.exports = router;
JavaScript
0.000001
c5fb340fa27ae0b163fbb46fc4481db5598e7c0b
Use consistent method
lib/node_modules/@stdlib/math/base/special/uimuldw/test/test.js
lib/node_modules/@stdlib/math/base/special/uimuldw/test/test.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var uimuldw = require( './../lib' ); // FIXTURES // var data = require( './fixtures/c/data.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof uimuldw, 'function', 'main export is a function' ); t.end(); }); tape( 'the function returns `NaN` if provided `NaN`', function test( t ) { var v; v = uimuldw( NaN, 1 ); t.strictEqual( isnan( v ), true, 'returns expected value' ); v = uimuldw( 1, NaN ); t.strictEqual( isnan( v ), true, 'returns expected value' ); v = uimuldw( NaN, NaN ); t.strictEqual( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'the function computes the double word product of two (unsigned) words', function test( t ) { var expected; var actual; var a; var b; var i; a = data.a; b = data.b; expected = data.expected; for ( i = 0; i < expected.length; i++ ) { actual = uimuldw( a[ i ], b[ i ] ); t.deepEqual( actual, expected[ i ], 'returns expected value. a: '+a[i]+'. b: '+b[i]+'. expected: ['+expected[i].join(',')+']'); } t.end(); });
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var uimuldw = require( './../lib' ); // FIXTURES // var data = require( './fixtures/c/data.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof uimuldw, 'function', 'main export is a function' ); t.end(); }); tape( 'the function returns `NaN` if provided `NaN`', function test( t ) { var v; v = uimuldw( NaN, 1 ); t.equal( isnan( v ), true, 'returns expected value' ); v = uimuldw( 1, NaN ); t.equal( isnan( v ), true, 'returns expected value' ); v = uimuldw( NaN, NaN ); t.equal( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'the function computes the doubleword product of two words, unsigned', function test( t ) { var expected; var actual; var a; var b; var i; a = data.a; b = data.b; expected = data.expected; for ( i = 0; i < expected.length; i++ ) { actual = uimuldw( a[ i ], b[ i ] ); t.deepEqual( actual, expected[ i ], 'returns expected value. a: '+a[i]+'. b: '+b[i]+'. expected: ['+expected[i].join(',')+']'); } t.end(); });
JavaScript
0.000072
77ef3c180f6bd8f06b357cefd8e2142164cf3618
add item spec
client/js/components/assessments/item.spec.js
client/js/components/assessments/item.spec.js
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react/lib/ReactTestUtils'; import Item from './item'; fdescribe('item', function() { var question = { title:"Test Question Title" }; var checkedResponse = {}; var currentItemIndex = 0; var assessment = {}; var questionCount = 10; var result; var subject; var renderItem = () => { result = TestUtils.renderIntoDocument(<Item question={question} checkedResponse={checkedResponse} currentItemIndex={currentItemIndex} questionCount={questionCount} assessment={assessment} />); subject = ReactDOM.findDOMNode(result); }; // Reset variables to default and render an item beforeEach(() => { question = { title:"Test Question Title" }; currentItemIndex = 0; assessment = {}; questionCount = 10; renderItem(); }); it('renders an item', () => { expect(subject.textContent).toContain("Test Question Title"); }); describe('feedback', () => { it('renders correct when item is correct', () => { checkedResponse = {correct:true, feedback:'Correct answer'}; renderItem(); expect(subject.textContent).toContain("Correct"); expect(subject.textContent).toContain("Correct answer"); expect(subject.textContent).not.toContain("Incorrect"); expect(subject.textContent).not.toContain("Incorrect answer"); }); it('renders incorrect when item is incorrect', () => { checkedResponse = {correct:false, feedback:'Incorrect answer'}; renderItem(); expect(subject.textContent).toContain("Incorrect"); expect(subject.textContent).toContain("Incorrect answer"); expect(subject.textContent).not.toContain("Correct"); expect(subject.textContent).not.toContain("Correct answer"); }); it('renders without feedback when item is unchecked', () => { checkedResponse = {}; renderItem(); expect(subject.textContent).not.toContain("Incorrect"); expect(subject.textContent).not.toContain("incorrect answer"); expect(subject.textContent).not.toContain("Correct"); expect(subject.textContent).not.toContain("Correct answer"); }); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react/lib/ReactTestUtils'; import Item from './item'; describe('item', function() { var question = { title:"Test Question Title" }; var currentItemIndex = 0; var assessmentKind = "SUMMATIVE"; var assessment = {}; var questionCount = 10; var nextQuestion = () => {}; var previousQuestion = () => {}; var submitAssessment = () => {}; var result; var subject; var renderItem = () => { result = TestUtils.renderIntoDocument(<Item question={question} currentItemIndex={currentItemIndex} questionCount={questionCount} assessment={assessment} nextQuestion = {nextQuestion} prevQuestion = {previousQuestion} submitAssessment = {submitAssessment} assessment_kind={assessmentKind} />); subject = ReactDOM.findDOMNode(result); }; // Reset variables to default and render an item beforeEach(() => { question = { title:"Test Question Title" }; currentItemIndex = 0; assessmentKind = "SUMMATIVE"; assessment = {}; questionCount = 10; nextQuestion = () => {}; previousQuestion = () => {}; submitAssessment = () => {}; renderItem(); }); it('renders an item', () => { expect(subject.textContent).toContain("Test Question Title"); }); });
JavaScript
0
ce2317029178c6b07c79fb9c5be83a6ead953bd1
tag v0.5.0-beta3
client/js/ng-controllers/versionController.js
client/js/ng-controllers/versionController.js
mainModule.controller('versionController', function($scope, $routeParams, $location, defaultFactory) { // nText app by Dan McKeown | http://danmckeown.info/code/ntext $scope.nVersion = "0.5.0-beta3"; // This is the app version number });
mainModule.controller('versionController', function($scope, $routeParams, $location, defaultFactory) { // nText app by Dan McKeown | http://danmckeown.info/code/ntext $scope.nVersion = "0.5.0-beta3-dev"; // This is the app version number });
JavaScript
0.000001
f9ae2c2f1c6d46b0a7e3c07df2a965ba6e9ba2dc
fix example
examples/a.js
examples/a.js
"use strict"; var _ = require("lodash"); var ChangeLog = require(".."); var properChange = "openstack (0.99.18-0ubuntu1~14.04.1~bleed1) trusty; urgency=medium\n\n" + " * Fix nclxd\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 25 Jun 2015 10:25:15 -0400\n\n" + "openstack (0.99.17-0ubuntu1~15.10.1~bleed1) wily; urgency=medium\n\n" + " * Fix typo in deploy command\n" + " * Upgrade juju compat\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Fri, 19 Jun 2015 17:01:14 -0400"; // var nonSemVerChange = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400\n\nmacumba (0.5-0ubuntu1) utopic; urgency=medium\n\n * Fix annotations\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Mon, 06 Oct 2014 11:52:49 -0400\n\nmacumba (0.3-0ubuntu1) utopic; urgency=medium\n\n * Add macumba-shell for interactively working with API\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Wed, 20 Aug 2014 12:41:16 -0400\n\nmacumba (0.2-0ubuntu1) utopic; urgency=medium\n\n * better exception handling\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 07 Aug 2014 01:25:49 +0200\n\nmacumba (0.1-0ubuntu1) utopic; urgency=low\n\n * Initial Release\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Tue, 08 Jul 2014 13:26:37 -0500\n"; // var logMultipleBody = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n Spans additional line\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400"; var svl = new ChangeLog(properChange); var logs = svl.splitLogs(); var log = _.first(logs); console.log("\n\nInput:"); console.log(log); console.log("Result:"); var model = svl.parse(log); console.log(model);
"use strict"; var _ = require("lodash"); var ChangeLog = require("."); var properChange = "openstack (0.99.18-0ubuntu1~14.04.1~bleed1) trusty; urgency=medium\n\n" + " * Fix nclxd\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 25 Jun 2015 10:25:15 -0400\n\n" + "openstack (0.99.17-0ubuntu1~15.10.1~bleed1) wily; urgency=medium\n\n" + " * Fix typo in deploy command\n" + " * Upgrade juju compat\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Fri, 19 Jun 2015 17:01:14 -0400"; // var nonSemVerChange = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400\n\nmacumba (0.5-0ubuntu1) utopic; urgency=medium\n\n * Fix annotations\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Mon, 06 Oct 2014 11:52:49 -0400\n\nmacumba (0.3-0ubuntu1) utopic; urgency=medium\n\n * Add macumba-shell for interactively working with API\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Wed, 20 Aug 2014 12:41:16 -0400\n\nmacumba (0.2-0ubuntu1) utopic; urgency=medium\n\n * better exception handling\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 07 Aug 2014 01:25:49 +0200\n\nmacumba (0.1-0ubuntu1) utopic; urgency=low\n\n * Initial Release\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Tue, 08 Jul 2014 13:26:37 -0500\n"; // var logMultipleBody = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n Spans additional line\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400"; var svl = new ChangeLog(properChange); var logs = svl.splitLogs(); var log = _.first(logs); console.log("\n\nInput:"); console.log(log); console.log("Result:"); var model = svl.parse(log); console.log(model);
JavaScript
0
6be0e405f35f06d4cc48e483a621b0d96d3bb1d7
Fix change type typos
test/unit/remote/change.js
test/unit/remote/change.js
const {describe, it} = require('mocha') const remoteChange = require('../../../core/remote/change') describe('remote change sort', () => { it('sort correctly move inside move', () => { const parent = { 'doc': {'path': 'parent/dst/dir'}, 'type': 'FolderMove', 'was': {'path': 'parent/src/dir'} } const child = { 'doc': {'path': 'parent/dst/dir/subdir/filerenamed'}, 'type': 'FileMove', 'was': {'path': 'parent/dst/dir/subdir/file'} } const a = [child, parent] remoteChange.sort(a) a.should.deepEqual([parent, child]) }) })
const {describe, it} = require('mocha') const remoteChange = require('../../../core/remote/change') describe('remote change sort', () => { it('sort correctly move inside move', () => { const parent = { 'doc': {'path': 'parent/dst/dir'}, 'type': 'FolderMoved', 'was': {'path': 'parent/src/dir'} } const child = { 'doc': {'path': 'parent/dst/dir/subdir/filerenamed'}, 'type': 'FileMoved', 'was': {'path': 'parent/dst/dir/subdir/file'} } const a = [child, parent] remoteChange.sort(a) a.should.deepEqual([parent, child]) }) })
JavaScript
0.000001
36ee0b25ccc81d60a52ed79e8f57c974e4a936ab
add new middlewares distinct on content range
ressources/middlewares.js
ressources/middlewares.js
var passport = require('passport'); require('./oauth.js')(passport); module.exports = { delete: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } }, list: { fetch: { before: function (req, res, context) { context.options = context.options || {}; context.options.distinct = true; return context.continue; } } }, create: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } } }; // SCOPE VS context.criteria();
var passport = require('passport'); require('./oauth.js')(passport); module.exports = { delete: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } }, create: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } } }; // SCOPE VS context.criteria();
JavaScript
0
53d5700946baba9d535cc4493f6bcd8e6b52e9a7
Add view-header element for settings view
client/src/js/settings/components/Settings.js
client/src/js/settings/components/Settings.js
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import React from "react"; import { connect } from "react-redux"; import { withRouter, Switch, Redirect, Route } from "react-router-dom"; import { Nav, NavItem } from "react-bootstrap"; import { LinkContainer } from "react-router-bootstrap"; import SourceTypes from "./General/SourceTypes"; import InternalControl from "./General/InternalControl"; import UniqueNames from "./General/UniqueNames"; import SamplePermissions from "./General/SamplePermissions"; import HTTP from "./Server/HTTP"; import SSL from "./Server/SSL"; import Data from "./Data"; import Resources from "./Jobs/Resources"; import Tasks from "./Jobs/Tasks"; import Users from "../users/components/Users"; const General = () => ( <div> <SourceTypes /> <InternalControl /> <UniqueNames /> <SamplePermissions /> </div> ); const Server = () => ( <div> <HTTP /> <SSL /> </div> ); const Jobs = () => ( <div> <Resources /> <Tasks /> </div> ); const Settings = () => { return ( <div className="container"> <h3 className="view-header"> <strong> Settings </strong> </h3> <Nav bsStyle="tabs"> <LinkContainer to="/settings/general"> <NavItem>General</NavItem> </LinkContainer> <LinkContainer to="/settings/server"> <NavItem>Server</NavItem> </LinkContainer> <LinkContainer to="/settings/data"> <NavItem>Data</NavItem> </LinkContainer> <LinkContainer to="/settings/jobs"> <NavItem>Jobs</NavItem> </LinkContainer> <LinkContainer to="/settings/users"> <NavItem>Users</NavItem> </LinkContainer> </Nav> <Switch> <Redirect from="/settings" to="/settings/general" exact /> <Route path="/settings/general" component={General} /> <Route path="/settings/server" component={Server} /> <Route path="/settings/data" component={Data} /> <Route path="/settings/jobs" component={Jobs} /> <Route path="/settings/users" component={Users} /> </Switch> </div> ); }; Settings.propTypes = { source_types: React.PropTypes.object, get: React.PropTypes.func }; const mapStateToProps = (state) => { return { restrictSourceTypes: state.settings.data.restrict_source_types, allowedSourceTypes: state.settings.data.allowed_source_types }; }; const SettingsContainer = withRouter(connect( mapStateToProps )(Settings)); export default SettingsContainer;
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import React from "react"; import { connect } from "react-redux"; import { withRouter, Switch, Redirect, Route } from "react-router-dom"; import { Nav, NavItem } from "react-bootstrap"; import { LinkContainer } from "react-router-bootstrap"; import SourceTypes from "./General/SourceTypes"; import InternalControl from "./General/InternalControl"; import UniqueNames from "./General/UniqueNames"; import SamplePermissions from "./General/SamplePermissions"; import HTTP from "./Server/HTTP"; import SSL from "./Server/SSL"; import Data from "./Data"; import Resources from "./Jobs/Resources"; import Tasks from "./Jobs/Tasks"; import Users from "../users/components/Users"; const General = () => ( <div> <SourceTypes /> <InternalControl /> <UniqueNames /> <SamplePermissions /> </div> ); const Server = () => ( <div> <HTTP /> <SSL /> </div> ); const Jobs = () => ( <div> <Resources /> <Tasks /> </div> ); const Settings = () => { return ( <div className="container"> <Nav bsStyle="tabs"> <LinkContainer to="/settings/general"> <NavItem>General</NavItem> </LinkContainer> <LinkContainer to="/settings/server"> <NavItem>Server</NavItem> </LinkContainer> <LinkContainer to="/settings/data"> <NavItem>Data</NavItem> </LinkContainer> <LinkContainer to="/settings/jobs"> <NavItem>Jobs</NavItem> </LinkContainer> <LinkContainer to="/settings/users"> <NavItem>Users</NavItem> </LinkContainer> </Nav> <Switch> <Redirect from="/settings" to="/settings/general" exact /> <Route path="/settings/general" component={General} /> <Route path="/settings/server" component={Server} /> <Route path="/settings/data" component={Data} /> <Route path="/settings/jobs" component={Jobs} /> <Route path="/settings/users" component={Users} /> </Switch> </div> ); }; Settings.propTypes = { source_types: React.PropTypes.object, get: React.PropTypes.func }; const mapStateToProps = (state) => { return { restrictSourceTypes: state.settings.data.restrict_source_types, allowedSourceTypes: state.settings.data.allowed_source_types }; }; const SettingsContainer = withRouter(connect( mapStateToProps )(Settings)); export default SettingsContainer;
JavaScript
0
8f5c299e190bc301f8e29910a7414146e1923500
clear precache thread on destroy
client/js/modules/imaging/views/imagehistory.js
client/js/modules/imaging/views/imagehistory.js
define(['marionette', 'utils/xhrimage', 'tpl!templates/imaging/imagehistory.html', 'tpl!templates/imaging/imagehistorymin.html' ], function(Marionette, XHRImage, template, templatemin) { var ThumbView = Marionette.ItemView.extend({ tagName: 'figure', template: _.template('<a href="/containers/cid/<%=CONTAINERID%>/iid/<%=CONTAINERINSPECTIONID%>/sid/<%=BLSAMPLEID%>"><img /></a><figcaption>+<%=DELTA%>d</figcaption>'), events: { 'mouseover': 'hover', }, hover: function(e) { console.log('hover') this.model.set({isSelected: true}); this.model.collection.trigger('selected:change', this.model) }, initialize: function(options) { this.model.on('change:isSelected', this.onSelectedChanged.bind(this)) var self = this this.img = new XHRImage() this.img.onload = function() { self.$el.find('img').attr('src', self.img.src) } this.img.load(this.model.urlFor()) }, onSelectedChanged: function() { this.model.get('isSelected') ? this.$el.addClass('selected') : this.$el.removeClass('selected') }, onRender: function() { if (this.model.get('isSelected')) this.$el.addClass('selected') }, }) var ThumbsView = Marionette.CollectionView.extend({ childView: ThumbView, }) return Marionette.LayoutView.extend({ // template: template, getTemplate: function() { return this.getOption('embed') ? templatemin : template }, className: function() { return 'img_history' + (this.getOption('embed') ? ' embed' : '') }, regions: { thm: '.columns', }, // setSampleId: function(id) { // this.blsampleid = id // if (id) this.images.fetch() // }, // getSampleId: function() { // return this.blsampleid // }, initialize: function(options) { this.caching = true this.images = options.historyimages this.listenTo(this.images, 'sync', this.preCache.bind(this,1)) //this.images.fetch() }, onRender: function() { this.thm.show(new ThumbsView({ collection: this.images })) }, preCache: function(n) { clearTimeout(this.cachethread) var self = this var i = this.images.at(n) if (this.caching && i) { var xhr = new XHRImage() console.log('caching history', i.urlFor('hd')) xhr.load(i.urlFor('full'), function() { self.cachethread = setTimeout(function() { self.preCache(++n) }, 500) }) } }, onDestroy: function() { clearTimeout(this.cachethread) this.caching = false }, }) })
define(['marionette', 'utils/xhrimage', 'tpl!templates/imaging/imagehistory.html', 'tpl!templates/imaging/imagehistorymin.html' ], function(Marionette, XHRImage, template, templatemin) { var ThumbView = Marionette.ItemView.extend({ tagName: 'figure', template: _.template('<a href="/containers/cid/<%=CONTAINERID%>/iid/<%=CONTAINERINSPECTIONID%>/sid/<%=BLSAMPLEID%>"><img /></a><figcaption>+<%=DELTA%>d</figcaption>'), events: { 'mouseover': 'hover', }, hover: function(e) { console.log('hover') this.model.set({isSelected: true}); this.model.collection.trigger('selected:change', this.model) }, initialize: function(options) { this.model.on('change:isSelected', this.onSelectedChanged.bind(this)) var self = this this.img = new XHRImage() this.img.onload = function() { self.$el.find('img').attr('src', self.img.src) } this.img.load(this.model.urlFor()) }, onSelectedChanged: function() { this.model.get('isSelected') ? this.$el.addClass('selected') : this.$el.removeClass('selected') }, onRender: function() { if (this.model.get('isSelected')) this.$el.addClass('selected') }, }) var ThumbsView = Marionette.CollectionView.extend({ childView: ThumbView, }) return Marionette.LayoutView.extend({ // template: template, getTemplate: function() { return this.getOption('embed') ? templatemin : template }, className: function() { return 'img_history' + (this.getOption('embed') ? ' embed' : '') }, regions: { thm: '.columns', }, // setSampleId: function(id) { // this.blsampleid = id // if (id) this.images.fetch() // }, // getSampleId: function() { // return this.blsampleid // }, initialize: function(options) { this.caching = true this.images = options.historyimages this.listenTo(this.images, 'sync', this.preCache.bind(this,1)) //this.images.fetch() }, onRender: function() { this.thm.show(new ThumbsView({ collection: this.images })) }, preCache: function(n) { clearTimeout(this.cachethread) var self = this var i = this.images.at(n) if (this.caching && i) { var xhr = new XHRImage() console.log('caching history', i.urlFor('hd')) xhr.load(i.urlFor('full'), function() { self.cachethread = setTimeout(function() { self.preCache(++n) }, 500) }) } }, onDestroy: function() { this.caching = false }, }) })
JavaScript
0
434402dfe84617e8334cf16ba0dda9b723b37b32
remove todo that was completed in a previous refactor
public/app/components/home/home-controller.js
public/app/components/home/home-controller.js
angular.module('app.home', []) .controller('HomeController', function($scope, $rootScope, $window, $location, $state, $http, $timeout, Utilities, Posts) { 'use strict'; // get recent posts to display on home page Posts.getRecent() .success(function(data) { $scope.posts = data; }) .error(function(err) { console.error(err); }); $scope.scrollDown = function() { Utilities.scrollTo(document.body, document.getElementById('main').offsetTop, 800); }; // some static data for home page $scope.contact = { "email": "ianlamb32@gmail.com", "phone": "+1 519-902-6533", "location": { "name": "London, ON", "latLng": [42.9837, -81.2497] } }; $scope.projects = [ { name: 'GoodLife Fitness Sales', url: 'http://www.goodlifefitness.com/training-programs/team-training/camps/ontario/london', repo: '', image: 'glf-sales-opt.png', desc: 'Sales engine for selling GoodLife team training contracts online' }, { name: 'Store Finder', url: 'http://apps.ianlamb.com/storefinder/', repo: 'https://github.com/ianlamb/storefinder', image: 'store-finder-opt.png', desc: 'Component for selecting stores from a large network' }, { name: 'Tempus Notes', url: 'http://notes.ianlamb.com/', repo: 'https://github.com/ianlamb/notes', image: 'tempus-notes-opt.png', desc: 'A very simple note-taker, great for remembering what you did for daily scrum' }, { name: 'Dark Souls Challenge Runs', url: 'http://darksouls.ianlamb.com/challenges', repo: 'https://github.com/ianlamb/darksouls-challenges', image: 'dscrgen-opt.png', desc: 'A fun little randomizer for Dark Souls challenge runs' }, { name: 'Z-Code', url: 'http://zcode.ianlamb.com/', repo: 'https://github.com/ianlamb/zcode', image: 'zcode-opt.png', desc: 'HTML5 game that my buddy and I made in college' }, { name: 'Creekside Landscaping', url: 'http://www.creeksidelandscaping.ca/', repo: '', image: 'creekside-landscaping-opt.png', desc: 'WordPress redesign for my neighbour\'s landscaping business' } ]; });
angular.module('app.home', []) .controller('HomeController', function($scope, $rootScope, $window, $location, $state, $http, $timeout, Utilities, Posts) { 'use strict'; // get recent posts to display on home page // TODO: change when this fires so it only happens on home page (controller reorg?) Posts.getRecent() .success(function(data) { $scope.posts = data; }) .error(function(err) { console.error(err); }); $scope.scrollDown = function() { Utilities.scrollTo(document.body, document.getElementById('main').offsetTop, 800); }; // some static data for home page $scope.contact = { "email": "ianlamb32@gmail.com", "phone": "+1 519-902-6533", "location": { "name": "London, ON", "latLng": [42.9837, -81.2497] } }; $scope.projects = [ { name: 'GoodLife Fitness Sales', url: 'http://www.goodlifefitness.com/training-programs/team-training/camps/ontario/london', repo: '', image: 'glf-sales-opt.png', desc: 'Sales engine for selling GoodLife team training contracts online' }, { name: 'Store Finder', url: 'http://apps.ianlamb.com/storefinder/', repo: 'https://github.com/ianlamb/storefinder', image: 'store-finder-opt.png', desc: 'Component for selecting stores from a large network' }, { name: 'Tempus Notes', url: 'http://notes.ianlamb.com/', repo: 'https://github.com/ianlamb/notes', image: 'tempus-notes-opt.png', desc: 'A very simple note-taker, great for remembering what you did for daily scrum' }, { name: 'Dark Souls Challenge Runs', url: 'http://darksouls.ianlamb.com/challenges', repo: 'https://github.com/ianlamb/darksouls-challenges', image: 'dscrgen-opt.png', desc: 'A fun little randomizer for Dark Souls challenge runs' }, { name: 'Z-Code', url: 'http://zcode.ianlamb.com/', repo: 'https://github.com/ianlamb/zcode', image: 'zcode-opt.png', desc: 'HTML5 game that my buddy and I made in college' }, { name: 'Creekside Landscaping', url: 'http://www.creeksidelandscaping.ca/', repo: '', image: 'creekside-landscaping-opt.png', desc: 'WordPress redesign for my neighbour\'s landscaping business' } ]; });
JavaScript
0
d62f015d188313b416631cf015604f27b7313b19
fix summary not clickable on dashboards
layouts/dashboards/selectors.js
layouts/dashboards/selectors.js
import { createSelector, createStructuredSelector } from 'reselect'; import upperFirst from 'lodash/upperFirst'; import { encodeQueryParams } from 'utils/url'; import { filterWidgetsByLocation, getWidgetCategories, getActiveCategory, } from 'components/widgets/selectors'; import { getActiveArea } from 'providers/areas-provider/selectors'; import CATEGORIES from 'data/categories.json'; // get list data const selectShowMap = (state) => state.widgets?.showMap; const selectLocation = (state) => state.location; const selectLocationType = (state) => state.location && state.location.payload && state.location.payload.type; const selectCategory = (state) => (state.location && state.location.query && state.location.query.category) || 'summary'; export const selectQuery = (state) => state.location && state.location.query; export const getEmbed = createSelector( [selectLocation], (location) => location && location.pathname.includes('/embed') ); export const getWidgetAnchor = createSelector( [selectQuery, filterWidgetsByLocation], (query, widgets) => { const { scrollTo } = query || {}; const hasWidget = widgets && widgets.length && widgets.find((w) => w.widget === scrollTo); return hasWidget ? document.getElementById(scrollTo) : null; } ); export const getNoWidgetsMessage = createSelector( [selectCategory], (category) => `${upperFirst(category)} data for {location} coming soon` ); export const getLinks = createSelector( [getWidgetCategories, getActiveCategory, selectLocation], (widgetCats, activeCategory, location) => { const serializePayload = Object.values(location.payload).filter( (p) => p && p.length ); function formatQuery(category) { const encodedQueryString = encodeQueryParams({ ...location.query, ...(category.value !== 'summary' && { category: category.value, }), ...(category.value === 'summary' && { category: undefined, }), }); return encodedQueryString.length > 0 ? `?${encodedQueryString}` : ''; } if (!widgetCats || widgetCats?.length === 0) { return CATEGORIES.map((category) => ({ label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, })); } return CATEGORIES.filter((c) => widgetCats.includes(c.value)).map( (category) => { return { label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, active: activeCategory === category.value, }; } ); } ); export const getDashboardsProps = createStructuredSelector({ showMapMobile: selectShowMap, category: getActiveCategory, links: getLinks, widgetAnchor: getWidgetAnchor, noWidgetsMessage: getNoWidgetsMessage, locationType: selectLocationType, activeArea: getActiveArea, widgets: filterWidgetsByLocation, });
import { createSelector, createStructuredSelector } from 'reselect'; import upperFirst from 'lodash/upperFirst'; import { encodeQueryParams } from 'utils/url'; import { filterWidgetsByLocation, getWidgetCategories, getActiveCategory, } from 'components/widgets/selectors'; import { getActiveArea } from 'providers/areas-provider/selectors'; import CATEGORIES from 'data/categories.json'; // get list data const selectShowMap = (state) => state.widgets?.showMap; const selectLocation = (state) => state.location; const selectLocationType = (state) => state.location && state.location.payload && state.location.payload.type; const selectCategory = (state) => (state.location && state.location.query && state.location.query.category) || 'summary'; export const selectQuery = (state) => state.location && state.location.query; export const getEmbed = createSelector( [selectLocation], (location) => location && location.pathname.includes('/embed') ); export const getWidgetAnchor = createSelector( [selectQuery, filterWidgetsByLocation], (query, widgets) => { const { scrollTo } = query || {}; const hasWidget = widgets && widgets.length && widgets.find((w) => w.widget === scrollTo); return hasWidget ? document.getElementById(scrollTo) : null; } ); export const getNoWidgetsMessage = createSelector( [selectCategory], (category) => `${upperFirst(category)} data for {location} coming soon` ); export const getLinks = createSelector( [getWidgetCategories, getActiveCategory, selectLocation], (widgetCats, activeCategory, location) => { const serializePayload = Object.values(location.payload).filter( (p) => p && p.length ); function formatQuery(category) { const encodedQueryString = encodeQueryParams({ ...location.query, ...(category.value !== 'summary' && { category: category.value, }), }); return encodedQueryString.length > 0 ? `?${encodedQueryString}` : ''; } if (!widgetCats || widgetCats?.length === 0) { return CATEGORIES.map((category) => ({ label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, })); } return CATEGORIES.filter((c) => widgetCats.includes(c.value)).map( (category) => { return { label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, active: activeCategory === category.value, }; } ); } ); export const getDashboardsProps = createStructuredSelector({ showMapMobile: selectShowMap, category: getActiveCategory, links: getLinks, widgetAnchor: getWidgetAnchor, noWidgetsMessage: getNoWidgetsMessage, locationType: selectLocationType, activeArea: getActiveArea, widgets: filterWidgetsByLocation, });
JavaScript
0.000003
e0d37a79655947ca31eb869e3d52fbedf8d018a1
Fix deployedUrl.
upload.js
upload.js
import archiver from 'archiver' import fs from 'mz/fs' import path from 'path' import {run} from 'yacol' import http from 'http' import https from 'https' import e from './env.js' import parseArgs from 'minimist' import fetch from 'node-fetch' const {bool, env, getErrors} = e() const request = (bool('HTTPS') ? https : http).request function* ignore(folder) { const ignoreFile = path.join(folder, '.docsignore') const parse = (f) => f.split('\n') .map((s) => s.trim()) .filter((s) => !s.match(/^#/) && s !== '') return yield run(function*() { return parse(yield fs.readFile(ignoreFile, 'utf-8')) }).catch((e) => { if (e.code === 'ENOENT') return [] else throw e }) } function response() { let resolve, reject return { promise: new Promise((res, rej) => { resolve = res reject = rej }), callback: (res) => { const data = [] res.on('data', (d) => data.push(d)) res.on('error', (e) => reject(e)) res.on('end', () => resolve({...res, body: data.join('')})) } } } function baseUrl() { const protocol = bool('HTTPS') ? 'https:' : 'http:' const defaultPorts = {'http:': '80', 'https:': '443'} const portPart = env('PORT') !== defaultPorts[protocol] ? `:${env('PORT')}` : '' return `${protocol}//${env('HOST')}${portPart}` } const deployedUrl = (docId, isDraft) => `${baseUrl()}${isDraft ? '/$drafts' : ''}/${docId}/` function* upload(folder) { const archive = archiver('zip') const {promise, callback} = response() const uploadReq = request({ host: env('HOST'), port: env('PORT'), path: '/$upload', method: 'POST', headers: { 'Authorization': env('API_KEY'), }, }, callback) getErrors() uploadReq.on('close', () => uploadReq.end()) archive.pipe(uploadReq) archive.glob('**/*', { dot: false, cwd: folder, ignore: yield run(ignore, folder) }) archive.finalize() const result = yield promise if (result.statusCode !== 200) { throw new Error(`Server returned: HTTP ${result.statusCode} -- ${result.body}`) } else{ console.log(`Deploy successful on ${deployedUrl(result.body, true)}`) return result.body } } function* link(folder, docId) { const configFile = path.join(folder, 'docs.json') const config = JSON.parse(yield fs.readFile(configFile, 'utf-8')) if (!config.alias) throw new Error(`Alias not defined in ${configFile}`) const url = `${baseUrl()}/$alias/${docId}/${config.alias}` const result = yield fetch(url, { method: 'PUT', headers: {'Authorization': env('API_KEY')} }) if (result.status !== 200) { const body = yield result.text() throw new Error(`Server returned: HTTP ${result.status} -- ${body}`) } else{ console.log(`Deploy successful on ${deployedUrl(config.alias, false)}`) return result.body } } const args = parseArgs(process.argv.slice(2), { alias: {'alias': 'a'}, 'boolean': ['alias'], }) const folder = args['_'][0] if (!folder) { console.log(`usage: yarn run upload -- [-a] folder`) process.exit(0) } run(function* () { const docId = yield run(upload, folder) if (args.alias) { yield run(link, folder, docId) } })
import archiver from 'archiver' import fs from 'mz/fs' import path from 'path' import {run} from 'yacol' import http from 'http' import https from 'https' import e from './env.js' import parseArgs from 'minimist' import fetch from 'node-fetch' const {bool, env, getErrors} = e() const request = (bool('HTTPS') ? https : http).request function* ignore(folder) { const ignoreFile = path.join(folder, '.docsignore') const parse = (f) => f.split('\n') .map((s) => s.trim()) .filter((s) => !s.match(/^#/) && s !== '') return yield run(function*() { return parse(yield fs.readFile(ignoreFile, 'utf-8')) }).catch((e) => { if (e.code === 'ENOENT') return [] else throw e }) } function response() { let resolve, reject return { promise: new Promise((res, rej) => { resolve = res reject = rej }), callback: (res) => { const data = [] res.on('data', (d) => data.push(d)) res.on('error', (e) => reject(e)) res.on('end', () => resolve({...res, body: data.join('')})) } } } function baseUrl() { const protocol = bool('HTTPS') ? 'https:' : 'http:' const defaultPorts = {'http:': '80', 'https:': '443'} const portPart = env('PORT') !== defaultPorts[protocol] ? `:${env('PORT')}` : '' return `${protocol}//${env('HOST')}${portPart}` } const deployedUrl = (docId, isDraft) => `${baseUrl()}/${isDraft ? 'drafts' : 'docs'}/${docId}/` function* upload(folder) { const archive = archiver('zip') const {promise, callback} = response() const uploadReq = request({ host: env('HOST'), port: env('PORT'), path: '/$upload', method: 'POST', headers: { 'Authorization': env('API_KEY'), }, }, callback) getErrors() uploadReq.on('close', () => uploadReq.end()) archive.pipe(uploadReq) archive.glob('**/*', { dot: false, cwd: folder, ignore: yield run(ignore, folder) }) archive.finalize() const result = yield promise if (result.statusCode !== 200) { throw new Error(`Server returned: HTTP ${result.statusCode} -- ${result.body}`) } else{ console.log(`Deploy successful on ${deployedUrl(result.body, true)}`) return result.body } } function* link(folder, docId) { const configFile = path.join(folder, 'docs.json') const config = JSON.parse(yield fs.readFile(configFile, 'utf-8')) if (!config.alias) throw new Error(`Alias not defined in ${configFile}`) const url = `${baseUrl()}/$alias/${docId}/${config.alias}` const result = yield fetch(url, { method: 'PUT', headers: {'Authorization': env('API_KEY')} }) if (result.status !== 200) { const body = yield result.text() throw new Error(`Server returned: HTTP ${result.status} -- ${body}`) } else{ console.log(`Deploy successful on ${deployedUrl(config.alias, false)}`) return result.body } } const args = parseArgs(process.argv.slice(2), { alias: {'alias': 'a'}, 'boolean': ['alias'], }) const folder = args['_'][0] if (!folder) { console.log(`usage: yarn run upload -- [-a] folder`) process.exit(0) } run(function* () { const docId = yield run(upload, folder) if (args.alias) { yield run(link, folder, docId) } })
JavaScript
0
c57c4b4b6a0aaa4478c9cc241eb9d780de8496eb
Update list_metadata_parser.js
test/core/list_metadata_parser.js
test/core/list_metadata_parser.js
require('../initialize-globals').load(); var listMetadataParser = require('../../lib/core/list_metadata_parser'); describe('# list_metadata_parser', function() { describe("##createListMetadatasOptions", function() { it.skip('GET', function() { var meta = { top: 10, skip: 23, sortFieldName: "colA", sortDesc: true }; var ajaxOptions = listMetadataParser.load({ criteria: { name: "pierre", age: 27 }, metadata: meta }, { url: "http://test.com" }); console.log("ajaxOptions", ajaxOptions); ajaxOptions.url.should.be.a.string; for (var m in meta) { ajaxOptions.url.indexOf(m).should.not.be.equal(-1); } }); }); });
require('../initialize-globals').load(); var listMetadataParser = require('../../lib/core/list_metadata_parser'); describe('# list_metadata_parser', function() { describe("##createListMetadatasOptions", function() { it('GET', function() { var meta = { top: 10, skip: 23, sortFieldName: "colA", sortDesc: true }; var ajaxOptions = listMetadataParser.load({ criteria: { name: "pierre", age: 27 }, metadata: meta }, { url: "http://test.com" }); console.log("ajaxOptions", ajaxOptions); ajaxOptions.url.should.be.a.string; for (var m in meta) { ajaxOptions.url.indexOf(m).should.not.be.equal(-1); } }); }); });
JavaScript
0.000002
748cbd48a2c0558a6f653aa92773493dc146fcec
fix typo
client/app/pods/media/route.js
client/app/pods/media/route.js
/* Single Ember.js Route that will work for all media types */ import Ember from 'ember'; import DataRouteErrorMixin from 'client/mixins/data-route-error'; const { Route, get } = Ember; // TODO: Figure out if different media types should just use different // templates, or if they should not share any code at all. export default Route.extend(DataRouteErrorMixin, { model(params) { return this.store.findRecord('user', params.mediaSlug); }, serialize(model) { return { mediaType: model.constructor.modelName, mediaSlug: get(model, 'slug') }; } });
/* Single Ember.js Route that will work for all media types */ import Ember from 'ember'; import DataRotueErrorMixin from 'client/mixins/data-route-error'; const { Route, get } = Ember; // TODO: Figure out if different media types should just use different // templates, or if they should not share any code at all. export default Route.extend(DataRotueErrorMixin, { model(params) { return this.store.findRecord('user', params.mediaSlug); }, serialize(model) { return { mediaType: model.constructor.modelName, mediaSlug: get(model, 'slug') }; } });
JavaScript
0.001084
b6f23172ccb9da4549d7e1c691d07e8973f1e430
Fix podcast publisher not showing in podcast detail view
public/app/js/cbus-server-get-podcast-info.js
public/app/js/cbus-server-get-podcast-info.js
if (!cbus.hasOwnProperty("server")) { cbus.server = {} } (function() { cbus.server.getPodcastInfo = function(podcastUrl, callback) { var podcastData = {}; xhr({ url: podcastUrl, // headers: cbus.const.REQUEST_HEADERS }, function(err, result, body) { if (err) { callback(null) } else { let parser = new DOMParser(); let doc = parser.parseFromString(body, "application/xml"); if (doc.documentElement.nodeName === "parsererror") { console.log("error parsing xml", err); callback(null) } else { let channel = doc.querySelector("rss channel"); // title let titleElem = channel.getElementsByTagName("title")[0]; if (titleElem) { podcastData.title = titleElem.textContent.trim(); } // publisher let authorElem = channel.getElementsByTagName("itunes:author")[0]; if (authorElem) { podcastData.publisher = authorElem.textContent; } // description let descriptionElem = channel.getElementsByTagName("description")[0]; if (descriptionElem) { podcastData.description = descriptionElem.textContent; } // image let imageElems = doc.querySelectorAll("rss channel > image"); for (let i = 0, l = imageElems.length; i < l; i++) { let imageElem = imageElems[i]; if (imageElem.tagName === "image" && imageElem.getElementsByTagName("url")[0]) { podcastData.image = imageElem.getElementsByTagName("url")[0].textContent; } else if (imageElem.tagName === "itunes:image") { podcastData.image = imageElem.getAttribute("href"); } } callback(podcastData); } } }); } }());
if (!cbus.hasOwnProperty("server")) { cbus.server = {} } (function() { cbus.server.getPodcastInfo = function(podcastUrl, callback) { var podcastData = {}; xhr({ url: podcastUrl, // headers: cbus.const.REQUEST_HEADERS }, function(err, result, body) { if (err) { callback(null) } else { let parser = new DOMParser(); let doc = parser.parseFromString(body, "application/xml"); if (doc.documentElement.nodeName === "parsererror") { console.log("error parsing xml", err); callback(null) } else { let channel = doc.querySelector("rss channel"); // title let titleElem = channel.getElementsByTagName("title")[0]; if (titleElem) { podcastData.title = titleElem.textContent.trim(); } // publisher let authorElem = channel.getElementsByTagName("author")[0]; if (authorElem && authorElem.tagName === "itunes:author") { podcastData.publisher = authorElem.textContent; } // description let descriptionElem = channel.getElementsByTagName("description")[0]; if (descriptionElem) { podcastData.description = descriptionElem.textContent; } // image let imageElems = doc.querySelectorAll("rss channel > image"); for (let i = 0, l = imageElems.length; i < l; i++) { let imageElem = imageElems[i]; if (imageElem.tagName === "image" && imageElem.getElementsByTagName("url")[0]) { podcastData.image = imageElem.getElementsByTagName("url")[0].textContent; } else if (imageElem.tagName === "itunes:image") { podcastData.image = imageElem.getAttribute("href"); } } callback(podcastData); } } }); } }());
JavaScript
0
5fdd6483d7346751b297b6f6ec16cf591507de8d
remove rate persent
src/js/components/Transaction/ExchangeForm.js
src/js/components/Transaction/ExchangeForm.js
import React from "react" import { roundingNumber } from "../../utils/converter" const ExchangeForm = (props) => { var errorToken = props.errors.selectSameToken + props.errors.selectTokenToken var tokenRate = props.isSelectToken ? <img src="/assets/img/waiting.svg" /> : props.exchangeRate.rate var render = ( <div> <div class="frame"> <div class="row"> <div class="column small-11 medium-10 large-8 small-centered"> <h1 class="title">Exchange</h1> <form action="#" method="get"> <div class="row"> <div class="column medium-6"> <label style={{marginBottom: 0}}>Exchange From <div className={errorToken === "" && props.errors.sourceAmount === "" ? "token-input" : "token-input error"}> <input type={props.input.sourceAmount.type} className="source-input" value={props.input.sourceAmount.value} onFocus={() => props.input.sourceAmount.onFocus()} onChange={(e) => props.input.sourceAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {props.tokenSource} </div> {errorToken !== "" && <span class="error-text">{errorToken}</span> } {props.errors.sourceAmount !== "" && <span class="error-text">{props.errors.sourceAmount}</span> } </label> <div class="address-balance" style={{marginBottom: 40}}> <span class="note">Address Balance</span> <a className="value" onClick={props.setAmount} title={props.balance.value}> {props.balance.roundingValue} {props.sourceTokenSymbol} </a> </div> </div> <div class="column medium-6"> <label>Exchange To <div class="token-input"> <input type={props.input.destAmount.type} value={props.input.destAmount.value} onFocus={() => props.input.destAmount.onFocus()} onChange={(e) => props.input.destAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {/* <div class="info" data-open="exchange-to-token-modal"><img src="/assets/img/omg.svg"/><span class="name">OMG</span></div> */} {props.tokenDest} </div> </label> </div> </div> <div class="row"> <div class="column"> <p class="token-compare" title={tokenRate}> 1 {props.exchangeRate.sourceToken} = {roundingNumber(tokenRate)} {props.exchangeRate.destToken} {/* <span class="up">{props.exchangeRate.percent}%</span> */} </p> </div> </div> {props.step === 2 && <div class="row hide-on-choose-token-pair"> <div class="column"> <div class="clearfix"> <div class="advanced-switch base-line float-right"> <div class="switch accent"> <input class="switch-input" id="advanced" type="checkbox" /> <label class="switch-paddle" for="advanced"><span class="show-for-sr">Advanced Mode</span></label> </div> <label class="switch-caption" for="advanced">Advanced</label> </div> </div> <div class="advanced-content" disabled> {props.gasConfig} </div> </div> </div> } </form> </div> </div> </div> {props.exchangeButton} {props.selectTokenModal} </div> ) return ( <div className={props.step === 1 ? "choose-token-pair" : ""} id="exchange"> {props.step !== 3 ? render : ''} <div class="page-3"> {props.step == 3 ? props.trasactionLoadingScreen : ''} </div> </div> ) } export default ExchangeForm
import React from "react" import { roundingNumber } from "../../utils/converter" const ExchangeForm = (props) => { var errorToken = props.errors.selectSameToken + props.errors.selectTokenToken var tokenRate = props.isSelectToken ? <img src="/assets/img/waiting.svg" /> : props.exchangeRate.rate var render = ( <div> <div class="frame"> <div class="row"> <div class="column small-11 medium-10 large-8 small-centered"> <h1 class="title">Exchange</h1> <form action="#" method="get"> <div class="row"> <div class="column medium-6"> <label style={{marginBottom: 0}}>Exchange From <div className={errorToken === "" && props.errors.sourceAmount === "" ? "token-input" : "token-input error"}> <input type={props.input.sourceAmount.type} className="source-input" value={props.input.sourceAmount.value} onFocus={() => props.input.sourceAmount.onFocus()} onChange={(e) => props.input.sourceAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {props.tokenSource} </div> {errorToken !== "" && <span class="error-text">{errorToken}</span> } {props.errors.sourceAmount !== "" && <span class="error-text">{props.errors.sourceAmount}</span> } </label> <div class="address-balance" style={{marginBottom: 40}}> <span class="note">Address Balance</span> <a className="value" onClick={props.setAmount} title={props.balance.value}> {props.balance.roundingValue} {props.sourceTokenSymbol} </a> </div> </div> <div class="column medium-6"> <label>Exchange To <div class="token-input"> <input type={props.input.destAmount.type} value={props.input.destAmount.value} onFocus={() => props.input.destAmount.onFocus()} onChange={(e) => props.input.destAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {/* <div class="info" data-open="exchange-to-token-modal"><img src="/assets/img/omg.svg"/><span class="name">OMG</span></div> */} {props.tokenDest} </div> </label> </div> </div> <div class="row"> <div class="column"> <p class="token-compare" title={tokenRate}> 1 {props.exchangeRate.sourceToken} = {roundingNumber(tokenRate)} {props.exchangeRate.destToken} <span class="up">{props.exchangeRate.percent}%</span> </p> </div> </div> {props.step === 2 && <div class="row hide-on-choose-token-pair"> <div class="column"> <div class="clearfix"> <div class="advanced-switch base-line float-right"> <div class="switch accent"> <input class="switch-input" id="advanced" type="checkbox" /> <label class="switch-paddle" for="advanced"><span class="show-for-sr">Advanced Mode</span></label> </div> <label class="switch-caption" for="advanced">Advanced</label> </div> </div> <div class="advanced-content" disabled> {props.gasConfig} </div> </div> </div> } </form> </div> </div> </div> {props.exchangeButton} {props.selectTokenModal} </div> ) return ( <div className={props.step === 1 ? "choose-token-pair" : ""} id="exchange"> {props.step !== 3 ? render : ''} <div class="page-3"> {props.step == 3 ? props.trasactionLoadingScreen : ''} </div> </div> ) } export default ExchangeForm
JavaScript
0.000005
e903aa8710d1558c79049f2e6305026065759132
support company tag; bugfix: hide locked problem after sort
leetcode-ext/leetcode-hidden.js
leetcode-ext/leetcode-hidden.js
/** * Created by binarylu on 3/21/16. */ $(function(){ var path = window.location.pathname; chrome.storage.sync.get({ ac_difficulty: 'show', hide_locked: 0 }, function(items) { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); } if (path.match(new RegExp('^\/tag')) || path.match(new RegExp('^\/company'))) { tag_add_check(); $("#hide_locked").prop("checked", items.hide_locked === 0 ? false : true); tag_hide_locked(); } if (items.ac_difficulty == "hide") { if (path.match(new RegExp('^\/problemset'))) { page_problemset(); } else if (path.match(new RegExp('^\/tag')) || path.match(new RegExp('^\/company'))) { $("#question_list thead a.btn-link").click(function() { setTimeout(page_tag, 1000); setTimeout(tag_hide_locked, 1000); }); page_tag(); } else if (path.match(new RegExp('^\/problems'))) { page_problem(); $("#result-state").bind("DOMSubtreeModified", function() { var state = $("#result-state").html().replace(/(^\s*)|(\s*$)/g, "").toLocaleLowerCase(); if (state == "accepted") { $("#total-submit-ac").show(); } else { $("#total-submit-ac").hide(); } }); } } }); }); function page_problemset() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#problemList tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:last"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_tag() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#question_list tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:eq(4)"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_problem() { $("#result h4:first").after($("<h4 id='total-submit-ac'></h4>").html($(".total-submit,.total-ac")).hide()); } function tag_add_check() { var $check = '<div style="display:inline;margin-left:10px">' + '<input type="checkbox" id="hide_locked">&nbsp;' + '<label for="hide_locked">Hide locked problems</label>' + '</div>'; $("label[for='tagCheck']").after($check); $("#hide_locked").click(tag_hide_locked); } function tag_hide_locked() { var hide_locked = $("#hide_locked").prop("checked") === true ? 1 : 0; chrome.storage.sync.set({ hide_locked: hide_locked }, function() { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); return; } $("#question_list tbody tr").each(function() { var locked = $(this).children("td:eq(2)").children("i").length === 0 ? 0 : 1; if (hide_locked === 1 && locked === 1) { $(this).hide(); return true; } $(this).show(); }); }); }
/** * Created by binarylu on 3/21/16. */ $(function(){ var path = window.location.pathname; chrome.storage.sync.get({ ac_difficulty: 'show', hide_locked: 0 }, function(items) { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); } if (path.match(new RegExp('^\/tag'))) { tag_add_check(); $("#hide_locked").prop("checked", items.hide_locked === 0 ? false : true); tag_hide_locked(); } if (items.ac_difficulty == "hide") { if (path.match(new RegExp('^\/problemset'))) { page_problemset(); } else if (path.match(new RegExp('^\/tag'))) { $("#question_list thead a.btn-link").click(function() { setTimeout(page_tag, 1000); }); page_tag(); } else if (path.match(new RegExp('^\/problems'))) { page_problem(); $("#result-state").bind("DOMSubtreeModified", function() { var state = $("#result-state").html().replace(/(^\s*)|(\s*$)/g, "").toLocaleLowerCase(); if (state == "accepted") { $("#total-submit-ac").show(); } else { $("#total-submit-ac").hide(); } }); } } }); }); function page_problemset() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#problemList tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:last"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_tag() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#question_list tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:eq(4)"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_problem() { $("#result h4:first").after($("<h4 id='total-submit-ac'></h4>").html($(".total-submit,.total-ac")).hide()); } function tag_add_check() { var $check = '<div style="display:inline;margin-left:10px">' + '<input type="checkbox" id="hide_locked">&nbsp;' + '<label for="hide_locked">Hide locked problems</label>' + '</div>'; $("label[for='tagCheck']").after($check); $("#hide_locked").click(tag_hide_locked); } function tag_hide_locked() { var hide_locked = $("#hide_locked").prop("checked") === true ? 1 : 0; chrome.storage.sync.set({ hide_locked: hide_locked }, function() { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); return; } $("#question_list tbody tr").each(function() { var locked = $(this).children("td:eq(2)").children("i").length === 0 ? 0 : 1; if (hide_locked === 1 && locked === 1) { $(this).hide(); return true; } $(this).show(); }); }); }
JavaScript
0
dc6cacb775d1970fdc2371191f436c43eaac2828
Update console2winston.js
console2winston.js
console2winston.js
var util = require("util"); var winston = require("winston"); var stackTrace = require("stack-trace"); var _ = require("underscore"); var g_logger = winston; exports.logger = g_logger; exports.init= function(log) { g_logger = log; exports.logger = exports.winston = g_logger; return g_logger; } exports.enable_console = false; exports.enable_extra_info = true; var my_console = {}; for (var i in console) { my_console[i] = console[i]; } exports.console= my_console; function log(sl, level, args) { var out = ""; if (exports.enable_extra_info) { var trace = stackTrace.parse(new Error()); var filename = trace[sl].fileName; var funcname = trace[sl].functionName; if (funcname == null) funcname = trace[sl].methodName; var line = trace[sl].lineNumber; header = util.format("[%d][%s:%d][%s]\t", process.pid,filename, line, funcname); g_logger.log(level, header + args); } else { g_logger.log(level, out); } if (!!exports.enable_console) { switch(level) { case "info": my_console.info(out); break; /*case "debug": my_console.debug(out); break; */ // no console.debug function case "error": my_console.error(out); break; case "warn": my_console.warn(out); break; default: my_console.log(out); } } } var g_time_labels={}; (function() { console.log = function(){ log(2, "info", util.format.apply(util.format, arguments)); }; _.each(["info", "debug", "error", "warn", "verbose", "silly"], function(m) { console[m] = function(){log(2, m, util.format.apply(util.format, arguments));}; }); console.trace = function(lable) { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Trace: "+lable +"\n" + st; log(2, "error", st); }; console.dir = function(a) { var out = util.inspect(a); log(2, "info", out); }; console.assert = function(a) { if (!a) { var st = new Error().stack; var msg = Array.prototype.slice.call(arguments, 1, arguments.length); st = st.replace(/^.*\n/, ""); st = st.replace(/^.*\n/, "AssertionError: " + util.format.apply(util.format, msg)+"\n"); log(2, "error", st); } } console.time = function(label) { g_time_labels[label] = new Date().getTime(); } console.timeEnd = function(label) { var begin= g_time_labels[label]; g_time_labels[label]=undefined; var now = new Date().getTime(); if (typeof(begin) != 'undefined') { log(2, "info", label+": "+ (now - begin)); } else { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Error: No such label: "+label +"\n"+ st; log(2, "error", st); } } })();
var util = require("util"); var winston = require("winston"); var stackTrace = require("stack-trace"); var _ = require("underscore"); var g_logger = winston; exports.logger = g_logger; exports.init= function(log) { g_logger = log; exports.logger = exports.winston = g_logger; return g_logger; } exports.enable_console = false; exports.enable_extra_info = true; var my_console = {}; for (var i in console) { my_console[i] = console[i]; } exports.console= my_console; function log(sl, level, args) { var out = ""; if (exports.enable_extra_info) { var trace = stackTrace.parse(new Error()); var filename = trace[sl].fileName; var funcname = trace[sl].functionName; if (funcname == null) funcname = trace[sl].methodName; var line = trace[sl].lineNumber; header = util.format("[%d][%s:%d][%s]\t", process.pid,filename, line, funcname); g_logger.log(level, header + args); } else { g_logger.log(level, out); } if (!!exports.enable_console) { switch(level) { case "info": my_console.info(out); break; case "debug": my_console.debug(out); break; case "error": my_console.error(out); break; case "warn": my_console.warn(out); break; default: my_console.log(out); } } } var g_time_labels={}; (function() { console.log = function(){ log(2, "info", util.format.apply(util.format, arguments)); }; _.each(["info", "debug", "error", "warn", "verbose", "silly"], function(m) { console[m] = function(){log(2, m, util.format.apply(util.format, arguments));}; }); console.trace = function(lable) { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Trace: "+lable +"\n" + st; log(2, "error", st); }; console.dir = function(a) { var out = util.inspect(a); log(2, "info", out); }; console.assert = function(a) { if (!a) { var st = new Error().stack; var msg = Array.prototype.slice.call(arguments, 1, arguments.length); st = st.replace(/^.*\n/, ""); st = st.replace(/^.*\n/, "AssertionError: " + util.format.apply(util.format, msg)+"\n"); log(2, "error", st); } } console.time = function(label) { g_time_labels[label] = new Date().getTime(); } console.timeEnd = function(label) { var begin= g_time_labels[label]; g_time_labels[label]=undefined; var now = new Date().getTime(); if (typeof(begin) != 'undefined') { log(2, "info", label+": "+ (now - begin)); } else { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Error: No such label: "+label +"\n"+ st; log(2, "error", st); } } })();
JavaScript
0.000001