commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
1a651fd12e02c470985149a2b0590af4d7049fb8
Use const #23
tests/unit/components/report/children.js
tests/unit/components/report/children.js
import Report from '../../../../ui/components/report.jsx'; import fixture from '../../../fixtures/components/report/data.js'; import suitesParser from './setup.js'; import {render, stubMethod, getChildProps} from '../../helpers.js'; describe('Report', function() { describe('Children', function() { let { suites, numberOfPasses, numberOfFailures, duration } = suitesParser(fixture.data); let component, props; beforeEach(function() { stubMethod(Report, 'render', null); component = render(Report, fixture); }); describe('Header', function() { beforeEach(function() { props = getChildProps(component, 'header', [numberOfPasses, numberOfFailures, duration]); }); it('should pass the number of passes', function() { expect(props.passes).to.equal(numberOfPasses); }); it('should pass the number of failures', function() { expect(props.failures).to.equal(numberOfFailures); }); it('should pass the total duration', function() { expect(props.duration).to.equal(duration); }); it('should pass the default filter', function() { expect(props.filter).to.equal('all'); }); }); describe('Results', function() { beforeEach(function() { props = getChildProps(component, 'results', [suites]); }); it('should pass the suites array', function() { expect(props.suites).to.equal(suites); }); it('should pass the default filter', function() { expect(props.filter).to.equal('all'); }); }); }); });
JavaScript
0.000001
@@ -299,18 +299,20 @@ ) %7B%0A -le +cons t %7B%0A
452ad2dc7aea3cf739777e53444561081592e7c7
Fix TypeError when switching tabs + minor cleanup (Task #356)
app/assets/javascripts/pusher.js
app/assets/javascripts/pusher.js
function pusherStart() { // Pusher global vars var pusher = new Pusher($("meta[name='pusher-key']").attr("content")); var listUrl = $(".list").data("url"); var channel = pusher.subscribe($(".list").data("pusher-channel")); // Pusher logger Pusher.log = function(message) { if (window.console && window.console.log) { window.console.log(message); } }; // Pusher event bind if($(".list").length){ channel.bind('new_message', function(data) { loadList(); }); loadList(); } // Ajax load list function function loadList(){ $(".list").load(listUrl, function(){ if($(".list .list-item").length == 0){ $(".panel.empty-state").show(); } else { $(".panel.empty-state").hide(); } }); } } $(document).on("ready page:change", function(){ pusherStart(); })
JavaScript
0
@@ -42,16 +42,41 @@ al vars%0A + var list = $(%22.list%22);%0A var pu @@ -156,26 +156,20 @@ stUrl = -$(%22. list -%22) .data(%22u @@ -180,17 +180,21 @@ ;%0A var -c +listC hannel = @@ -198,35 +198,12 @@ l = -pusher.subscribe($(%22. list -%22) .dat @@ -225,158 +225,116 @@ el%22) -) ;%0A%0A -// Pusher logger%0A Pusher.log = function(message) %7B%0A if (window.console && window.console.log) %7B%0A window.console.log(message);%0A %7D%0A %7D +if (typeof listChannel == %22undefined%22) %7B%0A return;%0A %7D%0A%0A var channel = pusher.subscribe(listChannel) ;%0A%0A @@ -360,26 +360,20 @@ nd%0A if( -$(%22. list -%22) .length) @@ -422,16 +422,24 @@ (data) %7B +%0A loadLis @@ -442,16 +442,20 @@ dList(); +%0A %7D);%0A @@ -795,9 +795,9 @@ rt();%0A%7D) -%0A +;
b49b4c23636c8264794085b33ffcc702a3d46620
Remove extraneous directory creation in examples environment.
bids-validator/tests/env/load-examples.js
bids-validator/tests/env/load-examples.js
const fs = require('fs') const { promisify } = require('util') const request = require('sync-request') const AdmZip = require('adm-zip') const lockfile = require('lockfile') const lockPromise = promisify(lockfile.lock) const test_version = '1.2.0' const examples_lock = 'bids-validator/tests/data/examples.lockfile' // Wait for up to five minutes for examples to finish // downloading in another test worker const examples_lock_opts = { wait: 300000 } const loadExamples = async () => { await lockPromise(examples_lock, examples_lock_opts) if ( !fs.existsSync( 'bids-validator/tests/data/bids-examples-' + test_version + '/', ) ) { console.log('downloading test data') const response = request( 'GET', 'http://github.com/bids-standard/bids-examples/archive/' + test_version + '.zip', ) if (!fs.existsSync('bids-validator/tests/data')) { fs.mkdirSync('bids-validator/tests/data') } fs.writeFileSync('bids-validator/tests/data/examples.zip', response.body) const zip = new AdmZip('bids-validator/tests/data/examples.zip') console.log('unzipping test data') zip.extractAllTo('bids-validator/tests/data/', true) } lockfile.unlockSync(examples_lock) return test_version } module.exports = loadExamples
JavaScript
0
@@ -846,117 +846,8 @@ )%0A - if (!fs.existsSync('bids-validator/tests/data')) %7B%0A fs.mkdirSync('bids-validator/tests/data')%0A %7D%0A
3709ab2532cb084ce19e55acbe55b0261a682a3e
Update game.js
scripts/game.js
scripts/game.js
var game = { resources: {}, tick: function () { for ( var res in game.resources ) { game.resources[res].update(); } } }; game.tick.bind( game ); game.interval = window.setInterval( game.tick, 100 ); game.buttons = document.getElementById( 'buttons' ); game.labels = document.getElementById( 'stats' ); game.resource = function ( name, startingValue, onTick, onClick, label ) { this.name = name; this.onTick = onTick ? onTick : function () { return 0; }; this.onTick.bind( this ); this.format = function ( value ) { if ( value > 1000000000000000 ) { return this.format( value / 1000000000000000 ) + "qi"; } if ( value > 1000000000000 ) { return this.format( value / 1000000000000 ) + "qa"; } if ( value > 1000000000 ) { return this.format( value / 1000000000 ) + "b"; } if ( value > 1000000 ) { return this.format( value / 1000000 ) + "m"; } if ( value > 1000 ) { return this.format( value / 1000 ) + "k"; } return Math.floor( value ) + "." + Math.floor( value * 10 ) % 10; }; this.update = function () { var ticked = this.onTick(); this.label.lastChild.previousSibling.innerHTML = this.format( this.value ); this.progress.value = ( this.value * 100 ) % 100; this.progress.setAttribute( 'title', ticked + ' per tick' ); this.progress.setAttribute( 'class', ticked < 0 ? 'red-bar' : ( ticked === 0 ? 'blue-bar' : 'green-bar' ) ); }; this.update.bind( this ); this.value = startingValue ? startingValue : 0; this.increase = function ( amount ) { this.value += !Number.isNaN( amount ) ? amount : 1; } this.decrease = function ( amount ) { if ( amount > this.value ) { throw "Not enough " + this.name; } this.value -= amount; } if ( onClick ) { this.button = document.createElement( 'button' ); this.button.innerHTML = label ? label : name + "-action"; this.button.onclick = onClick; game.buttons.appendChild( this.button ); } this.label = document.createElement( 'div' ); this.label.setAttribute( 'class', 'resource' ); this.label.appendChild( document.createElement( 'div' ) ); this.label.lastChild.innerHTML = this.name; this.label.appendChild( document.createElement( 'div' ) ); this.label.lastChild.innerHTML = this.format( Math.floor( this.value ) ); game.labels.appendChild( this.label ); this.progress = document.createElement( 'progress' ) this.label.appendChild( this.progress ); this.progress.setAttribute( 'value', 0 ); this.progress.setAttribute( 'max', 100 ); game.resources[this.name] = this; } game.resources.human = new game.resource( 'human', 1, function () { if ( game.resources['human'].value * 0.01 > game.resources["supplies"].value && game.resources['human'].value > 1 ) { game.resources.human.decrease( 0.01 ); return -0.01; } else if ( game.resources['human'].value < game.resources['house'].value * 10 ) { game.resources.human.increase( 0.01 ); return 0.01; } return 0; } ); game.resources.gold = new game.resource( 'gold', 50, function () { var tmp = 0.1 * game.resources.house.value + 0.01 * game.resources.human.value + 0.0001 - game.resources.farm.value*0.01; game.resources["gold"].value += tmp; return tmp; }, function () { game.resources["gold"].value++; }, 'Mine gold' ); game.resources.supplies = new game.resource( 'supplies', 25, function () { var tmp = game.resources.farm.value * 0.1 - 0.01 * game.resources.human.value game.resources.supplies.increase( tmp ) return tmp; }, function () { game.resources.supplies.increase( 1+game.resources.farm.value ) }, 'Gather Supplies' ); game.resources.house = new game.resource( 'house', 0, null, function ( event ) { event = event || window.event; if ( game.resources.gold.value > 100 * Math.pow( 1.1, game.resources.house.value ) ) { game.resources.gold.decrease( 100 * Math.pow( 1.1, game.resources.house.value ) ); game.resources.house.increase( 1 ); } }, 'Buy House' ); game.resources.farm = new game.resource( 'farm', 0, null, function ( event ) { event = event || window.event; if ( game.resources.gold.value > 100 * Math.pow( 1.1, game.resources.farm.value ) ) { game.resources.gold.decrease( 100 * Math.pow( 1.1, game.resources.farm.value ) ); game.resources.farm.increase( 1 ); } }, 'Buy Farm' );
JavaScript
0.000001
@@ -1131,16 +1131,19 @@ value ) +;// + %22.%22 +
600c13c52621e08f1444d230970258d8439a6970
Remove internal import from react-native
elements/Image.js
elements/Image.js
import React from "react"; import PropTypes from "prop-types"; import { Image, requireNativeComponent } from "react-native"; import ImageSourcePropType from "react-native/Libraries/Image/ImageSourcePropType"; import { ImageAttributes } from "../lib/attributes"; import { numberProp, touchableProps, responderProps } from "../lib/props"; import Shape from "./Shape"; import { meetOrSliceTypes, alignEnum } from "../lib/extract/extractViewBox"; import extractProps from "../lib/extract/extractProps"; const spacesRegExp = /\s+/; export default class extends Shape { static displayName = "Image"; static propTypes = { ...responderProps, ...touchableProps, x: numberProp, y: numberProp, width: numberProp.isRequired, height: numberProp.isRequired, href: ImageSourcePropType, preserveAspectRatio: PropTypes.string, }; static defaultProps = { x: 0, y: 0, width: 0, height: 0, preserveAspectRatio: "xMidYMid meet", }; setNativeProps = props => { this.root.setNativeProps(props); }; render() { const { props } = this; const { preserveAspectRatio, x, y, width, height, href } = props; const modes = preserveAspectRatio.trim().split(spacesRegExp); const meetOrSlice = meetOrSliceTypes[modes[1]] || 0; const align = alignEnum[modes[0]] || "xMidYMid"; return ( <RNSVGImage ref={ele => { this.root = ele; }} {...extractProps({ ...props, x: null, y: null }, this)} x={x} y={y} width={width} height={height} meetOrSlice={meetOrSlice} align={align} src={Image.resolveAssetSource(href)} /> ); } } const RNSVGImage = requireNativeComponent("RNSVGImage", null, { nativeOnly: ImageAttributes, });
JavaScript
0.000013
@@ -122,92 +122,8 @@ e%22;%0A -import ImageSourcePropType from %22react-native/Libraries/Image/ImageSourcePropType%22;%0A impo @@ -715,43 +715,8 @@ ed,%0A - href: ImageSourcePropType,%0A
f3b70e97c4d72e773d6880506de28afec94882e0
Fix testing component model
bin/ComponentModel/ComponentModel.test.js
bin/ComponentModel/ComponentModel.test.js
import React from 'react'; import ComponentModel from '../../../src/js/components/ui/ComponentModel/ComponentModel.js'; import styles from '../../../src/js/components/ui/ComponentModel/ComponentModel.scss'; import { shallow, configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; configure({ adapter: new Adapter() }); describe('Test ComponentModel component', () => { const mockFn = jest.fn(); const componentModel = shallow(<ComponentModel onClickHandler={mockFn}>Lorem ipsum</ComponentModel>); it('should be defined', () => { expect(ComponentModel).toBeDefined(); }); it('should render correctly', () => { expect(componentModel).toMatchSnapshot(); }); it('ComponentModel click event', () => { componentModel.find(`.${styles.componentModel}`).simulate('click'); expect(mockFn).toHaveBeenCalledTimes(1); }); });
JavaScript
0
@@ -571,17 +571,17 @@ expect( -C +c omponent
95182d5e71d0a140f148feb681cd6ed34620ea86
normalize react and react/addons requires
webpack.make.js
webpack.make.js
var fs = require('fs'), path = require('path'), mkdirp = require('mkdirp'), webpack = require('webpack'), ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = function buildWebpackConfig (options) { options = options || {}; var ENV = options.ENV || process.env.NODE_ENV || 'development', PRODUCTION = options.PRODUCTION || ENV === 'production', RENDERER = !!options.renderer; // shared values var publicPath = PRODUCTION ? '/assets/' : 'http://localhost:2992/assets/', outputPath = path.join(__dirname, 'public', RENDERER ? 'renderer' : 'assets'); // base var config = { devtool: 'sourcemap', externals: [], module: { loaders: [{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url-loader?limit=10000' }, { test: /\.(woff)$/, loader: 'url-loader?limit=100000' }, { test: /\.(ttf|eot)$/, loader: 'file-loader' }] }, // resolveLoader: { // root: path.join(__dirname, 'node_modules') // }, resolve: { // root: path.join(__dirname, 'client'), extensions: ['', '.js' , '.jsx'], // modulesDirectories: ['node_modules'] }, plugins: [ function statsPlugin () { function statsPluginDone (stats) { var jsonStats = stats.toJson(); jsonStats.publicPath = publicPath; mkdirp.sync(outputPath); fs.writeFileSync(path.join(outputPath, 'stats.json'), JSON.stringify(jsonStats)); } if (!RENDERER) this.plugin('done', statsPluginDone); }, new webpack.DefinePlugin({'process.env.NODE_ENV': JSON.stringify(ENV)}) ] }; // entry config.entry = { scripts: RENDERER ? './client/renderer.js' : './client/index.js' }; // output config.output = { path: outputPath, pathinfo: !PRODUCTION, publicPath: publicPath, libraryTarget: RENDERER ? 'commonjs2' : 'var', filename: RENDERER ? 'renderer.js' : PRODUCTION ? 'scripts.[hash].js' : 'scripts.dev.js' }; // externals if (RENDERER) { Array.prototype.push.apply(config.externals, [ 'react', 'fluxible', 'superagent', 'react-router', 'serialize-javascript' ]); } // loaders // var to5LoaderBlacklist = RENDERER ? '&blacklist=regenerator' : ''; config.module.loaders.push({ test: /\.js$/, loader: '6to5-loader?experimental&optional=selfContained', // + to5LoaderBlacklist, exclude: /.*node_modules.*/ }); var hotLoader = PRODUCTION || RENDERER ? '' : 'react-hot-loader!'; config.module.loaders.push({ test: /\.jsx$/, loader: hotLoader + '6to5-loader?experimental&optional=selfContained', // + to5LoaderBlacklist, exclude: /.*node_modules.*((?!\.jsx).{4}$)/ }); var lessLoader = 'css-loader?sourceMap!autoprefixer-loader!less-loader?sourceMap'; config.module.loaders.push({ test: /\.less$/, loader: PRODUCTION ? ExtractTextPlugin.extract(lessLoader) : 'style-loader!' + lessLoader }); // target config.target = RENDERER ? 'node' : 'web'; // plugins if (PRODUCTION) { // var cssName = PRODUCTION ? 'scripts.[hash].css' : 'scripts.dev.css' config.plugins.push(new ExtractTextPlugin('scripts.[hash].css')); } if (!RENDERER) { config.plugins.push( new webpack.PrefetchPlugin('react'), new webpack.PrefetchPlugin('react/lib/ReactComponentBrowserEnvironment') ); } if (PRODUCTION && !RENDERER) { config.plugins.push( new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.NoErrorsPlugin() ); } return config; };
JavaScript
0
@@ -3242,16 +3242,228 @@ .css')); +%0A%0A // Ensures requires for %60react%60 and %60react/addons%60 normalize to the same requirement%0A config.plugins.push(new webpack.NormalModuleReplacementPlugin(/%5Ereact(%5C/addons)?$/, require.resolve('react/addons'))) %0A %7D%0A i
4c85e1a8b9dd752dc0b291b22f4799ee73530b3b
Build v0.0.1
compound-subject.min.js
compound-subject.min.js
/*! compound-subject 2014-08-01 */ !function(){"use strict";var a=function(a){var b={},c="and",d=!1,e=",";return b.endWith=function(a){return"string"!=typeof a?b:(c=a,b)},b.delimitAll=function(){var a=arguments[0];return d="boolean"==typeof a?a:!0,b},b.delimitWith=function(a){return"string"!=typeof a?b:(e=a,b)},b.make=function(){var b,f,g=d?e+" "+c+" ":" "+c+" ";return!a instanceof Array?"":(b=a.slice(0,-2).join(e+" "),f=a.slice(a.length-2).join(g),b.length?b+e+" "+f:f)},b};if(module)module.exports=a;else{if(!window)throw new Error("Couldn't find a suitable scope in which to define compoundSubject");window.compoundSubject=a}}();
JavaScript
0.000011
@@ -364,16 +364,39 @@ %22;return +%22undefined%22==typeof a%7C%7C !a insta @@ -498,16 +498,36 @@ %7D,b%7D;if( +%22undefined%22!=typeof module)m @@ -550,17 +550,36 @@ else%7Bif( -! +%22undefined%22==typeof window)t
075081db587fee9580b92a7ee554128c7e7df63f
improve build plugin ordering
webpack.make.js
webpack.make.js
var fs = require('fs'), path = require('path'), mkdirp = require('mkdirp'), webpack = require('webpack'), ExtractTextPlugin = require('extract-text-webpack-plugin') module.exports = function buildWebpackConfig (options) { options = options || {} var ENV = options.ENV || process.env.NODE_ENV || 'development', SERVER = options.SERVER || process.env.SERVER, BUILD = options.BUILD || process.env.BUILD // shared values var publicPath = BUILD ? '/assets/' : 'http://localhost:8080/assets/' var outputPath = path.resolve('public', SERVER ? 'renderer' : 'assets') var excludeFromStats = [ /node_modules[\\\/]react(-router)?[\\\/]/ ] // base var config = { externals: [], module: { // noParse: [/react-with-addons/], loaders: [{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: BUILD ? 'url?limit=10000' : 'url' }, { test: /\.(woff)$/, loader: BUILD ? 'url?limit=100000' : 'url' }, { test: /\.(ttf|eot)$/, loader: 'file' }] }, resolve: { extensions: ['', '.js', '.jsx', '.less'] }, plugins: [ // TODO: only use when non-server? new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(ENV) }) ], devServer: { contentBase: './public', stats: { exclude: excludeFromStats, cached: false } } } // target config.target = SERVER ? 'node' : 'web' // Source maps config.devtool = BUILD ? 'source-map' : 'eval' // entry config.entry = { bshed: SERVER ? './client/renderer' : './client' } // externals if (SERVER) { // Every non-relative module is external config.externals.push(/^[a-z\-0-9]+$/) } // output var filename = SERVER ? 'index.js' : '[name].[hash].js' config.output = { path: outputPath, pathinfo: !BUILD, publicPath: publicPath, filename: filename, chunkFilename: '[id].[hash].js', libraryTarget: SERVER ? 'commonjs2' : void 0 } // loaders var babelLoader = 'babel?experimental&optional=runtime' // Webpack fails at parsing generator functions :( // babelLoader += SERVER ? '&blacklist=regenerator' : '' config.module.loaders.push({ test: /\.js$/, loader: babelLoader, exclude: /.*node_modules.*/ }) var hotLoader = BUILD || SERVER ? '' : 'react-hot!' config.module.loaders.push({ test: /\.jsx$/, loader: hotLoader + babelLoader, exclude: /.*node_modules.*((?!\.jsx).{4}$)/ }) var lessLoader = 'css?sourceMap!autoprefixer!less?sourceMap' lessLoader = BUILD ? ExtractTextPlugin.extract(lessLoader) : 'style!' + lessLoader config.module.loaders.push({ test: /\.less$/, loader: SERVER ? 'null' : lessLoader }) // plugins if (BUILD && !SERVER) { // Ensures requires for 'react' and 'react/addons' normalize to the same path var reactRegex = /^react(\/addons)?$/ var reactAddonsPath = require.resolve('react/dist/react-with-addons') config.plugins.push(new webpack.NormalModuleReplacementPlugin(reactRegex, reactAddonsPath)) // Minifify, dedupe, extract css config.plugins.push( new ExtractTextPlugin('[name].css?[contenthash]'), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.NoErrorsPlugin() ) } if (!SERVER) { config.plugins.push(new webpack.PrefetchPlugin('react')) config.plugins.push(StatsPlugin()) } return config function StatsPlugin () { return function () { this.plugin('done', saveStats) } function saveStats (stats) { var jsonStats = stats.toJson({ exclude: excludeFromStats, chunkModules: true }) jsonStats.publicPath = publicPath mkdirp.sync(outputPath) fs.writeFileSync(path.join(outputPath, 'stats.json'), JSON.stringify(jsonStats)) } } }
JavaScript
0
@@ -3194,25 +3194,18 @@ me%5D. -css?%5Bcontent +%5B hash%5D +.css '),%0A @@ -3226,24 +3226,15 @@ ack. -optimize.UglifyJ +NoError sPlu @@ -3293,39 +3293,48 @@ new webpack. -NoError +optimize.UglifyJ sPlugin()%0A )%0A
488aba6cf6a3241dfcb27232803065867351ab5f
Remove ngRoute
public/config.js
public/config.js
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'peopleMa'; var applicationModuleVendorDependencies = ['ngResource', 'ngCookies', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ngRoute', 'ui.router', 'ui.bootstrap', 'ui.utils']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
JavaScript
0.000001
@@ -318,19 +318,8 @@ ze', - 'ngRoute', 'ui
e24a5c61295a31a794430793efe9a38511f4c167
Use Babili (and source maps in prod)
webpack/base.js
webpack/base.js
const webpack = require('webpack') const { join } = require('path') const { TsConfigPathsPlugin } = require('awesome-typescript-loader') const { NODE_ENV } = process.env const isDev = NODE_ENV === 'development' module.exports = { output: { path: join(__dirname, '..', 'dist') }, // Enable sourcemaps for debugging webpack's output. devtool: isDev ? 'source-map' : 'none', resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: ['.ts', '.tsx', '.js', '.json'], plugins: [new TsConfigPathsPlugin()] }, module: { rules: [ // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. { test: /\.tsx?$/, loader: 'awesome-typescript-loader', options: { transpileOnly: true } }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader', exclude: [/node_modules\/apollo-client/] }, // Handle .graphql { test: /\.graphql$/, loader: 'graphql-tag/loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV || 'production') }) ], watch: isDev, watchOptions: { ignored: /node_modules/ } }
JavaScript
0
@@ -129,16 +129,70 @@ loader') +%0Aconst BabiliPlugin = require('babili-webpack-plugin') %0A%0Aconst @@ -400,16 +400,8 @@ ool: - isDev ? 'so @@ -413,17 +413,8 @@ map' - : 'none' ,%0A%0A%09 @@ -1115,16 +1115,54 @@ gins: %5B%0A +%09%09!isDev ? new BabiliPlugin() : null,%0A %09%09new we
f34ee624dce4a9618f5958928461accc72ecf3cf
Use property filter inside of tableContent property.
app/components/expenses-table.js
app/components/expenses-table.js
import Ember from 'ember'; import $ from 'jquery'; import moment from 'npm:moment'; export default Ember.Component.extend({ userSettings: Ember.inject.service('user-settings'), sortAscending: false, searchQuery: '', tableViewSettings: 'all', init () { this._super(); this.set('currency', this.get('userSettings').currency()); }, actions: { sortByProperty (property) { this.sortValues(property); }, tableViewSettings (settings) { if (this.get('tableViewSettings') === settings) { return; } $('.table-view-settings button').removeClass('mdl-button--raised'); $(`#btn-${settings}`).addClass('mdl-button--raised'); this.set('tableViewSettings', settings); } }, sortValues (property) { if (this.get('sortAscending')) { const dataSorted = this.get('data').sortBy(property); this.set('data', dataSorted); } else { const dataSorted = this.get('data').sortBy(property).reverse(); this.set('data', dataSorted); } this.set('sortAscending', !this.get('sortAscending')); }, tableContent: function () { let filter = this.get('searchQuery'); let data = this.setContentView(this.get('data')); if (this.get('searchQuery').length) { // Display data based on searchQuery let filteredContent = data.filter(function (item, index, enumerable) { return item.get('name').toLowerCase().match(filter.toLowerCase()) || item.get('category').toLowerCase().match(filter.toLowerCase()); }); return filteredContent; } // Display latest on top // Default values if search field empty return data; }.property('searchQuery', 'data.@each', 'tableViewSettings'), setContentView (data) { if (!data) { return; } let dataToDisplay; switch (this.get('tableViewSettings')) { case 'today': dataToDisplay = data.filter((item, index, enumerable) => { let currentTimestamp = item.get('timestamp'); return moment(currentTimestamp).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD'); }); break; case 'week': let oldestAllowed = moment().subtract(7, 'days').toDate().getTime(); dataToDisplay = data.filter((item, index, enumerable) => { return item.get('timestamp') >= oldestAllowed; }); break; default: dataToDisplay = data; } return dataToDisplay; } });
JavaScript
0
@@ -242,12 +242,39 @@ s: ' -all' +today',%0A sortByProperty: false ,%0A%0A @@ -759,40 +759,100 @@ %0A%0A -sortValues (property) %7B%0A if ( +applyPropertyFilter (data, property) %7B%0A if (property) %7B%0A this.set('sortAscending', ! this @@ -877,107 +877,89 @@ g')) - %7B +; %0A -const dataSorted = this.get('data').sortBy(property);%0A this.set('data', +if (this.get('sortAscending')) %7B%0A return data -Sorted +.sortBy(property );%0A + @@ -977,43 +977,21 @@ -const dataSorted = this.get(' + return data -') .sor @@ -1025,103 +1025,77 @@ -this.set('data', dataSorted);%0A %7D%0A%0A this.set('sortAscending', !this.get('sortAscending')); +%7D%0A %7D else %7B%0A return data.sortBy('timestamp').reverse();%0A %7D %0A %7D @@ -1127,26 +1127,28 @@ on () %7B%0A -le +cons t filter = t @@ -1171,26 +1171,28 @@ uery');%0A -le +cons t data = thi @@ -1231,40 +1231,376 @@ ));%0A -%0A -if (this.get('searchQuery') +const filterPropety = this.get('sortByProperty');%0A%0A /*%0A Reset property filter each time content changes or is being filtered. It%0A ensures that latest item is always on top when another filter is being%0A applied or expense is added to db%0A */%0A this.set('sortByProperty', false);%0A%0A // Filter by search field value if not empty%0A if (filter .len @@ -1894,120 +1894,158 @@ urn -filteredContent;%0A %7D%0A%0A // Display latest on top%0A // Default values if search field empty%0A return data +this.applyPropertyFilter(filteredContent, filterPropety);%0A %7D%0A%0A // Display latest on top%0A return this.applyPropertyFilter(data, filterPropety) ;%0A @@ -2103,16 +2103,34 @@ ettings' +, 'sortByProperty' ),%0A%0A se
c5812928e86f5e00773eba6ba52f5df76475740c
use user-data api, cleanup
verify/repository.js
verify/repository.js
var exec = require('child_process').exec var fs = require('fs') var helper = require('../verify/helpers.js') var userData = require('../data.json') var addtoList = helper.addtoList var markChallengeCompleted = helper.markChallengeCompleted var writeData = helper.writeData var currentChallenge = 'repository' module.exports = function repositoryVerify (path) { // path should be a directory if (!fs.lstatSync(path).isDirectory()) return addtoList("Path is not a directory", false) exec('git status', {cwd: path}, function(err, stdout, stdrr) { // if (err) { // console.log(err) // return addtoList(err.message, false) // } // can't return on error since git's 'fatal' not a repo is an error // potentially read file, look for '.git' directory var status = stdout.trim() if (status.match("On branch")) { addtoList("This is a Git repository!", true) markChallengeCompleted(currentChallenge) writeData(userData, currentChallenge) } else addtoList("This folder isn't being tracked by Git.", false) }) }
JavaScript
0
@@ -134,17 +134,24 @@ '../ +lib/user- data.js -on ')%0A%0A @@ -246,41 +246,110 @@ ted%0A -var writeData = helper.writeData%0A +%0A// do I want to do this as a var? un-needed, also can't browser view%0A// pass in the challenge string? %0Avar @@ -524,17 +524,17 @@ dtoList( -%22 +' Path is @@ -548,17 +548,17 @@ irectory -%22 +' , false) @@ -600,16 +600,17 @@ function + (err, st @@ -627,19 +627,16 @@ r) %7B%0A - // if (err @@ -640,45 +640,8 @@ err) - %7B%0A // console.log(err)%0A // ret @@ -678,17 +678,8 @@ se)%0A - // %7D%0A @@ -854,17 +854,17 @@ s.match( -%22 +' On branc @@ -864,17 +864,17 @@ n branch -%22 +' )) %7B%0A @@ -882,25 +882,25 @@ addtoList( -%22 +' This is a Gi @@ -912,17 +912,17 @@ ository! -%22 +' , true)%0A @@ -978,28 +978,28 @@ -writeData(user +userData.update Data -, +( curr
7d05b5cc814488bb82f58a901b7cf0c5c54477d4
Remove jsx from nodemon watching b/c it's idiotic to restart the server on every change
gulp/config.js
gulp/config.js
var dest = "./build"; var src = './src'; var port = 3000; module.exports = { nodemon: { script: './server.js', ext: 'js,jsx', ignore: ['build/*', 'node_modules/*'], env: { 'NODE_ENV': 'development', 'DEBUG': 'Server', 'PORT': port } }, browserSync: { // Don't use browsersync's static browser. // We just proxy into the actual server.js here. proxy: 'localhost:' + port, port: port + 1, notify: false, open: false }, sass: { src: src + "/sass/**/*.{sass,scss}", dest: dest + "/css", settings: { // Required if you want to use SASS syntax // See https://github.com/dlmanning/gulp-sass/issues/81 sourceComments: 'map', imagePath: '/images' // Used by the image-url helper } }, images: { src: src + "/images/**", dest: dest + "/images" }, markup: { src: src + "/html/**/*.html", dest: dest }, browserify: { // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + '/javascript/client.js', dest: dest + '/js', outputName: 'client.js', extensions: ['.js', '.jsx'] }] }, production: { cssSrc: dest + '/css/*.css', jsSrc: dest + '/js/*.js', dest: dest }, heroku: { development: { branch: 'dev', remoteName: 'dev', remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_DEV.git', website: 'http://HEROKU_APP_NAME_DEV.herokuapp.com' }, staging: { branch: 'staging', remoteName: 'staging', remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_STAGING.git', website: 'http://HEROKU_APP_NAME_STAGING.herokuapp.com' }, production: { branch: 'master', remoteName: 'prod', remoteUrl: 'https://git.heroku.com/HEROKU_APP_NAME_PRODUCTION.git', website: 'http://HEROKU_APP_NAME_PRODUCTION.herokuapp.com' } }, settings: { src: './settings.json', dest: dest } };
JavaScript
0
@@ -137,12 +137,8 @@ 'js -,jsx ',%0A
5bc7d2472cdae5fd3a6f2b73de926d9d33bb86aa
fix path to contributors.json
gulp/tasks/build-contributors.js
gulp/tasks/build-contributors.js
(function () { 'use strict'; var colors = require('colors'); var child_process = require('child_process'); /** * Note 'githubcontrib' may require a application-scoped access token: GITHUB_API_TOKEN */ exports.task = function () { var taskPath = __dirname; var appPath = `${taskPath}/../../dist/docs`; exec([ `rm -f ${appPath}/contributors.json`, `githubcontrib --owner=angular --repository=material --cols=6 --format=json --showlogin=true --sortBy=login --sha=master > ${appPath}/contributors.json` ]); }; exports.dependencies = []; /** utility method for executing terminal commands */ function exec (cmd, userOptions) { if (cmd instanceof Array) { return cmd.map(function (cmd) { return exec(cmd, userOptions); }); } try { var options = { } ; for (var key in userOptions) options[ key ] = userOptions[ key ]; return child_process.execSync(cmd + ' 2> /dev/null', options).toString().trim(); } catch (err) { return err; } } /** outputs done text when a task is completed */ function done () { log('done'.green); } /** outputs to the terminal with string variable replacement */ function log (msg) { console.log(msg || ''); } })();
JavaScript
0.000004
@@ -303,26 +303,8 @@ = %60 -$%7BtaskPath%7D/../../ dist
4b707d9da54fb68888a5494fcd9d6d64036446c1
Update for new Moment.js API
scripts/time.js
scripts/time.js
/* * Clock plugin using Moment.js (http://momentjs.com/) to * format the time and date. * * The only exposed property, 'format', determines the * format (see Moment.js documentation) to display time and date. * * Requires 'jquery' and 'moment' to be available through RequireJS. */ define(['jquery', 'moment'], function ($, moment) { "use strict"; var config = { format: 'llll' }; function updateClock() { var dt = moment(); var clockText = dt.format(config.format); $('.widget-time').text(clockText); var interval = 59 - dt.second(); if (interval < 1) { interval = 1; } else if (interval > 5) { interval = 5; } setTimeout(updateClock, interval * 1000); } $(document).ready(function () { var lang = navigator.language; if (moment.langData(lang)) { moment.lang(lang); } else { moment.lang(navigator.language.replace(/-.+/, '')); } updateClock(); }); return config; });
JavaScript
0
@@ -803,19 +803,21 @@ moment.l -ang +ocale Data(lan @@ -836,19 +836,21 @@ moment.l -ang +ocale (lang);%0A @@ -876,19 +876,21 @@ moment.l -ang +ocale (navigat
2ec172a7fda8eab985e79bf83e53864f7fb2eeb0
Handle error objects better (#6053)
app/core/Tracker2/BaseTracker.js
app/core/Tracker2/BaseTracker.js
export const TRACKER_LOGGING_ENABLED_QUERY_PARAM = 'tracker_logging'; export const DEFAULT_USER_TRAITS_TO_REPORT = [ 'email', 'anonymous', 'dateCreated', 'hourOfCode', 'name', 'referrer', 'testGroupNumber', 'testGroupNumberUS', 'gender', 'lastLevel', 'siteref', 'ageRange', 'schoolName', 'coursePrepaidID', 'role', 'firstName', 'lastName', 'dateCreated' ] export const DEFAULT_TRACKER_INIT_TIMEOUT = 12000; export function extractDefaultUserTraits(me) { return DEFAULT_USER_TRAITS_TO_REPORT.reduce((obj, key) => { const meAttr = me[key] if (typeof meAttr !== 'undefined' && meAttr !== null) { obj[key] = meAttr } return obj; }, {}) } /** * A baseline tracker that: * 1. Defines a standard initialization flow for all trackers * 2. Exposes an event emitter interface for all trackers * 3. Exposes a default tracker interface with a noop implementation. * * Standard initialization flow: * The standard initialization flow is based around the this.initializationComplete promise * that is exposed publicly by the tracker. This promise should be resolved by the tracker * by calling this.onInitializationSuccess (or this.onInitializationError) when the * initialization process has been completed (or failed). The initializationComplete * promise should _never_ be overwritten as other external components can depend on it. */ export default class BaseTracker { constructor () { this.initializing = false this.initialized = false this.setupInitialization() this.loggingEnabled = false try { this.loggingEnabled = (new URLSearchParams(window.location.search)).has(TRACKER_LOGGING_ENABLED_QUERY_PARAM) } catch (e) {} this.trackerInitTimeout = DEFAULT_TRACKER_INIT_TIMEOUT; } async identify (traits = {}) {} async resetIdentity () {} async trackPageView (includeIntegrations = []) {} async trackEvent (action, properties = {}, includeIntegrations = []) {} async trackTiming (duration, category, variable, label) {} watchForDisableAllTrackingChanges (store) { this.disableAllTracking = store.getters['tracker/disableAllTracking'] store.watch( (state, getters) => getters['tracker/disableAllTracking'], (result) => { this.disableAllTracking = result } ) } get isInitialized () { return this.initialized } set isInitialized (initialized) { return this.initialized = initialized } get isInitializing () { return this.initializing } set isInitializing (initializing) { return this.initializing = initializing } get initializationComplete () { return this.initializationCompletePromise } /** * Standard initialization method to be used to initialize the tracker. Ensures that the * initialize process is only called once and returns the initializationComplete promise. * * Calls internal initialize method */ async initialize () { if (this.isInitializing) { return this.initializationComplete } this.isInitializing = true const initTimeout = new Promise((resolve, reject) => { setTimeout(() => reject('Tracker init timeout'), this.trackerInitTimeout) }) try { await Promise.race([initTimeout, this._initializeTracker()]) } catch (e) { this.onInitializeFail(e) } return this.initializationComplete } /** * Internal tracker initialization method to be implemented by sub trackers. This is * called by the initialize method when the tracker is initialized. * * This method _must_ call onInitializeSuccess or onInitializeFail */ async _initializeTracker () { this.onInitializeSuccess() } /** * Sets up initialization callbacks and top level promise so that * all internal methods can wait on an internal initialize promise. * * This must be called from constructor _before_ initialize is called. */ setupInitialization () { const finishInitialization = (result) => { this.isInitialized = result // We only want to resolve / reject the init promise once during the initialization flow. Because some trackers // do not support reporting "failures" we need to support timeouts that can result in race conditions in some // situations. In these situations we use the first success / fail callback to determine the tracker state and // we change the callbacks to noops to prevent later calls from changing the init state. this.onInitializeSuccess = () => {} this.onInitializeFail = () => {} } this.initializationCompletePromise = new Promise((resolve, reject) => { this.onInitializeSuccess = () => { resolve() finishInitialization(true) } this.onInitializeFail = () => { reject() finishInitialization(false) } }) } log (...args) { if (!this.loggingEnabled) { return } console.info(`[tracker] [${this.constructor.name}]`, ...args) } }
JavaScript
0
@@ -61,18 +61,17 @@ logging' -; %0A + %0Aexport @@ -405,17 +405,16 @@ = 12000 -; %0A%0Aexport @@ -648,17 +648,16 @@ turn obj -; %0A %7D, %7B%7D @@ -1756,9 +1756,8 @@ EOUT -; %0A %7D @@ -3117,16 +3117,26 @@ reject( +new Error( 'Tracker @@ -3150,16 +3150,17 @@ imeout') +) , this.t @@ -4754,24 +4754,25 @@ lizeFail = ( +e ) =%3E %7B%0A @@ -4781,16 +4781,17 @@ reject( +e )%0A
7a49bcacbb557caca510ea8a044e4a57a62a8733
Add additional property to pass to weatherCard.
lib/components/App.js
lib/components/App.js
import React, {Component} from 'react'; import $ from 'jquery'; import CurrentWeatherCard from './CurrentWeatherCard'; export default class App extends Component { constructor(){ super() this.state = { location:'', responseData: null, currentData: null, forecastData: null, hourlyData: null, }; } handleInput(e) { this.setState({ location: e.target.value, }) } handleSubmit(){ const currentLocation = this.state.location $.get(`http://api.wunderground.com/api/878e77b9c3411d19/hourly/conditions/forecast10day/q/${currentLocation}.json`).then((data)=> { this.handleData(data) }) } handleData(weatherData){ const keys = Object.keys(weatherData) this.setState({ location:'', responseData:weatherData[keys[0]], currentData:weatherData[keys[1]], forecastData:weatherData[keys[2]], hourlyData:weatherData[keys[3]], }) } render() { return ( <div> <navbar> <input type="text" value={this.state.location} onChange={this.handleInput.bind(this)}/> <input type="submit" onClick={this.handleSubmit.bind(this)}/> </navbar> <h1 className="welcomeHeader">Weathrly</h1> <CurrentWeatherCard weatherData={this.state.weatherData}/> </div> ) } }
JavaScript
0
@@ -1267,23 +1267,61 @@ herCard -weather +currentData=%7Bthis.state.currentData%7D forecast Data=%7Bth @@ -1329,23 +1329,24 @@ s.state. -weather +forecast Data%7D/%3E%0A
53426146036a2711f2984e8a85e37cbcb1d1fa25
Fix the build
app/frontend/app/models/group.js
app/frontend/app/models/group.js
import DS from 'ember-data'; import ModelTruncatedDetails from '../mixins/model-truncated-details'; export default DS.Model.extend(ModelTruncatedDetails, { name: DS.attr('string'), bio: DS.attr('string'), about: DS.attr('string'), aboutFormatted: DS.attr('string'), coverImageUrl: DS.attr('string'), avatarUrl: DS.attr('string'), memberCount: DS.attr('number'), members: DS.hasMany('group-member'), currentMember: DS.belongsTo('group-member'), aboutDisplay: Ember.computed.any('aboutFormatted', 'about'), coverImageStyle: function() { return "background: url(" + this.get('coverImageUrl') + ") center;"; }.property('coverImageUrl'), // Fixes the fact that viewing all members adds to the members // association. recentMembers: function() { var members = this.get('members'); return members.filterBy('pending', false).slice(0, 14); }.property('members.@each'), getMember: function(user, includePending = false) { var members = this.get('members'); if (!includePending) { members = members.filterBy('pending', false); } return members.findBy('user.id', user.get('id')); } });
JavaScript
0.000254
@@ -1,12 +1,39 @@ +import Ember from 'ember';%0A import DS fr
ce262962f600d4d5f4ac061527167a9e4f7617d0
Fix loopback model transformation
lib/contentful/dao.js
lib/contentful/dao.js
const debug = require('debug')('loopback:connector:contentful'); const _ = require('lodash'); const mixinMeta = require('./meta'); const queryHelper = require('./query'); module.exports = Connector => class MixinDAO extends mixinMeta(Connector) { create(model, data, options, cb) { if (!this.contentful.space) { return cb(new Error('Management access token is required.')); } const contentType = this.getContentType(model); this.contentful.space.createEntry(contentType.sys.id, { fields: this.toDatabase(model, data), }) .then(entry => entry.publish()) .then((entry) => { const id = entry.sys.id; const rev = entry.sys.version; process.nextTick(() => cb(null, id, rev)); }) .catch(err => cb(err)); } updateAttributes(model, id, data, cb) { this.updateAll(model, { id }, data, {}, cb); } update(model, where, data, options, cb) { this.updateAll(model, where, data, options, cb); } updateAll(model, where, data, options, cb) { if (!this.contentful.space) { cb(new Error('Management access token is required.')); return; } if (this.debug) { debug('updateAll', model, where, data); } const idName = this.idName(model); delete data[idName]; data = this.toDatabase(model, data); this.getEntries(model, { where, contentful: { api: 'management' } }) .then(entries => Promise.all(_.map(entries.items, (entry) => { _.assign(entry.fields, data); return entry.update(); }))) .then(entries => Promise.all(_.map(entries, (entry) => entry.publish()))) .then(entries => process.nextTick(() => cb(null, { count: entries.length }))) .catch(err => cb(err)); } all(model, filter, options, cb) { this.getEntries(model, filter) .then((entries) => { let data = entries; if (!this.settings.respectContentfulClass) { data = entries.toPlainObject(); data = _.map(data.items, item => this.toLoopback(model, item)); } process.nextTick(() => { cb(null, data); }); }) .catch(err => cb(err)); } count(model, filter, options, cb) { filter.limit = 1; return this.getEntries(model, filter) .then((entries) => { cb(null, entries.total); }) .catch(err => cb(err)); } getEntries(model, filter) { if (this.debug) { debug('getEntries', model, filter); } filter = filter || {}; const idName = this.idName(model); const query = queryHelper.buildFilter(model, idName, filter); query.content_type = this.getContentType(model).sys.id; const contentful = filter.contentful || {}; switch (contentful.api || 'delivery') { case 'preview': if (this.clients.preview) { return this.clients.preview.getEntries(query); } break; case 'management': if (this.contentful.space) { return this.contentful.space.getEntries(query); } else if (this.clients.management) { const spaceId = this.getContentfulSettings(model).spaceId; return this.clients.management.getSpace(spaceId).getEntries(query); } break; case 'delivery': default: if (this.clients.delivery) { return this.clients.delivery.getEntries(query); } break; } return Promise.reject(new Error('No contentful clients found.')); } toLoopback(model, data, locale = null) { locale = locale || this.getDefaultLocale(model); const idName = model === 'Asset' ? 'id' : this.idName(model); const rels = model === 'Asset' ? {} : (this.getModelDefinition(model).settings.relations || {}); const d = _.mapValues(data.fields, (field, key) => { let f = null; if (_.has(field, locale)) { f = field[locale]; } else { f = field; if (rels[key]) { const relDefinition = rels[key]; if (Array.isArray(f)) { f = _.map(f, r => this.toLoopback(relDefinition.model, r, relDefinition.model === 'Asset' ? locale : null)); } else { f = this.toLoopback(relDefinition.model, f, relDefinition.model === 'Asset' ? locale : null); } } } return f; }); d[idName] = data.sys.id; d.createdAt = data.sys.createdAt; d.createdBy = data.sys.createdBy; d.updatedAt = data.sys.updatedAt; d.updatedBy = data.sys.updatedBy; d.version = data.sys.version || data.sys.revision; return d; } toDatabase(model, data) { const locale = this.getDefaultLocale(model); const d = _.mapValues(data, field => ({ [locale]: field })); return d; } };
JavaScript
0.000001
@@ -3877,17 +3877,16 @@ ? %7B%7D : -( this.get @@ -3930,15 +3930,8 @@ ions - %7C%7C %7B%7D) ;%0A%0A @@ -4004,20 +4004,21 @@ let f = -null +field ;%0A @@ -4095,60 +4095,32 @@ lse -%7B%0A f = field;%0A if +if (_.has (rels -%5Bkey%5D +, key) ) %7B%0A - @@ -4164,26 +4164,24 @@ ;%0A - if (Array.is @@ -4188,26 +4188,24 @@ Array(f)) %7B%0A - @@ -4319,26 +4319,24 @@ ;%0A - %7D else %7B%0A @@ -4332,18 +4332,16 @@ else %7B%0A - @@ -4442,22 +4442,8 @@ l);%0A - %7D%0A
c6833e323731f284785db1e7645603c74f2f4ef0
Fix jslint issues.
extension/content_script.js
extension/content_script.js
/*global chrome*/ "use strict"; function receiveMessage(event) { switch (event.data.text) { case "flooScreenDoWeHaveAnExtension": window.postMessage({name: "flooScreenHasExtension"}, "*"); break; case "flooScreenShare": chrome.runtime.sendMessage({action: "getScreen"}, function (id) { window.postMessage({name: "flooScreenShareResponse", id: id}, "*"); }); break; } } function main() { window.addEventListener("message", receiveMessage, false); window.postMessage({name: "flooScreenHasExtension"}, "*"); } main();
JavaScript
0
@@ -88,18 +88,16 @@ text) %7B%0A - case %22 @@ -128,18 +128,16 @@ nsion%22:%0A - wind @@ -195,27 +195,23 @@ %22);%0A - break;%0A - case %22 @@ -232,18 +232,16 @@ e%22:%0A - chrome.r @@ -298,18 +298,16 @@ (id) %7B%0A - wi @@ -380,16 +380,12 @@ - %7D);%0A -
ef842f5be520054a12eb9037994f53ddcc185166
Fix key listener to allow holding down of modifier keys. Allow native keydown actions.
app/keys.js
app/keys.js
'use strict'; const defaultKeyMap = (function() { const keys = { 'Enter': {type: 'INSERT_NEW_LINE'}, 'Tab': {type: 'INSERT', text: ' '}, // TODO: Change this to reflect preferences/mode etc. 'Backspace': {type: 'DELETE_BACK_CHAR'}, 'Control-k': {type: 'KILL_LINE'}, 'ArrowLeft': {type: 'MOVE_CURSOR_LEFT'}, 'Control-b': {type: 'MOVE_CURSOR_LEFT'}, 'ArrowRight': {type: 'MOVE_CURSOR_RIGHT'}, 'Control-f': {type: 'MOVE_CURSOR_RIGHT'}, 'ArrowUp': {type: 'MOVE_CURSOR_UP'}, 'Control-p': {type: 'MOVE_CURSOR_UP'}, 'ArrowDown': {type: 'MOVE_CURSOR_DOWN'}, 'Control-n': {type: 'MOVE_CURSOR_DOWN'}, 'Control-a': {type: 'MOVE_CURSOR_BEGINNING_OF_LINE'}, 'Control-e': {type: 'MOVE_CURSOR_END_OF_LINE'} }; ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'].forEach(e => { keys[e] = {type: 'INSERT', text: e}; keys[e.toUpperCase()] = {type: 'INSERT', text: e.toUpperCase()}; }); [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].forEach(e => { keys[e] = {type: 'INSERT', text: (e + '')}; }); [' ', ',', '<', '.', '>', '[', '{', ']', '}', '\\', '|', '/', '?', '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', ':', ';', '"', '\''].forEach(e => { keys[e] = {type: 'INSERT', text: e}; }); return keys; }()); function createKeyListener(elem, keyMap, onKeyAction, onKeyError) { const activeModifiers = []; elem.addEventListener('keydown', (e) => { e.preventDefault(); if (keyIsModifier(e.key)) { activeModifiers.push(e.key); return; } const withModifiers = activeModifiers.length === 0 ? e.key : activeModifiers.join('-') + '-' + e.key; const action = keyMap[withModifiers]; if (action) { onKeyAction(action); } else { onKeyError(withModifiers); } activeModifiers.splice(0, activeModifiers.length); }); elem.addEventListener('keypress', (e) => { e.preventDefault(); }); elem.addEventListener('keyup', (e) => { e.preventDefault(); const index = activeModifiers.indexOf(e.key); if (index !== -1) { activeModifiers.splice(index, 1); } }); function keyIsModifier(key) { return key === 'Control' || key === 'Alt' || key === 'Meta'; } const allChords = Object.keys(keyMap); function isValidActionPrefix(prefix) { const pattern = new RegExp(prefix); return allChords.find(e => pattern.test(e)); } }; module.exports = { defaultKeyMap, createKeyListener };
JavaScript
0
@@ -81,24 +81,27 @@ nter': + %7Btype: 'INSE @@ -129,16 +129,19 @@ 'Tab': + @@ -246,16 +246,19 @@ kspace': + %7Btype: @@ -299,16 +299,19 @@ trol-k': + %7Btype: @@ -345,16 +345,19 @@ owLeft': + %7Btype: @@ -398,16 +398,19 @@ trol-b': + %7Btype: @@ -452,16 +452,19 @@ wRight': + %7Btype: @@ -505,16 +505,19 @@ trol-f': + %7Btype: @@ -557,24 +557,27 @@ rrowUp': + + %7Btype: 'MOVE @@ -610,16 +610,19 @@ trol-p': + %7Btype: @@ -661,16 +661,19 @@ owDown': + %7Btype: @@ -714,16 +714,19 @@ trol-n': + %7Btype: @@ -767,16 +767,19 @@ trol-a': + %7Btype: @@ -833,16 +833,19 @@ trol-e': + %7Btype: @@ -871,16 +871,104 @@ F_LINE'%7D +,%0A 'Alt-Meta-Dead': %7Btype: 'NATIVE!'%7D,%0A 'Meta-q': %7Btype: 'NATIVE!'%7D %0A %7D;%0A @@ -1850,37 +1850,8 @@ %3E %7B%0A - e.preventDefault();%0A%0A @@ -2174,24 +2174,107 @@ (action) %7B%0A + if (action.type === 'NATIVE!') %7B%0A return;%0A %7D%0A @@ -2373,59 +2373,28 @@ -activeModifiers.splice(0, activeModifiers.length + e.preventDefault( ); - %0A @@ -2555,24 +2555,16 @@ ault();%0A - %0A
01eaea7fe1d2a284988d3ef0d0d7abc7b7b75e5a
Add missing scenes
app/main.js
app/main.js
import React, { Component } from 'react'; import { View, StatusBar, Image, Alert, BackAndroid, Keyboard, StyleSheet, } from 'react-native'; import { Scene, Router } from 'react-native-router-flux'; import { connect } from 'react-redux'; import AppSettings from './AppSettings'; import css from './styles/css'; import general from './util/general'; // GPS import GeoLocationContainer from './containers/geoLocationContainer'; // VIEWS import Home from './views/Home'; import SurfReport from './views/weather/SurfReport'; import ShuttleStop from './views/shuttle/ShuttleStop'; import DiningDetail from './views/dining/DiningDetail'; import DiningNutrition from './views/dining/DiningNutrition'; import EventDetail from './views/events/EventDetail'; import WebWrapper from './views/WebWrapper'; import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView'; import NewsDetail from './views/news/NewsDetail'; import FeedbackView from './views/FeedbackView'; import PreferencesView from './views/preferences/PreferencesView'; import NearbyMapView from './views/mapsearch/NearbyMapView'; import TabIcons from './navigation/TabIcons'; import DataListViewAll from './views/common/DataListViewAll'; import ConferenceFullScheduleView from './views/conference/ConferenceFullScheduleView'; import ConferenceMyScheduleView from './views/conference/ConferenceMyScheduleView'; import ConferenceDetailView from './views/conference/ConferenceDetailView'; const RouterWithRedux = connect()(Router); export default class Main extends Component { constructor(props) { super(props); this.state = { hideTabs: false }; } campusLogo() { return (<Image source={require('./assets/img/UCSanDiegoLogo-White.png')} style={css.navCampusLogoTitle} />); } _exitHandler = () => { Alert.alert( 'Exit', 'Are you sure you want to exit this app?', [ { text: 'Cancel', onPress: () => {} }, { text: 'Yes', onPress: () => BackAndroid.exitApp() } ] ); return true; } render() { if (general.platformIOS()) { StatusBar.setBarStyle('light-content'); } else if (general.platformAndroid()) { StatusBar.setBackgroundColor('#101d32', false); } return ( <View style={css.flex}> <RouterWithRedux navigationBarStyle={general.platformIOS() ? css.navIOS : css.navAndroid} titleStyle={general.platformIOS() ? css.navIOSTitle : css.navAndroidTitle} barButtonIconStyle={general.platformIOS() ? css.navIOSIconStyle : css.navAndroidIconStyle} backButtonTextStyle={general.platformIOS() ? css.navBackButtonTextIOS : css.navBackButtonTextAndroid} backTitle="Back" onExitApp={this._exitHandler} > <Scene key="root"> <Scene key="tabbar" tabs hideOnChildTabs initial tabBarStyle={general.platformIOS() ? css.tabBarIOS : css.tabBarAndroid} > <Scene key="tab1" title={AppSettings.APP_NAME} initial icon={TabIcons}> <Scene key="Home" component={Home} renderTitle={() => this.campusLogo()} /> <Scene key="SurfReport" component={SurfReport} title="Surf Report" /> <Scene key="ShuttleStop" component={ShuttleStop} title="Shuttle" /> <Scene key="DiningDetail" component={DiningDetail} title="Dining" /> <Scene key="DiningNutrition" component={DiningNutrition} title="Nutrition" /> <Scene key="EventDetail" component={EventDetail} title="Events" /> <Scene key="WebWrapper" component={WebWrapper} /> <Scene key="WelcomeWeekView" component={WelcomeWeekView} title="Welcome Week" /> <Scene key="NewsDetail" component={NewsDetail} title="News" /> <Scene key="DataListViewAll" component={DataListViewAll} /> <Scene key="ConferenceBar" tabs tabBarStyle={general.platformIOS() ? css.tabBarIOS : css.tabBarAndroid} tabBarSelectedItemStyle={styles.selectedTab} > <Scene key="con1" initial icon={TabIcons} title="Full"> <Scene key="ConferenceFullScheduleView" component={ConferenceFullScheduleView} /> </Scene> <Scene key="con2" icon={TabIcons} title="Mine"> <Scene key="ConferenceMyScheduleView" component={ConferenceMyScheduleView} /> </Scene> </Scene> <Scene key="ConferenceDetailView" component={ConferenceDetailView} /> </Scene> <Scene key="tab2" title="Map" component={NearbyMapView} icon={TabIcons} /> <Scene key="tab3" title="Feedback" component={FeedbackView} icon={TabIcons} /> <Scene key="tab4" title="Settings" component={PreferencesView} icon={TabIcons} /> </Scene> </Scene> </RouterWithRedux> </View> ); } } const styles = StyleSheet.create({ selectedTab: { backgroundColor: '#DDD' } });
JavaScript
0.001415
@@ -1444,16 +1444,237 @@ ilView'; +%0Aimport ShuttleRoutesListView from './views/shuttle/ShuttleRoutesListView';%0Aimport ShuttleStopsListView from './views/shuttle/ShuttleStopsListView';%0Aimport ShuttleSavedListView from './views/shuttle/ShuttleSavedListView'; %0A%0Aconst @@ -3887,24 +3887,322 @@ ViewAll%7D /%3E%0A +%09%09%09%09%09%09%09%09%3CScene key=%22ShuttleRoutesListView%22 component=%7BShuttleRoutesListView%7D title=%22Choose Route%22 /%3E%0A%09%09%09%09%09%09%09%09%3CScene key=%22ShuttleStopsListView%22 component=%7BShuttleStopsListView%7D title=%22Choose Stop%22 /%3E%0A%09%09%09%09%09%09%09%09%3CScene key=%22ShuttleSavedListView%22 component=%7BShuttleSavedListView%7D title=%22Manage Stops%22 /%3E%0A %09%09%09%09%09%09%09%09%3CSce
40b9521f4e05eed0bf03accf868f5a4e844e3b9f
Remove line break in includes params
app/routes/owner/repositories.js
app/routes/owner/repositories.js
import Ember from 'ember'; import TravisRoute from 'travis/routes/basic'; import config from 'travis/config/environment'; export default TravisRoute.extend({ needsAuth: false, titleToken(model) { var name = model.name || model.login; return name; }, model(params, transition) { var options; options = {}; if (this.get('auth.signedIn')) { options.headers = { Authorization: 'token ' + (this.auth.token()) }; } let includes = `?include=owner.repositories,repository.default_branch, build.commit,repository.current_build`; let { owner } = transition.params.owner; let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`; return Ember.$.get(url, options); } });
JavaScript
0
@@ -459,16 +459,48 @@ %0A %7D%0A%0A + // eslint-disable-next-line%0A let @@ -565,23 +565,16 @@ _branch, -%0A build.co
a28922f5fe103d30fd79d663fe729555374c4157
make filter by urgency work too
app/scripts/controllers/inbox.js
app/scripts/controllers/inbox.js
angular.module('zentodone').controller('InboxCtrl', function ($scope, $rootScope, $filter, $location, tasks, Task, lists) { var debug = new window.$debug('mushin:task'); var search = $location.search(); debug('controllers/inbox.js: search params ' + JSON.stringify(search)); $scope.saveListActive = false; $scope.inbox = []; /* this adds proxy functions to Task class functions */ tasks.extend($scope); // http://cubiq.org/add-to-home-screen addToHomescreen({ maxDisplayCount: 3 }) function fetchTasks() { tasks.getAll(Task.INBOX) .then(function(tasks) { // at this time, the rootScope contexts/projects are set and thus // available through $scope too $scope.inbox = $filter('filter')(tasks, function(task) { // FIXME: I'm filtering on complete/end in a filter func if (!task.done && !task.deleted) return true }) // parse query params now if (search.query) { var parser = new window.Parser(); var parsed = parser.parse(search.query); debug('controllers/inbox: parsed query ' + JSON.stringify(parsed)); angular.forEach(parsed.contexts, function (context) { $scope.contexts[context].active = true; }); angular.forEach(parsed.projects, function (project) { $scope.projects[project].active = true; }); } }) } fetchTasks() $scope.$on('taskChange', function() { debug('taskChange'); fetchTasks() }) $scope.newTask = function() { var title = ($scope.taskTitle || '').trim() var parser = new window.Parser(); var parsed = parser.parse(title); title = parsed.title; debug('parsed new thing ' + JSON.stringify(parsed, null, 4)); if (!title) return // see app/scripts/services/tasks.js tasks.add(title, '', parsed) $scope.taskTitle = '' $scope.taskInput.$setPristine() } // filter tasks by context/project // FIXME: this now loops over all contexts/projects for each thing; // would be faster to precalculate the selection once into an array on // each click event in a taglist, then compare here $scope.filterByTag = function(thing) { var keep; var selectedAll; // either taglist may reject a thing // don't convert to angular.forEach as that does not allow breaks var types = [ 'context', 'project' ]; var type; var tags; for (var i = 0; i < types.length; ++i) { type = types[i]; tags = $scope[type + 's']; // debug('filter: looking at type ' + type); keep = false; selectedAll = true; // guilty until proven innocent for (var name in tags) { var tag = tags[name]; // debug('filter: looking at tag ' + tag.name); if (tag.active) { // debug('filter: tag.name active ' + tag.name); selectedAll = false; // debug('thing tags: ' + JSON.stringify(thing)); if (thing[type + 's'] && thing[type + 's'].indexOf(tag.name) > -1) { debug('filter: keeping ' + thing.title); keep = true; } } } /* also keep if no tag is selected, which means all are */ if (selectedAll) keep = true; if (!keep) { return false; } return true; } } // filter tasks by importance/urgency $scope.filterByNumber = function(thing) { var keep; var selectedAll; // either numberlist may reject a thing // don't convert to angular.forEach as that does not allow breaks var types = [ 'importance', 'urgency' ]; var type; var tags; for (var i = 0; i < types.length; ++i) { type = types[i]; tags = $scope[type]; // debug('filter: looking at type ' + type); keep = false; selectedAll = true; // guilty until proven innocent for (var number in tags) { var tag = tags[number]; // debug('filter: looking at tag ' + tag.name); if (tag.active) { // debug('filter: tag.name active ' + tag.name); selectedAll = false; // debug('thing tags: ' + JSON.stringify(thing)); if (thing[type] && thing[type] == number) { debug('filter: keeping ' + thing.title); keep = true; } } } /* also keep if no tag is selected, which means all are */ if (selectedAll) keep = true; if (!keep) { return false; } return true; } } $scope.notRecentlyCompleted = function(thing) { if (thing.complete != 100) { // debug(thing.title + ' not complete, keeping'); return true; } if (!thing.end) { // debug(thing.title + ' no complete date, dropping'); return false; } var now = new Date(); var then = new Date(thing.end); var diff = Math.abs(now - then); if (diff >= 1000 * 60) { // debug(thing.title + ' done too long, dropping, ms ' + diff); return false; } // debug(thing.title + ' done just now, keeping, ms' + diff); return true; } // save the current state of the list of things as a saved list $scope.saveList = function(name) { debug('saveList ' + name); $scope.saveListActive = false; // construct query from state of filtering var parts = []; angular.forEach($scope.contexts, function (context) { if (context.active) { parts.push('@' + context.name); } }); angular.forEach($scope.projects, function (project) { if (project.active) { parts.push('p:' + project.name); } }); var query = parts.join(' '); debug('saveList: query ' + query); lists.add(name, query); } })
JavaScript
0
@@ -4608,32 +4608,42 @@ return false;%0A + %7D%0A %7D%0A%0A r @@ -4655,30 +4655,24 @@ true;%0A %7D -%0A %7D %0A%0A $scope
37b88ee2a4a582434e1203d32c7082e417af9649
Fix app.configure
heat_tracer.js
heat_tracer.js
var http = require('http'); var libdtrace = require('libdtrace'); var io = require('socket.io'); var express = require('express'); /* create our express server and prepare to serve javascript files in ./public */ var app = express.createServer(); app.configure(function(){ app.use(express.staticProvider(__dirname + '/public')); }); /* Before we go any further we must realize that each time a user connects we're going to want to them send them dtrace aggregation every second. We can do so using 'setInterval', but we must keep track of both the intervals we set and the dtrace consumers that are created as we'll need them later when the client disconnects. */ var interval_id_by_session_id = {}; var dtp_by_session_id = {}; /* In order to effecienctly send packets we're going to use the Socket.IO library which seemlessly integrates with express. */ var websocket_server = io.listen(app); /* Now that we have a web socket server, we need to create a handler for connection events. These events represet a client connecting to our server */ websocket_server.on('connection', function(socket) { /* Like the web server object, we must also define handlers for various socket events that will happen during the lifetime of the connection. These will define how we interact with the client. The first is a message event which occurs when the client sends something to the server. */ socket.on( 'message', function(message) { /* The only message the client ever sends will be sent right after connecting. So it will happen only once during the lifetime of a socket. This message also contains a d script which defines an agregation to walk. */ var dtp = new libdtrace.Consumer(); var dscript = message['dscript']; console.log( dscript ); dtp.strcompile(dscript); dtp.go(); dtp_by_session_id[socket.sessionId] = dtp; /* All that's left to do is send the aggration data from the dscript. */ interval_id_by_session_id[socket.sessionId] = setInterval(function () { var aggdata = {}; try { dtp.aggwalk(function (id, key, val) { for( index in val ) { /* console.log( 'key: ' + key + ', interval: ' + val[index][0][0] + '-' + val[index][0][1], ', count ' + val[index][1] ); */ aggdata[key] = val; } } ); socket.send( aggdata ); } catch( err ) { console.log(err); } }, 1001 ); } ); /* Not so fast. If a client disconnects we don't want their respective dtrace consumer to keep collecting data any more. We also don't want to try to keep sending anything to them period. So clean up. */ socket.on('disconnect', function(){ clearInterval(clearInterval(interval_id_by_session_id[socket.sessionId])); var dtp = dtp_by_session_id[socket.sessionId]; delete dtp_by_session_id[socket.sessionId]; dtp.stop(); console.log('disconnected'); }); } ); app.listen(80);
JavaScript
0.000197
@@ -295,16 +295,8 @@ atic -Provider (__d
1bb76ea4133b7d374833f517957e0b4257c3d0e4
Set height for player.
app/sidebar/components/Player.js
app/sidebar/components/Player.js
import React, { Component } from 'react'; import Controls from './Controls.js'; export default class Player extends Component { constructor(props) { super(props); }; render() { return ( <div> <Controls /> </div> ) } };
JavaScript
0
@@ -178,24 +178,72 @@ render() %7B%0A + var style = %7B%0A 'height' : '50%25'%0A %7D%0A%0A return ( @@ -253,16 +253,30 @@ %3Cdiv + style=%7Bstyle%7D %3E%0A
f6992a1d5cdf7632bf5f5d62ab1aaf265bd9f2fe
Create flash message on failed login
app/sign-in/sign-in.directive.js
app/sign-in/sign-in.directive.js
{ angular .module('meganote.signIn') .directive('signIn', [ '$state', 'UsersService', ($state, UsersService) => { class SignInController { submit() { UsersService.login(this.user) .then( (data) => { $state.go('notes.form', {noteId: undefined}); }, (error) => { console.log(error); } ); } } return { scope: {}, controller: SignInController, controllerAs: 'vm', bindToController: true, template: `<div class="container"> <div class="row"> <div class="col-xs-6 col-xs-offset-4"> <h3>Welcome Back!</h3> <form id="new_user" ng-submit="vm.submit()"> <p> <label for="username">Username</label><br> <input type="text" name="username" ng-model="vm.user.username" required> </p> <p> <label for="password">Password</label><br> <input type="password" name="password" ng-model="vm.user.password" required> </p> <input type="submit" name="commit" value="Log in" class="btn btn-default"> <span class="login"> Don't have an account? <a ui-sref="sign-up">Sign up.</a> </span> </form> </div> </div> </div> ` }; } ]); }
JavaScript
0
@@ -80,16 +80,31 @@ state',%0A + 'Flash',%0A 'U @@ -132,16 +132,23 @@ ($state, + Flash, UsersSe @@ -280,39 +280,18 @@ hen( -%0A ( data -) =%3E %7B%0A - @@ -348,18 +348,16 @@ ined%7D);%0A - @@ -363,17 +363,17 @@ %7D -, +) %0A @@ -383,17 +383,18 @@ - +.catch (err -or) =%3E @@ -415,22 +415,40 @@ - console.log( +Flash.create('danger', err.data. erro @@ -469,26 +469,9 @@ - %7D%0A +%7D );%0A @@ -1803,16 +1803,215 @@ %3C/form%3E%0A + %3Cdiv id=%22flash%22%3E%0A %3Cflash-message%0A duration=%225000%22%0A show-close=%22true%22%3E%0A %3C/flash-message%3E%0A %3C/div%3E%0A
dea6ff9273819596af0f55459590befb16d0ad5b
add projects page to router
troposphere/static/js/AppRoutes.react.js
troposphere/static/js/AppRoutes.react.js
define(function (require) { "use strict"; var React = require('react'), Router = require('react-router'), Route = Router.Route, Redirect = Router.Redirect, DefaultRoute = Router.DefaultRoute; var Master = require('./components/Master.react'), MasterTest = require('./components/MasterTest.react'); //<Route name="dashboard" handler={Master}/> //<Route name="projects" handler={Master}/> //<Route name="project" path="projects/:projectId" handler={Master}> // <Route name="project-details" path="details" handler={Master}/> // <Route name="project-resources" path="resources" handler={Master}/> // <Route name="project-instance" path="instances/:instanceId" handler={Master}/> // <Route name="project-volume" path="volumes/:volumeId" handler={Master}/> // <DefaultRoute handler={MasterTest}/> //</Route> //<Route name="images" handler={Master}/> //<Route name="image" path="images/:imageId" handler={Master}/> var AppRoutes = ( <Route name="root" path="/application" handler={Master}> <Route name="dashboard" handler={MasterTest}/> <Route name="projects" handler={MasterTest}/> <Route name="images" handler={MasterTest}/> <Route name="providers" handler={MasterTest}/> <Route name="help" handler={MasterTest}/> <DefaultRoute handler={MasterTest}/> </Route> ); return AppRoutes; });
JavaScript
0
@@ -327,16 +327,96 @@ .react') +,%0A ProjectListPage = require('./components/projects/ProjectListPage.react') ;%0A%0A //%3C @@ -1217,34 +1217,39 @@ s%22 handler=%7B -MasterTest +ProjectListPage %7D/%3E%0A %3CR
9f26e7e0aafb6137cc8b621e2daecce41b769d9f
improve network sync percentage algorithmn
app/stores/NetworkStatusStore.js
app/stores/NetworkStatusStore.js
// @flow import { observable, action, computed} from 'mobx'; import Store from './lib/Store'; export default class NetworkStatusStore extends Store { @observable isConnected = false; @observable hasBeenConnected = false; @observable localDifficulty = 0; @observable networkDifficulty = 0; @observable isSyncedAfterLaunch = false; @observable isLoadingWallets = true; constructor(...args) { super(...args); this.registerReactions([ this._redirectToWalletAfterSync, this._computeSyncStatus, this._redirectToLoadingWhenDisconnected, ]); this._listenToServerStatusNotifications(); } @computed get isConnecting() { return !this.isConnected; } @computed get syncPercentage() { if (this.networkDifficulty > 0) { return (this.localDifficulty / this.networkDifficulty * 100); } return 0; } @computed get isSyncing() { return !this.isConnecting && this.networkDifficulty > 0 && !this.isSynced; } @computed get isSynced() { return !this.isConnecting && this.syncPercentage >= 100; } @action _listenToServerStatusNotifications() { this.api.notify((message) => { if (message === "ConnectionClosed") { return this.isConnected = false; } switch (message.tag) { case "ConnectionOpened": this.isConnected = true; break; case "NetworkDifficultyChanged": this.networkDifficulty = message.contents.getChainDifficulty; this.isConnected = true; this.hasBeenConnected = true; break; case "LocalDifficultyChanged": this.localDifficulty = message.contents.getChainDifficulty; break; case "ConnectionClosedReconnecting": this.isConnected = false; break; default: console.log("Unknown server notification received:", message); } }); }; _computeSyncStatus = () => { if (this.syncPercentage === 100) this.isSyncedAfterLaunch = true; }; _redirectToWalletAfterSync = () => { const { app, wallets } = this.stores; if (this.isConnected && this.isSyncedAfterLaunch && wallets.hasLoadedWallets && app.currentRoute === '/') { this.isLoadingWallets = false; if (wallets.first) { this.actions.goToRoute({ route: wallets.getWalletRoute(wallets.first.id) }); } else { this.actions.goToRoute({ route: '/no-wallets'}); } } }; _redirectToLoadingWhenDisconnected = () => { if (!this.isConnected) { this.actions.goToRoute({ route: '/' }); } }; }
JavaScript
0.000001
@@ -375,16 +375,55 @@ true;%0A%0A + _localDifficultyStartedWith = null;%0A%0A constr @@ -435,24 +435,24 @@ (...args) %7B%0A - super(.. @@ -806,31 +806,113 @@ %3E 0 -) %7B%0A return ( + && this._localDifficultyStartedWith != null) %7B%0A const relativeLocal = this.localDifficulty - this. +_ loca @@ -926,40 +926,160 @@ ulty - / this.networkDifficulty +StartedWith;%0A const relativeNetwork = this.networkDifficulty - this._localDifficultyStartedWith;%0A return relativeLocal / relativeNetwork * 100 -) ;%0A @@ -1845,27 +1845,23 @@ -this.localD +const d ifficult @@ -1893,32 +1893,206 @@ hainDifficulty;%0A + if (this._localDifficultyStartedWith == null) %7B%0A this._localDifficultyStartedWith = difficulty;%0A %7D%0A this.localDifficulty = difficulty;%0A break;
563e5e3d572b6b4dd40bc2c70ae97ce80418a87a
add details to redirects file (#15020)
website/redirects.js
website/redirects.js
module.exports = [ // Rename and re-arrange Autoscaling Internals section { source: '/nomad/tools/autoscaling/internals/:path*', destination: '/nomad/tools/autoscaling/concepts/:path*', permanent: true, }, { source: '/nomad/tools/autoscaling/concepts/checks', destination: '/nomad/tools/autoscaling/concepts/policy-eval/checks', permanent: true, }, { source: '/nomad/tools/autoscaling/concepts/node-selector-strategy', destination: '/nomad/tools/autoscaling/concepts/policy-eval/node-selector-strategy', permanent: true, }, ]
JavaScript
0
@@ -1,22 +1,913 @@ -module.exports = %5B +/**%0A * Define your custom redirects within this file.%0A *%0A * Vercel's redirect documentation:%0A * https://nextjs.org/docs/api-reference/next.config.js/redirects%0A *%0A * Relative paths with fragments (#) are not supported.%0A * For destinations with fragments, use an absolute URL.%0A *%0A * Playground for testing url pattern matching: https://npm.runkit.com/path-to-regexp%0A *%0A * Note that redirects defined in a product's redirects file are applied to%0A * the developer.hashicorp.com domain, which is where the documentation content%0A * is rendered. Redirect sources should be prefixed with the product slug%0A * to ensure they are scoped to the product's section. Any redirects that are%0A * not prefixed with a product slug will be ignored.%0A */%0Amodule.exports = %5B%0A /*%0A Example redirect:%0A %7B%0A source: '/nomad/docs/internal-docs/my-page',%0A destination: '/nomad/docs/internals/my-page',%0A permanent: true,%0A %7D,%0A */ %0A /
7252227ac66b79c3e394b7cf262ae1fae9cf652b
Remove externs in externs/closure-compiler.js
externs/closure-compiler.js
externs/closure-compiler.js
/** * @fileoverview Definitions for externs that are either missing or incorrect * in the current release version of the closure compiler we use. * * The entries must be removed once they are available/correct in the * version we use. * * @externs */ /** @type {number} */ Touch.prototype.force; /** @type {number} */ Touch.prototype.radiusX; /** @type {number} */ Touch.prototype.radiusY; /** @type {number} */ Touch.prototype.webkitForce; /** @type {number} */ Touch.prototype.webkitRadiusX; /** @type {number} */ Touch.prototype.webkitRadiusY; // see https://github.com/google/closure-compiler/pull/1139 /** * @type {string} * @see http://www.w3.org/TR/pointerevents/#the-touch-action-css-property */ CSSProperties.prototype.touchAction;
JavaScript
0.000002
@@ -256,511 +256,4 @@ */%0A -%0A/** @type %7Bnumber%7D */%0ATouch.prototype.force;%0A%0A%0A/** @type %7Bnumber%7D */%0ATouch.prototype.radiusX;%0A%0A%0A/** @type %7Bnumber%7D */%0ATouch.prototype.radiusY;%0A%0A%0A/** @type %7Bnumber%7D */%0ATouch.prototype.webkitForce;%0A%0A%0A/** @type %7Bnumber%7D */%0ATouch.prototype.webkitRadiusX;%0A%0A%0A/** @type %7Bnumber%7D */%0ATouch.prototype.webkitRadiusY;%0A%0A%0A// see https://github.com/google/closure-compiler/pull/1139%0A%0A/**%0A * @type %7Bstring%7D%0A * @see http://www.w3.org/TR/pointerevents/#the-touch-action-css-property%0A */%0ACSSProperties.prototype.touchAction;%0A
61ee4e97610105b08ab640a2197059d31eed3a2b
make trace uid an `anim:true` attr + improve description
src/plots/attributes.js
src/plots/attributes.js
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var fxAttrs = require('../components/fx/attributes'); module.exports = { type: { valType: 'enumerated', role: 'info', values: [], // listed dynamically dflt: 'scatter', editType: 'calc+clearAxisTypes', _noTemplating: true // we handle this at a higher level }, visible: { valType: 'enumerated', values: [true, false, 'legendonly'], role: 'info', dflt: true, editType: 'calc', description: [ 'Determines whether or not this trace is visible.', 'If *legendonly*, the trace is not drawn,', 'but can appear as a legend item', '(provided that the legend itself is visible).' ].join(' ') }, showlegend: { valType: 'boolean', role: 'info', dflt: true, editType: 'style', description: [ 'Determines whether or not an item corresponding to this', 'trace is shown in the legend.' ].join(' ') }, legendgroup: { valType: 'string', role: 'info', dflt: '', editType: 'style', description: [ 'Sets the legend group for this trace.', 'Traces part of the same legend group hide/show at the same time', 'when toggling legend items.' ].join(' ') }, opacity: { valType: 'number', role: 'style', min: 0, max: 1, dflt: 1, editType: 'style', description: 'Sets the opacity of the trace.' }, name: { valType: 'string', role: 'info', editType: 'style', description: [ 'Sets the trace name.', 'The trace name appear as the legend item and on hover.' ].join(' ') }, uid: { valType: 'string', role: 'info', editType: 'plot' }, ids: { valType: 'data_array', editType: 'calc', anim: true, description: [ 'Assigns id labels to each datum.', 'These ids for object constancy of data points during animation.', 'Should be an array of strings, not numbers or any other type.' ].join(' ') }, customdata: { valType: 'data_array', editType: 'calc', description: [ 'Assigns extra data each datum.', 'This may be useful when listening to hover, click and selection events.', 'Note that, *scatter* traces also appends customdata items in the markers', 'DOM elements' ].join(' ') }, // N.B. these cannot be 'data_array' as they do not have the same length as // other data arrays and arrayOk attributes in general // // Maybe add another valType: // https://github.com/plotly/plotly.js/issues/1894 selectedpoints: { valType: 'any', role: 'info', editType: 'calc', description: [ 'Array containing integer indices of selected points.', 'Has an effect only for traces that support selections.', 'Note that an empty array means an empty selection where the `unselected`', 'are turned on for all points, whereas, any other non-array values means no', 'selection all where the `selected` and `unselected` styles have no effect.' ].join(' ') }, hoverinfo: { valType: 'flaglist', role: 'info', flags: ['x', 'y', 'z', 'text', 'name'], extras: ['all', 'none', 'skip'], arrayOk: true, dflt: 'all', editType: 'none', description: [ 'Determines which trace information appear on hover.', 'If `none` or `skip` are set, no information is displayed upon hovering.', 'But, if `none` is set, click and hover events are still fired.' ].join(' ') }, hoverlabel: fxAttrs.hoverlabel, stream: { token: { valType: 'string', noBlank: true, strict: true, role: 'info', editType: 'calc', description: [ 'The stream id number links a data trace on a plot with a stream.', 'See https://plot.ly/settings for more details.' ].join(' ') }, maxpoints: { valType: 'number', min: 0, max: 10000, dflt: 500, role: 'info', editType: 'calc', description: [ 'Sets the maximum number of points to keep on the plots from an', 'incoming stream.', 'If `maxpoints` is set to *50*, only the newest 50 points will', 'be displayed on the plot.' ].join(' ') }, editType: 'calc' }, transforms: { _isLinkedToArray: 'transform', editType: 'calc', description: [ 'An array of operations that manipulate the trace data,', 'for example filtering or sorting the data arrays.' ].join(' ') }, uirevision: { valType: 'any', role: 'info', editType: 'none', description: [ 'Controls persistence of some user-driven changes to the trace:', '`constraintrange` in `parcoords` traces, as well as some', '`editable: true` modifications such as `name` and `colorbar.title`.', 'Defaults to `layout.uirevision`.', 'Note that other user-driven trace attribute changes are controlled', 'by `layout` attributes:', '`trace.visible` is controlled by `layout.legend.uirevision`,', '`selectedpoints` is controlled by `layout.selectionrevision`,', 'and `colorbar.(x|y)` (accessible with `config: {editable: true}`)', 'is controlled by `layout.editrevision`.', 'Trace changes are tracked by `uid`, which only falls back on trace', 'index if no `uid` is provided. So if your app can add/remove traces', 'before the end of the `data` array, such that the same trace has a', 'different index, you can still preserve user-driven changes if you', 'give each trace a `uid` that stays with it as it moves.' ].join(' ') } };
JavaScript
0.000023
@@ -2105,16 +2105,239 @@ : 'plot' +,%0A anim: true,%0A description: %5B%0A 'Assign an id to this trace,',%0A 'Use this to provide object constancy between traces during animations',%0A 'and transitions.'%0A %5D.join(' ') %0A %7D,%0A
10062e50bada3d2343c2af334c832817b1b9e67a
fix soundset
src/plugins/soundset.js
src/plugins/soundset.js
/* * SoundSet.js * 2014/11/28 * @auther minimo * This Program is MIT license. * */ phina.extension = phina.extension || {}; //サウンド管理 phina.define("phina.extension.SoundSet", { _member: { elements: null, bgm: null, bgmIsPlay: false, volumeBGM: 0.5, volumeSE: 0.5, }, init: function() { this.$extend(this._member); this.elements = []; }, readAsset: function() { for (var key in phina.asset.AssetManager.assets.sound) { var obj = phina.asset.AssetManager.get("sound", key); if (obj instanceof phina.asset.Sound) this.add(key); } }, add: function(name, url) { if (name === undefined) return null; url = url || null; if (this.find(name)) return true; var e = phina.extension.SoundElement(name); if (!e.media) return false; this.elements.push(e); return true; }, find: function(name) { if (!this.elements) return null; for (var i = 0; i < this.elements.length; i++) { if (this.elements[i].name == name) return this.elements[i]; } return null; }, playBGM: function(name) { if (this.bgm) { this.bgm.stop(); this.bgmIsPlay = false; } var media = this.find(name); if (media) { media.play(true); media.setVolume(this.volumeBGM); this.bgm = media; this.bgmIsPlay = true; } else { if (this.add(name)) this.playBGM(name); } return this; }, stopBGM: function() { if (this.bgm) { if (this.bgmIsPlay) { this.bgm.stop(); this.bgmIsPlay = false; } this.bgm = null; } return this; }, pauseBGM: function() { if (this.bgm) { if (this.bgmIsPlay) { this.bgm.pause(); this.bgmIsPlay = false; } } return this; }, resumeBGM: function() { if (this.bgm) { if (!this.bgmIsPlay) { this.bgm.volume = this.volumeBGM; this.bgm.resume(); this.bgmIsPlay = true; } } return this; }, setVolumeBGM: function(vol) { this.volumeBGM = vol; if (this.bgm) { this.bgm.pause(); this.bgm.setVolume(this.volumeBGM * media.volume); this.bgm.resume(); } return this; }, playSE: function(name) { var media = this.find(name); if (media) { var vol = this.volumeSE * media.volume; media.setVolume(vol); media.playClone(); } else { if (this.add(name)) this.playSE(name); } return this; }, setVolumeSE: function(vol) { this.volumeSE = vol; return this; }, }); //SoundElement Basic phina.define("phina.extension.SoundElement", { _member: { name: null, url: null, media: null, masterVolume: 1, volume: 1, status: null, message: null, }, init: function(name) { this.$extend(this._member); this.name = name; this.media = phina.asset.AssetManager.get("sound", name); if (this.media) { this.media.volume = 1; } else { console.warn("asset not found. "+name); } }, play: function(loop) { if (!this.media) return this; this.media.loop = loop; this.media.play(); return this; }, playClone: function() { if (!this.media) return this; this.media.loop = false; this.media.clone().play(); return this; }, resume: function() { if (!this.media) return this; this.media.resume(); return this; }, pause: function () { if (!this.media) return this; this.media.pause(); }, stop: function() { if (!this.media) return this; this.media.stop(); return this; }, setMasterVolume: function(vol) { }, setVolume: function(vol) { if (!this.media) return this; if (vol === undefined) vol = 0; this.volume = vol; this.media.volume = this.volume; return this; }, });
JavaScript
0.000018
@@ -3814,16 +3814,8 @@ dia. -clone(). play
880b08cb402e0cdac54abc48089cf168285ca611
We need an entity name
blueprints/ember-cli-latex-maths/index.js
blueprints/ember-cli-latex-maths/index.js
module.exports = { //description: '', // locals: function(options) { // // Return custom template variables here. // return { // foo: options.entity.options.foo // }; // } // afterInstall: function(options) { // // Perform extra work here. // } afterInstall: function() { return this.addBowerPackageToProject('katex'); // is a promise } };
JavaScript
0.999999
@@ -32,16 +32,100 @@ ion: '', +%0A normalizeEntityName: function() %7B%7D, // no-op since we're just adding dependencies %0A%0A // l
3690b733a4fd306633422bdcdb3638a3327492c4
use { ammount cents } for convention
schema/sale/index.js
schema/sale/index.js
import { map } from 'lodash'; import { exclude } from '../../lib/helpers'; import moment from 'moment'; import gravity from '../../lib/loaders/gravity'; import cached from '../fields/cached'; import date from '../fields/date'; import Artwork from '../artwork'; import SaleArtwork from '../sale_artwork'; import Profile from '../profile'; import Image from '../image/index'; import { GraphQLString, GraphQLObjectType, GraphQLNonNull, GraphQLList, GraphQLBoolean, GraphQLInt, GraphQLFloat, } from 'graphql'; export function auctionState({ start_at, end_at, live_start_at }) { const start = moment(start_at); const end = moment(end_at); const liveStart = moment(live_start_at); if (moment().isAfter(end) || moment().isSame(end)) { return 'closed'; } else if (moment().isBetween(liveStart, end)) { return 'live'; } else if (moment().isBetween(start, end)) { return 'open'; } else if (moment().isBefore(start) || moment().isSame(start)) { return 'preview'; } } const SaleType = new GraphQLObjectType({ name: 'Sale', fields: () => { return { cached, id: { type: GraphQLString, }, _id: { type: GraphQLString, }, name: { type: GraphQLString, }, href: { type: GraphQLString, resolve: ({ id }) => `/auction/${id}`, }, description: { type: GraphQLString, }, sale_type: { type: GraphQLString, }, is_auction: { type: GraphQLBoolean, }, is_auction_promo: { type: GraphQLBoolean, resolve: ({ sale_type }) => sale_type === 'auction promo', }, is_preview: { type: GraphQLBoolean, resolve: (sale) => auctionState(sale) === 'preview', }, is_open: { type: GraphQLBoolean, resolve: (sale) => auctionState(sale) === 'open' || auctionState(sale) === 'live', }, is_live_open: { type: GraphQLBoolean, resolve: (sale) => auctionState(sale) === 'live', }, is_closed: { type: GraphQLBoolean, resolve: (sale) => auctionState(sale) === 'closed', }, is_with_buyers_premium: { type: GraphQLBoolean, resolve: ({ buyers_premium }) => buyers_premium, }, auction_state: { type: GraphQLString, resolve: auctionState, deprecationReason: 'Favor `status` for consistency with other models', }, status: { type: GraphQLString, resolve: auctionState, }, registration_ends_at: date, start_at: date, end_at: date, live_start_at: date, currency: { type: GraphQLString, }, sale_artworks: { type: new GraphQLList(SaleArtwork.type), args: { page: { type: GraphQLInt, defaultValue: 1, }, size: { type: GraphQLInt, defaultValue: 25, }, all: { type: GraphQLBoolean, defaultValue: false, }, }, resolve: ({ id }, options) => { if (options.all) { return gravity.all(`sale/${id}/sale_artworks`, options); } return gravity(`sale/${id}/sale_artworks`, options); }, }, artworks: { type: new GraphQLList(Artwork.type), args: { page: { type: GraphQLInt, defaultValue: 1, }, size: { type: GraphQLInt, defaultValue: 25, }, all: { type: GraphQLBoolean, defaultValue: false, }, exclude: { type: new GraphQLList(GraphQLString), description: 'List of artwork IDs to exclude from the response (irrespective of size)', }, }, resolve: ({ id }, options) => { const invert = saleArtworks => map(saleArtworks, 'artwork'); if (options.all) { return gravity.all(`sale/${id}/sale_artworks`, options) .then(invert) .then(exclude(options.exclude, 'id')); } return gravity(`sale/${id}/sale_artworks`, options) .then(invert) .then(exclude(options.exclude, 'id')); }, }, cover_image: { type: Image.type, resolve: ({ image_versions, image_url }) => Image.resolve({ image_versions, image_url }), }, sale_artwork: { type: SaleArtwork.type, args: { id: { type: new GraphQLNonNull(GraphQLString), }, }, resolve: (sale, { id }) => gravity(`sale/${sale.id}/sale_artwork/${id}`), }, profile: { type: Profile.type, resolve: ({ profile }) => profile, }, bid_increments: { type: new GraphQLList(new GraphQLObjectType({ name: 'BidIncrements', fields: { from: { type: GraphQLInt, }, to: { type: GraphQLInt, }, amount: { type: GraphQLInt, }, }, })), description: 'A bid increment policy that explains minimum bids in ranges.', resolve: (sale) => gravity(`increments`, { key: sale.increment_strategy }) .then((incs) => incs[0].increments), }, buyers_premium: { type: new GraphQLList(new GraphQLObjectType({ name: 'BuyersPremium', fields: { min_amount_cents: { type: GraphQLInt, }, percent: { type: GraphQLFloat, }, }, })), description: "Auction's buyer's premium policy.", resolve: (sale) => sale.buyers_premium.schedule, }, }; }, }); const Sale = { type: SaleType, description: 'A Sale', args: { id: { type: new GraphQLNonNull(GraphQLString), description: 'The slug or ID of the Sale', }, }, resolve: (root, { id }) => gravity(`sale/${id}`), }; export default Sale;
JavaScript
0.000032
@@ -367,16 +367,58 @@ index';%0A +import %7B amount %7D from '../fields/money';%0A import %7B @@ -5678,58 +5678,186 @@ -min_amount_cents: %7B%0A type: GraphQLInt +amount: amount((%7B min_amount_cents %7D) =%3E min_amount_cents),%0A cents: %7B%0A type: GraphQLInt,%0A resolve: (%7B min_amount_cents %7D) =%3E min_amount_cents ,%0A
8283ad382b47acf8d59d4c3b1d51c10062432ea5
Fix spacing issue on shuttle card
app/views/shuttle/ShuttleCard.js
app/views/shuttle/ShuttleCard.js
import React from 'react'; import { View, ActivityIndicator, StyleSheet, Text, TouchableHighlight } from 'react-native'; import { Actions } from 'react-native-router-flux'; import ShuttleOverview from './ShuttleOverview'; import ScrollCard from '../card/ScrollCard'; import ShuttleOverviewList from './ShuttleOverviewList'; import LocationRequiredContent from '../common/LocationRequiredContent'; import { doPRM, getMaxCardWidth, getCampusPrimary } from '../../util/general'; const ShuttleCard = ({ stopsData, savedStops, permission, gotoRoutesList, gotoSavedList, removeStop, closestStop }) => { let content; // no permission to get location if (permission !== 'authorized') { content = (<LocationRequiredContent />); } /*else if (stopID === -1 && (!stopData || !stopData[stopID] || !stopData[stopID].arrivals || stopData[stopID].arrivals.length === 0)) { content = ( <View style={[styles.shuttle_card_row_center, styles.shuttle_card_loader]}> <ActivityIndicator size="large" /> </View> ); } else if (stopID !== -1 && (!stopData || !stopData[stopID] || !stopData[stopID].arrivals || stopData[stopID].arrivals.length === 0)) { content = ( <View style={[styles.shuttle_card_row_center, styles.shuttle_card_loader]}> <Text style={styles.fs18}>No Shuttles en Route</Text> <Text style={[styles.pt10, styles.fs12, styles.dgrey]}>We were unable to locate any nearby shuttles, please try again later.</Text> </View> ); }*/ else { content = ( <ShuttleOverviewList stopsData={stopsData} savedStops={savedStops} /> ); } const extraActions = [ { name: 'Remove stop', action: removeStop }, { name: 'Manage stops', action: gotoSavedList }, ]; return ( <ScrollCard id="shuttle" title="Shuttle" scrollData={savedStops} renderRow={ (row) => <ShuttleOverview onPress={() => Actions.ShuttleStop({ stopID: row.id })} stopData={stopsData[row.id]} closest={row.id === closestStop.id} /> } actionButton={ <TouchableHighlight style={styles.add_container} underlayColor={'rgba(200,200,200,.1)'} onPress={() => gotoRoutesList()} > <Text style={styles.add_label}>Add a Stop</Text> </TouchableHighlight> } extraActions={extraActions} /> ); }; export default ShuttleCard; // There's gotta be a better way to do this...find a way to get rid of magic numbers const nextArrivals = ((2 * doPRM(36)) + 32) + doPRM(20); // Two rows + text const cardHeader = 26; // font + padding const cardBody = doPRM(83) + (2 * doPRM(20)) + doPRM(26) + 20; // top + margin + font + padding const styles = StyleSheet.create({ add_container: { width: getMaxCardWidth(), backgroundColor: '#F9F9F9', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4, paddingTop: 8, paddingBottom: 4, borderTopWidth: 1, borderBottomWidth: 1, borderColor: '#DDD' }, add_label: { fontSize: 20, color: getCampusPrimary(), fontWeight: '300' }, shuttle_card_row_center: { alignItems: 'center', justifyContent: 'center', width: getMaxCardWidth() }, shuttle_card_loader: { height: nextArrivals + cardHeader + cardBody }, shuttlecard_loading_fail: { marginHorizontal: doPRM(16), marginTop: doPRM(40), marginBottom: doPRM(60) }, fs18: { fontSize: doPRM(18) }, pt10: { paddingTop: 10 }, fs12: { fontSize: doPRM(12) }, dgrey: { color: '#333' }, });
JavaScript
0
@@ -2813,32 +2813,19 @@ ding -Top: 8, paddingBottom: 4 +Vertical: 8 , bo
878d5444eb19f68596b7125734b984e34bd49f40
Fix require paths
windows/test/main.js
windows/test/main.js
// Copyright © 2014 Intel Corporation. All rights reserved. // Use of this source code is governed by an Apache v2 // license that can be found in the LICENSE-APACHE-V2 file. var ShellJS = require("shelljs"); var Application = require("../src/Application"); var Util = require("../test-util/Util.js"); var _packageId = "com.example.foo"; exports.tests = { main: function(test) { test.expect(1); // Just call main without args, this should display help. // Need to strip extra command-line args though, so the // command parser is not confused. process.argv = process.argv.slice(0, 2); // As long as no exception hits us we're good. var app = require("../src/Main"); app.run(function (errno) { test.equal(errno, 0); test.done(); }); }, create: function(test) { test.expect(1); // Good test. var tmpdir = Util.createTmpDir(); ShellJS.pushd(tmpdir); var app = require("../src/Main"); Application.call(app, tmpdir, _packageId); app.create(_packageId, {platforms: "windows"}, function(errno) { test.equal(errno, 0); ShellJS.popd(); ShellJS.rm("-rf", tmpdir); test.done(); }); } };
JavaScript
0.000001
@@ -235,24 +235,27 @@ require(%22../ +../ src/Applicat @@ -284,16 +284,19 @@ ire(%22../ +../ test-uti @@ -718,32 +718,35 @@ p = require(%22../ +../ src/Main%22);%0A @@ -1044,16 +1044,19 @@ ire(%22../ +../ src/Main
87d85de49ad9b8b0fe1097c7cdbafb4ff3bd9ba4
Update repository name
VeevaThumb.js
VeevaThumb.js
/** * VeevaThumb * https://github.com/dzervoudakes/VeevaThumb * * Auto-exports thumbnails for "Veeva" eDetailing presentations * * Copyright (c) 2014, 2016 Dan Zervoudakes * Released under the MIT license * https://github.com/dzervoudakes/VeevaThumb/blob/master/LICENSE */ (function() { // Collect open documents and prepare to export as JPG... var newSize = undefined; var openDocs = app.documents; var exportJPG = new ExportOptionsSaveForWeb(); exportJPG.format = SaveDocumentType.JPEG; exportJPG.includeProfile = false; exportJPG.interlaced = true; exportJPG.optimized = false; exportJPG.quality = 100; // Ask users which size they wish to export... function askUser() { while (newSize !== '1' || newSize !== '2') { newSize = prompt('Export: 1) 1024x768, or 2) 200x150?', ''); if (newSize === '1' || newSize === '2') return newSize; } }; // History rollback function... function revertHistory() { var latestHistory = app.activeDocument.historyStates.length; var revertTo = latestHistory - 2; app.activeDocument.activeHistoryState = app.activeDocument.historyStates[revertTo]; app.activeDocument.save(); }; // The export function... function exportThumbs() { // Obtain user input askUser(); // Cycle through the documents for (var i = 0; i < openDocs.length; i++) { app.activeDocument = openDocs[i]; if (newSize === '1') { app.activeDocument.resizeImage(UnitValue(1024, 'px'), UnitValue(768, 'px')); // Typical thumbnail size for "Home" screens } else if (newSize === '2') { app.activeDocument.resizeImage(UnitValue(200, 'px'), UnitValue(150, 'px')); // Default thumbnail size for Veeva presentations } var fullPath = app.activeDocument.path.fsName; var Name = app.activeDocument.name.replace(/\.[^\.]+$/, ''); var saveFile = File(fullPath + '/' + Name + '.jpg'); // Export the files and undo image resizing after successfully exporting app.activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, exportJPG); revertHistory(); } }; // Viva la Veeva! exportThumbs(); })();
JavaScript
0.000001
@@ -42,30 +42,30 @@ zervoudakes/ -V +v eeva -T +t humb%0A * %0A * @@ -242,22 +242,22 @@ oudakes/ -V +v eeva -T +t humb/blo
fa9f21dd65b6a278d04a68192b98593e68c63eb7
Call scroll handler on element mount, with an additional check in scroll handler for links without mounted elements yet
modules/mixins/Helpers.js
modules/mixins/Helpers.js
"use strict"; var React = require('react'); var ReactDOM = require('react-dom'); var animateScroll = require('./animate-scroll'); var scrollSpy = require('./scroll-spy'); var scroller = require('./scroller'); var __deferredScrollDestination = ''; var __deferredScrollOffset = 0; var Helpers = { Scroll: { propTypes: { to: React.PropTypes.string.isRequired, offset: React.PropTypes.number }, getDefaultProps: function() { return {offset: 0}; }, scrollTo : function(to) { scroller.scrollTo(to, this.props.smooth, this.props.duration, this.props.offset); }, onClick: function(event) { /* * give the posibility to override onClick */ if(this.props.onClick) { this.props.onClick(event); } /* * dont bubble the navigation */ if (event.stopPropagation) event.stopPropagation(); if (event.preventDefault) event.preventDefault(); /* * do the magic! */ this.scrollTo(this.props.to); }, componentDidMount: function() { scrollSpy.mount(); if(this.props.spy) { var to = this.props.to; var element = null; var elemTopBound = 0; var elemBottomBound = 0; scrollSpy.addStateHandler((function() { if(scroller.getActiveLink() != to) { this.setState({ active : false }); } }).bind(this)); scrollSpy.addSpyHandler((function(y) { if(!element) { element = scroller.get(to); } var cords = element.getBoundingClientRect(); elemTopBound = Math.floor(cords.top + y); elemBottomBound = elemTopBound + cords.height; var offsetY = y - this.props.offset; var isInside = (offsetY >= elemTopBound && offsetY <= elemBottomBound); var isOutside = (offsetY < elemTopBound || offsetY > elemBottomBound); var activeLnik = scroller.getActiveLink(); if (isOutside && activeLnik === to) { scroller.setActiveLink(void 0); this.setState({ active : false }); } else if (isInside && activeLnik != to) { scroller.setActiveLink(to); this.setState({ active : true }); if(this.props.onSetActive) this.props.onSetActive(to); scrollSpy.updateStates(); } }).bind(this)); } }, componentWillUnmount: function() { scrollSpy.unmount(); } }, Element: { propTypes: { name: React.PropTypes.string.isRequired }, componentDidMount: function() { scroller.register(this.props.name, ReactDOM.findDOMNode(this)); if (__deferredScrollDestination === this.props.name) { window.setTimeout(function(){ scroller.scrollTo(__deferredScrollDestination, false, 0, __deferredScrollOffset); __deferredScrollDestination = ''; __deferredScrollOffset = 0; }); } }, componentWillUnmount: function() { scroller.unregister(this.props.name); } }, DeferredScroll: { deferredScrollTo: function(desination, offset) { __deferredScrollDestination = desination; __deferredScrollOffset = offset || 0; } } }; module.exports = Helpers;
JavaScript
0
@@ -1497,16 +1497,17 @@ if(! + element) @@ -1560,24 +1560,84 @@ %7D%0A%0A + if (! element) %7B%0A return;%0A %7D%0A%0A va @@ -3048,32 +3048,65 @@ %7D);%0A %7D%0A + scrollSpy.scrollHandler();%0A %7D,%0A compo
11c8351adf4a0e52cc7a866681aaf3584f1e26d5
Add range visualization to RuleGraph
ui/src/kapacitor/components/RuleGraph.js
ui/src/kapacitor/components/RuleGraph.js
import React, {PropTypes} from 'react'; import selectStatement from 'src/chronograf/utils/influxql/select'; import AutoRefresh from 'shared/components/AutoRefresh'; import LineGraph from 'shared/components/LineGraph'; const RefreshingLineGraph = AutoRefresh(LineGraph); export const RuleGraph = React.createClass({ propTypes: { source: PropTypes.shape({ links: PropTypes.shape({ proxy: PropTypes.string.isRequired, }).isRequired, }).isRequired, query: PropTypes.shape({}).isRequired, rule: PropTypes.shape({}).isRequired, timeRange: PropTypes.shape({}).isRequired, }, render() { return ( <div className="rule-builder--graph"> {this.renderGraph()} </div> ); }, renderGraph() { const {query, source, timeRange} = this.props; const autoRefreshMs = 30000; const queryText = selectStatement({lower: timeRange.queryValue}, query); const queries = [{host: source.links.proxy, text: queryText}]; const kapacitorLineColors = ["#4ED8A0"]; if (!queryText) { return ( <div className="rule-preview--graph-empty"> <p>Select a <strong>Metric</strong> to preview on a graph</p> </div> ); } return ( <RefreshingLineGraph queries={queries} autoRefresh={autoRefreshMs} underlayCallback={this.createUnderlayCallback()} isGraphFilled={false} overrideLineColors={kapacitorLineColors} /> ); }, createUnderlayCallback() { const {rule} = this.props; return (canvas, area, dygraph) => { if (rule.trigger !== 'threshold' || rule.values.value === '') { return; } const theOnePercent = 0.01; let highlightStart = 0; let highlightEnd = 0; switch (rule.values.operator) { case 'equal to or greater': case 'greater than': { highlightStart = rule.values.value; highlightEnd = dygraph.yAxisRange()[1]; break; } case 'equal to or less than': case 'less than': { highlightStart = dygraph.yAxisRange()[0]; highlightEnd = rule.values.value; break; } case 'not equal to': case 'equal to': { const width = (theOnePercent) * (dygraph.yAxisRange()[1] - dygraph.yAxisRange()[0]); highlightStart = +rule.values.value - width; highlightEnd = +rule.values.value + width; break; } } const bottom = dygraph.toDomYCoord(highlightStart); const top = dygraph.toDomYCoord(highlightEnd); canvas.fillStyle = 'rgba(78,216,160,0.3)'; canvas.fillRect(area.x, top, area.w, bottom - top); }; }, }); export default RuleGraph;
JavaScript
0
@@ -2468,16 +2468,269 @@ %7D +%0A%0A case 'out of range':%0A case 'within range': %7B%0A const %7BrangeValue, value%7D = rule.values;%0A highlightStart = Math.min(+value, +rangeValue);%0A highlightEnd = Math.max(+value, +rangeValue);%0A break;%0A %7D %0A %7D
f232675cc98722e0d16698fa3b424c61a9b34bdd
create a favicon if it does not already exist
www/common/notify.js
www/common/notify.js
(function () { var Module = {}; var isSupported = Module.isSupported = function () { return typeof(window.Notification) === 'function'; }; var hasPermission = Module.hasPermission = function () { return Notification.permission === 'granted'; }; var getPermission = Module.getPermission = function (f) { Notification.requestPermission(function (permission) { if (permission === "granted") { f(true); } else { f(false); } }); }; var create = Module.create = function (msg, title) { return new Notification(title,{ // icon: icon, body: msg, }); }; Module.system = function (msg, title, icon) { // Let's check if the browser supports notifications if (!isSupported()) { console.log("Notifications are not supported"); } // Let's check whether notification permissions have already been granted else if (hasPermission()) { // If it's okay let's create a notification return create(msg, title, icon); } // Otherwise, we need to ask the user for permission else if (Notification.permission !== 'denied') { getPermission(function (state) { if (state) { create(msg, title, icon); } }); } }; Module.tab = function (frequency, count) { var key = '_pendingTabNotification'; var favicon = document.getElementById('favicon'); if (favicon) { var main = favicon.getAttribute('data-main-favicon'); var alt = favicon.getAttribute('data-alt-favicon'); favicon.setAttribute('href', main); } var cancel = function (pending) { // only run one tab notification at a time if (Module[key]) { window.clearInterval(Module[key]); if (favicon) { favicon.setAttribute('href', pending? alt : main); } return true; } return false; }; cancel(); var step = function () { if (favicon) { favicon.setAttribute('href', favicon.getAttribute('href') === main? alt : main); } --count; }; Module[key] = window.setInterval(function () { if (count > 0) { return step(); } cancel(true); }, frequency); step(); return { cancel: cancel, }; }; if (typeof(module) !== 'undefined' && module.exports) { module.exports = Module; } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { define(function () { return Module; }); } else { window.Visible = Module; } }());
JavaScript
0.000001
@@ -1343,32 +1343,728 @@ %7D%0A %7D;%0A%0A + var DEFAULT_MAIN = '/customize/main-favicon.png';%0A var DEFAULT_ALT = '/customize/alt-favicon.png';%0A%0A var createFavicon = function () %7B%0A console.log(%22creating favicon%22);%0A var fav = document.createElement('link');%0A var attrs = %7B%0A id: 'favicon',%0A type: 'image/png',%0A rel: 'icon',%0A 'data-main-favicon': DEFAULT_MAIN,%0A 'data-alt-favicon': DEFAULT_ALT,%0A href: DEFAULT_MAIN,%0A %7D;%0A Object.keys(attrs).forEach(function (k) %7B%0A fav.setAttribute(k, attrs%5Bk%5D);%0A %7D);%0A document.head.appendChild(fav);%0A %7D;%0A%0A if (!document.getElementById('favicon')) %7B createFavicon(); %7D%0A%0A Module.tab = @@ -2190,32 +2190,98 @@ yId('favicon');%0A +%0A var main = DEFAULT_MAIN;%0A var alt = DEFAULT_ALT;%0A%0A if (favi @@ -2295,28 +2295,24 @@ -var main = favic @@ -2339,32 +2339,48 @@ a-main-favicon') + %7C%7C DEFAULT_MAIN ;%0A va @@ -2373,28 +2373,24 @@ -var alt = favico @@ -2423,16 +2423,31 @@ avicon') + %7C%7C DEFAULT_ALT ;%0A
64a2940a0d80a200610b9e97da58cf08040a3734
fix webkit archiving (#4642)
browser_patches/webkit/concat_protocol.js
browser_patches/webkit/concat_protocol.js
const fs = require('fs'); const path = require('path'); const protocolDir = path.join(__dirname, './checkout/Source/JavaScriptCore/inspector/protocol'); const files = fs.readdirSync(protocolDir).filter(f => f.endsWith('.json')).map(f => path.join(protocolDir, f)); const json = files.map(file => JSON.parse(fs.readFileSync(file))); console.log(JSON.stringify(json));
JavaScript
0
@@ -59,54 +59,135 @@ nst -protocolDir = path.join(__dirname, './checkout +checkoutPath = process.env.WK_CHECKOUT_PATH %7C%7C path.join(__dirname, 'checkout');%0Aconst protocolDir = path.join(checkoutPath, '. /Sou
eb8881f4d7b54bce41f37f297ecc5e238934bded
set X-Interface header to identify requests from the HAL Browser
vendor/hal-browser/js/hal/http/client.js
vendor/hal-browser/js/hal/http/client.js
HAL.Http.Client = function(opts) { this.vent = opts.vent; $.ajaxSetup({ headers: { 'Accept': 'application/hal+json, application/json, */*; q=0.01' } }); }; HAL.Http.Client.prototype.get = function(url) { var self = this; this.vent.trigger('location-change', { url: url }); var jqxhr = $.ajax({ url: url, dataType: 'json', success: function(resource, textStatus, jqXHR) { self.vent.trigger('response', { resource: resource, jqxhr: jqXHR, headers: jqXHR.getAllResponseHeaders() }); } }).error(function() { self.vent.trigger('fail-response', { jqxhr: jqxhr }); }); }; HAL.Http.Client.prototype.request = function(opts) { var self = this; opts.dataType = 'json'; self.vent.trigger('location-change', { url: opts.url }); return jqxhr = $.ajax(opts); }; HAL.Http.Client.prototype.updateDefaultHeaders = function(headers) { this.defaultHeaders = headers; $.ajaxSetup({ headers: headers }); }; HAL.Http.Client.prototype.getDefaultHeaders = function() { return this.defaultHeaders; };
JavaScript
0
@@ -143,16 +143,46 @@ q=0.01' +, 'X-Interface': 'HAL Browser' %7D %7D);%0A%7D
4e9d54a9bf75adb79e5e5b8ef3869546a87a05ae
fix busview wrapping issues (#576)
views/transportation/bus/bus-stop-row.js
views/transportation/bus/bus-stop-row.js
// @flow import React from 'react' import {Platform, StyleSheet, Text} from 'react-native' import {Row, Column} from '../../components/layout' import {ListRow, Detail, Title} from '../../components/list' import type {FancyBusTimeListType} from './types' import type moment from 'moment' import * as c from '../../components/colors' import {ProgressChunk} from './components/progress-chunk' const TIME_FORMAT = 'h:mma' const styles = StyleSheet.create({ skippingStopTitle: { color: c.iosDisabledText, }, skippingStopDetail: { }, internalPadding: { paddingVertical: Platform.OS === 'ios' ? 8 : 15, }, atStopTitle: { fontWeight: Platform.OS === 'ios' ? '500' : '600', }, passedStopTitle: { color: c.iosDisabledText, }, }) export function BusStopRow({time, now, barColor, currentStopColor, place, times}: { time: moment, now: moment, barColor: string, currentStopColor: string, place: string, times: FancyBusTimeListType, }) { const afterStop = time && now.isAfter(time, 'minute') const atStop = time && now.isSame(time, 'minute') const beforeStop = !afterStop && !atStop && time !== false const skippingStop = time === false return ( <ListRow fullWidth={true} fullHeight={true} > <Row> <ProgressChunk {...{barColor, afterStop, beforeStop, atStop, skippingStop, currentStopColor}} /> <Column style={styles.internalPadding}> <Title bold={false} style={[ skippingStop && styles.skippingStopTitle, afterStop && styles.passedStopTitle, atStop && styles.atStopTitle, ]} > {place} </Title> <Detail> <ScheduleTimes {...{times, skippingStop}} /> </Detail> </Column> </Row> </ListRow> ) } const ScheduleTimes = ({times, skippingStop}: { skippingStop: boolean, times: FancyBusTimeListType, }) => { return ( <Text style={skippingStop && styles.skippingStopDetail} numberOfLines={1} > {times // and format the times .map(time => time === false ? 'None' : time.format(TIME_FORMAT)) .join(' • ')} </Text> ) }
JavaScript
0
@@ -1385,16 +1385,25 @@ %3CColumn + flex=%7B1%7D style=%7B @@ -1427,16 +1427,16 @@ dding%7D%3E%0A - @@ -1720,24 +1720,34 @@ %3CDetail + lines=%7B1%7D %3E%0A @@ -1998,22 +1998,16 @@ %3CText -%0A style=%7B @@ -2052,37 +2052,8 @@ ail%7D -%0A numberOfLines=%7B1%7D%0A %3E%0A
1ecc460686221a87e89806cc4614d968d71b18e3
Fix a backup and restore issue from the settings
www/settings/main.js
www/settings/main.js
// Load #1, load as little as possible because we are in a race to get the loading screen up. define([ '/bower_components/nthen/index.js', '/api/config', '/common/dom-ready.js', '/common/requireconfig.js', '/common/sframe-common-outer.js' ], function (nThen, ApiConfig, DomReady, RequireConfig, SFCommonO) { var requireConfig = RequireConfig(); // Loaded in load #2 nThen(function (waitFor) { DomReady.onReady(waitFor()); }).nThen(function (waitFor) { var req = { cfg: requireConfig, req: [ '/common/loading.js' ], pfx: window.location.origin }; window.rc = requireConfig; window.apiconf = ApiConfig; document.getElementById('sbox-iframe').setAttribute('src', ApiConfig.httpSafeOrigin + '/settings/inner.html?' + requireConfig.urlArgs + '#' + encodeURIComponent(JSON.stringify(req))); // This is a cheap trick to avoid loading sframe-channel in parallel with the // loading screen setup. var done = waitFor(); var onMsg = function (msg) { var data = JSON.parse(msg.data); if (data.q !== 'READY') { return; } window.removeEventListener('message', onMsg); var _done = done; done = function () { }; _done(); }; window.addEventListener('message', onMsg); }).nThen(function (/*waitFor*/) { var addRpc = function (sframeChan, Cryptpad, Utils) { sframeChan.on('Q_THUMBNAIL_CLEAR', function (d, cb) { Utils.LocalStore.clearThumbnail(function (err, data) { cb({err:err, data:data}); }); }); sframeChan.on('Q_SETTINGS_DRIVE_GET', function (d, cb) { if (d === "full") { // We want shared folders too } Cryptpad.getUserObject(function (obj) { if (obj.error) { return void cb(obj); } var result = { uo: obj, sf: {} }; if (!obj.drive || !obj.drive.sharedFolders) { return void cb(result); } Utils.nThen(function (waitFor) { Object.keys(obj.drive.sharedFolders).forEach(function (id) { Cryptpad.getSharedFolder(id, waitFor(function (obj) { result.sf[id] = obj; })); }); }).nThen(function () { cb(result); }); }); }); sframeChan.on('Q_SETTINGS_DRIVE_SET', function (data, cb) { var sjson = JSON.stringify(data); require([ '/common/cryptget.js', ], function (Crypt) { var k = Utils.LocalStore.getUserHash() || Utils.LocalStore.getFSHash(); Crypt.put(k, sjson, function (err) { cb(err); }); }); }); sframeChan.on('Q_SETTINGS_DRIVE_RESET', function (data, cb) { Cryptpad.resetDrive(cb); }); sframeChan.on('Q_SETTINGS_LOGOUT', function (data, cb) { Cryptpad.logoutFromAll(cb); }); sframeChan.on('Q_SETTINGS_IMPORT_LOCAL', function (data, cb) { Cryptpad.mergeAnonDrive(cb); }); sframeChan.on('Q_SETTINGS_DELETE_ACCOUNT', function (data, cb) { Cryptpad.deleteAccount(cb); }); }; var category; if (window.location.hash) { category = window.location.hash.slice(1); window.location.hash = ''; } var addData = function (obj) { if (category) { obj.category = category; } }; SFCommonO.start({ noRealtime: true, addRpc: addRpc, addData: addData }); }); });
JavaScript
0
@@ -1822,77 +1822,107 @@ -if (d === %22full%22) %7B%0A // We want shared folders too +Cryptpad.getUserObject(function (obj) %7B%0A if (obj.error) %7B return void cb(obj); %7D %0A @@ -1938,126 +1938,90 @@ -%7D%0A - Cryptpad.getUserObject(function (obj) %7B%0A if (obj.error) %7B return void cb(obj); %7D%0A +if (d === %22full%22) %7B%0A // We want shared folders too%0A @@ -2075,16 +2075,20 @@ + uo: obj, @@ -2088,16 +2088,20 @@ o: obj,%0A + @@ -2135,35 +2135,43 @@ -%7D;%0A + %7D;%0A @@ -2262,24 +2262,28 @@ + Utils.nThen( @@ -2327,16 +2327,20 @@ + + Object.k @@ -2388,24 +2388,28 @@ tion (id) %7B%0A + @@ -2510,16 +2510,20 @@ + result.s @@ -2563,16 +2563,20 @@ + + %7D));%0A @@ -2588,36 +2588,44 @@ -%7D);%0A + %7D);%0A @@ -2675,16 +2675,20 @@ + cb(resul @@ -2703,36 +2703,175 @@ + + %7D);%0A + return;%0A %7D%0A // We want only the user object%0A cb(obj);%0A @@ -2954,32 +2954,89 @@ on (data, cb) %7B%0A + if (data && data.uo) %7B data = data.uo; %7D%0A
bdb4f2630e80b3567923f47a041f2523613479ba
Clear black
game/assets/scripts/main.js
game/assets/scripts/main.js
JavaScript
0.000008
@@ -0,0 +1,202 @@ +var resolution;%0A%0Afunction update(dt)%0A%7B%0A%7D%0A%0Afunction render()%0A%7B%0A // Cache latest resolution each frame%0A resolution = Renderer.getResolution();%0A%0A // Clear black%0A Renderer.clear(Color.BLACK);%0A%7D%0A
1611ff6263e6e146867a54fcaa5d8603d77d2156
Update index.ios.js
autoHeightWebView/index.ios.js
autoHeightWebView/index.ios.js
'use strict'; import React, { PureComponent } from 'react'; import { Animated, StyleSheet, ViewPropTypes, WebView } from 'react-native'; import PropTypes from 'prop-types'; import { isEqual, setState, getWidth, isSizeChanged, handleSizeUpdated, domMutationObserveScript, getCurrentSize } from './common.js'; import momoize from './momoize'; export default class AutoHeightWebView extends PureComponent { static propTypes = { hasIframe: PropTypes.bool, onNavigationStateChange: PropTypes.func, onMessage: PropTypes.func, source: WebView.propTypes.source, customScript: PropTypes.string, customStyle: PropTypes.string, enableAnimation: PropTypes.bool, style: ViewPropTypes.style, scrollEnabled: PropTypes.bool, // either height or width updated will trigger this onSizeUpdated: PropTypes.func, // if set to true may cause some layout issues (smaller font size) scalesPageToFit: PropTypes.bool, // only works on enable animation animationDuration: PropTypes.number, // offset of rn webview margin heightOffset: PropTypes.number, // rn WebView callback onError: PropTypes.func, onLoad: PropTypes.func, onLoadStart: PropTypes.func, onLoadEnd: PropTypes.func, onShouldStartLoadWithRequest: PropTypes.func, // 'web/' by default baseUrl: PropTypes.string, // add baseUrl/files... to project root files: PropTypes.arrayOf( PropTypes.shape({ href: PropTypes.string, type: PropTypes.string, rel: PropTypes.string }) ) }; static defaultProps = { baseUrl: 'web/', scalesPageToFit: false, enableAnimation: true, animationDuration: 255, heightOffset: 12 }; constructor(props) { super(props); const { enableAnimation, style } = props; enableAnimation && (this.opacityAnimatedValue = new Animated.Value(0)); this.webView = React.createRef(); this.state = { isSizeChanged: false, width: getWidth(style), height: style && style.height ? style.height : 0 }; } getUpdatedState = momoize(setState, isEqual); static getDerivedStateFromProps(props, state) { const { height: oldHeight, width: oldWidth } = state; const height = props.style ? props.style.height : null; const width = props.style ? props.style.width : null; if (isSizeChanged(height, oldHeight, width, oldWidth)) { return { height: height || oldHeight, width: width || oldWidth, isSizeChanged: true }; } return null; } componentDidUpdate() { const { height, width, isSizeChanged } = this.state; if (isSizeChanged) { const { enableAnimation, animationDuration, onSizeUpdated } = this.props; if (enableAnimation) { Animated.timing(this.opacityAnimatedValue, { toValue: 1, duration: animationDuration }).start(() => { handleSizeUpdated(height, width, onSizeUpdated); }); } else { handleSizeUpdated(height, width, onSizeUpdated); } this.setState({ isSizeChanged: false }); } } handleNavigationStateChange = navState => { const { title } = navState; const { onNavigationStateChange } = this.props; if (!title) { onNavigationStateChange && onNavigationStateChange(navState); return; } const [heightValue, widthValue] = title.split(','); const width = Number(widthValue); const height = Number(heightValue); const { height: oldHeight, width: oldWidth } = this.state; if (isSizeChanged(height, oldHeight, width, oldWidth)) { this.props.enableAnimation && this.opacityAnimatedValue.setValue(0); this.setState({ isSizeChanged: true, height, width }); } onNavigationStateChange && onNavigationStateChange(navState); }; stopLoading() { this.webView.current.stopLoading(); } render() { const { height, width } = this.state; const { onMessage, onError, onLoad, onLoadStart, onLoadEnd, onShouldStartLoadWithRequest, scalesPageToFit, enableAnimation, heightOffset, style, scrollEnabled } = this.props; const { source, script } = this.getUpdatedState(this.props, getBaseScript, getIframeBaseScript); return ( <Animated.View style={[ styles.container, { opacity: enableAnimation ? this.opacityAnimatedValue : 1, width, height: height + heightOffset }, style ]} > <WebView originWhitelist={['*']} ref={this.webView} onMessage={onMessage} onError={onError} onLoad={onLoad} onLoadStart={onLoadStart} onLoadEnd={onLoadEnd} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} style={styles.webView} scrollEnabled={!!scrollEnabled} scalesPageToFit={scalesPageToFit} injectedJavaScript={script} source={source} onNavigationStateChange={this.handleNavigationStateChange} /> </Animated.View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'transparent' }, webView: { flex: 1, backgroundColor: 'transparent' } }); const commonScript = ` updateSize(); window.addEventListener('load', updateSize); window.addEventListener('resize', updateSize); `; function getBaseScript(style) { return ` ; ${getCurrentSize} (function () { if (!document.getElementById("rnahw-wrapper")) { var height = 0; var width = ${getWidth(style)}; var wrapper = document.createElement('div'); wrapper.id = 'rnahw-wrapper'; while (document.body.firstChild instanceof Node) { wrapper.appendChild(document.body.firstChild); } document.body.appendChild(wrapper); function updateSize() { if (document.body.offsetHeight !== height || document.body.offsetWidth !== width) { var size = getSize(wrapper); height = size.height; width = size.width; document.title = height.toString() + ',' + width.toString(); } } ${commonScript} ${domMutationObserveScript} } } ()); `; } function getIframeBaseScript(style) { return ` ; ${getCurrentSize} (function () { var height = 0; var width = ${getWidth(style)}; function updateSize() { if(document.body.offsetHeight !== height || document.body.offsetWidth !== width) { var size = getSize(document.body.firstChild); height = size.height; width = size.width; document.title = height.toString() + ',' + width.toString(); } } ${commonScript} ${domMutationObserveScript} } ()); `; }
JavaScript
0.000001
@@ -5157,24 +5157,67 @@ tateChange%7D%0A + allowsInlineMediaPlayback=%7Btrue%7D%0A /%3E%0A
72ce6406eb17f1c77721b2a1bf715f41d4228220
modify active channel logic when rejoining channels after reconnection
src/redux/chat/index.js
src/redux/chat/index.js
import Config from '~/core/config'; import Event from '~/helpers/Event'; import Error from '~/helpers/Error'; import { toggleSideBar } from '~/redux/navigation'; import { nth, omit, tail, without } from 'lodash'; const INITIALIZE_CHAT = 'INITIALIZE_CHAT'; const RESET_CHAT = 'RESET_CHAT'; const JOIN_CHANNEL = 'JOIN_CHANNEL'; const LEAVE_CHANNEL = 'LEAVE_CHANNEL'; const SWITCH_CHANNEL = 'SWITCH_CHANNEL'; const SEND_MESSAGE_PENDING = 'SEND_MESSAGE_PENDING'; const SEND_MESSAGE_SUCCESS = 'SEND_MESSAGE_SUCCESS'; const SEND_MESSAGE_ERROR = 'SEND_MESSAGE_ERROR'; const EVENT = 'EVENT'; const initialState = { activeChannel: Config.idleChannel, initialized: false, channels: { [Config.idleChannel]: { idle: true, users: [], events: [], viewed: true, }, }, error: null, pendingMessage: false, }; export default function reducer(state = initialState, action = {}) { switch (action.type) { case INITIALIZE_CHAT: return Object.assign({}, state, { initialized: true, }); case JOIN_CHANNEL: return Object.assign({}, state, { activeChannel: action.channel, channels: Object.assign({}, state.channels, { [action.channel]: { idle: false, users: [], events: action.events, viewed: true, }, }), }); case LEAVE_CHANNEL: return Object.assign({}, state, { activeChannel: action.activeChannel, channels: omit(state.channels, action.channel), }); case SEND_MESSAGE_PENDING: return Object.assign({}, state, { pendingMessage: true, }); case SEND_MESSAGE_SUCCESS: return Object.assign({}, state, { pendingMessage: false, }); case SEND_MESSAGE_ERROR: return Object.assign({}, state, { pendingMessage: false, error: action.error, }); case EVENT: case SWITCH_CHANNEL: return Object.assign({}, state, action.payload); case RESET_CHAT: return initialState; default: return state; } } export function emitEvent(event = {}) { return (dispatch, getState) => { const { chat } = getState(); const { activeChannel, channels } = chat; const data = event.data; const channel = data.channel || activeChannel; let c = channels[channel]; let payload = {}; switch (event.action) { case 'join': case 'leave': payload = { channels: Object.assign({}, channels, { [channel]: { ...c, events: [...c.events, data], users: data.users, viewed: (data.silent) ? c.viewed : activeChannel === channel, }, }), }; break; case 'quit': payload = { channels, }; data.channels.forEach((chan) => { c = channels[chan]; if (c) { const isInAC = channels[activeChannel].users.indexOf(data.username) !== -1; payload.channels = Object.assign({}, payload.channels, { [chan]: { ...c, events: [...c.events, data], viewed: (!isInAC) ? false : c.viewed, }, }); } }); break; case 'event': case 'message': payload = { channels: Object.assign({}, channels, { [channel]: { ...c, events: [...c.events, data], viewed: (data.silent) ? c.viewed : activeChannel === channel, }, }), }; break; default: payload = event; break; } dispatch({ type: EVENT, payload, }); }; } export function switchChannel(channel) { return (dispatch, getState) => { const { channels } = getState().chat; const c = channels[channel]; dispatch({ type: SWITCH_CHANNEL, payload: { activeChannel: channel, channels: Object.assign({}, channels, { [channel]: { ...c, viewed: true, }, }), }, }); }; } export function joinChannel(channel, rejoin = false) { return (dispatch, getState) => { const store = getState(); const { socket } = store.primus; const { sidebarOpen } = store.navigation; const c = store.chat.channels[channel]; if (c && !rejoin) { dispatch(switchChannel(channel)); } else if (!c || rejoin) { socket.writeAndWait({ action: 'join-channel', data: { channel }, }, (err) => { if (err) { dispatch(emitEvent(new Error(err))); } else { dispatch({ type: JOIN_CHANNEL, channel, events: (c) ? c.events : [], }); if (sidebarOpen) { dispatch(toggleSideBar(false)); } } }); } }; } export function leaveChannel(channel) { return (dispatch, getState) => { const store = getState(); const { socket } = store.primus; const { channels } = store.chat; const c = channels[channel]; const keys = Object.keys(channels); const nextChannel = keys.indexOf(channel) - 1; let activeChannel = tail(without(keys, channel)); if (nextChannel > -1) { activeChannel = nth(keys, nextChannel); } if (c) { socket.writeAndWait({ action: 'leave-channel', data: { channel }, }, (err) => { if (err) { dispatch(emitEvent(new Error(err))); } else { dispatch({ type: LEAVE_CHANNEL, activeChannel, channel, }); } }); } }; } export function rejoinChannels() { return (dispatch, getState) => { const { channels } = getState().chat; Object.keys(channels).forEach((channel) => { if (!channels[channel].idle) { dispatch(joinChannel(channel, true)); } }); }; } function sendMessagePending() { return { type: SEND_MESSAGE_PENDING, }; } function sendMessageSuccess() { return { type: SEND_MESSAGE_SUCCESS, }; } function sendMessageError(error) { return { type: SEND_MESSAGE_ERROR, error, }; } export function resetChat() { return { type: RESET_CHAT, }; } export function sendMessage(message, callback = () => {}) { return (dispatch, getState) => { const store = getState(); const { socket } = store.primus; const { activeChannel } = store.chat; dispatch(sendMessagePending()); socket.writeAndWait({ action: 'send-message', data: { channel: activeChannel, message, }, }, (err) => { if (err) { dispatch(sendMessageError(err)); dispatch(emitEvent(new Error(err))); } else { dispatch(sendMessageSuccess()); } callback(err); }); }; } export function initializeChat() { return (dispatch, getState) => { const { socket } = getState().primus; dispatch({ type: INITIALIZE_CHAT, }); socket.on('open', () => dispatch(emitEvent(new Event('connected')))); socket.on('data', (data) => dispatch(emitEvent(data))); socket.on('reconnect', () => dispatch(emitEvent(new Event('reconnecting')))); socket.on('reconnect failed', () => dispatch(emitEvent(new Event('reconnect failed')))); }; }
JavaScript
0
@@ -1110,32 +1110,72 @@ activeChannel: + (action.rejoin) ? state.activeChannel : action.channel, @@ -4860,24 +4860,44 @@ vents : %5B%5D,%0A + rejoin,%0A %7D)
056953f2c1cbb9506edf0dcdbc4bfcc30fe0d93c
Fix cropping of canvas for float sized elements
src/renderers/Canvas.js
src/renderers/Canvas.js
_html2canvas.Renderer.Canvas = function(options) { options = options || {}; var doc = document, safeImages = [], testCanvas = document.createElement("canvas"), testctx = testCanvas.getContext("2d"), canvas = options.canvas || doc.createElement('canvas'); function createShape(ctx, args) { ctx.beginPath(); args.forEach(function(arg) { ctx[arg.name].apply(ctx, arg['arguments']); }); ctx.closePath(); } function safeImage(item) { if (safeImages.indexOf(item['arguments'][0].src ) === -1) { testctx.drawImage(item['arguments'][0], 0, 0); try { testctx.getImageData(0, 0, 1, 1); } catch(e) { testCanvas = doc.createElement("canvas"); testctx = testCanvas.getContext("2d"); return false; } safeImages.push(item['arguments'][0].src); } return true; } function isTransparent(backgroundColor) { return (backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)"); } function renderItem(ctx, item) { switch(item.type){ case "variable": ctx[item.name] = item['arguments']; break; case "function": if (item.name === "createPattern") { if (item['arguments'][0].width > 0 && item['arguments'][0].height > 0) { try { ctx.fillStyle = ctx.createPattern(item['arguments'][0], "repeat"); } catch(e) { _html2canvas.Util.log("html2canvas: Renderer: Error creating pattern", e.message); } } } else if (item.name === "drawShape") { createShape(ctx, item['arguments']); } else if (item.name === "drawImage") { if (item['arguments'][8] > 0 && item['arguments'][7] > 0) { if (!options.taintTest || (options.taintTest && safeImage(item))) { ctx.drawImage.apply( ctx, item['arguments'] ); } } } else { ctx[item.name].apply(ctx, item['arguments']); } break; } } return function(zStack, options, document, queue, _html2canvas) { var ctx = canvas.getContext("2d"), render = renderItem.bind(null, ctx), newCanvas, bounds, fstyle; canvas.width = canvas.style.width = options.width || zStack.ctx.width; canvas.height = canvas.style.height = options.height || zStack.ctx.height; fstyle = ctx.fillStyle; ctx.fillStyle = (isTransparent(zStack.backgroundColor) && options.background !== undefined) ? options.background : zStack.backgroundColor; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = fstyle; queue.forEach(function(storageContext) { // set common settings for canvas ctx.textBaseline = "bottom"; ctx.save(); if (storageContext.transform.matrix) { ctx.transform.apply(ctx, storageContext.transform.matrix); } if (storageContext.clip){ ctx.beginPath(); ctx.rect(storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height); ctx.clip(); } if (storageContext.ctx.storage) { storageContext.ctx.storage.forEach(render); } ctx.restore(); }); _html2canvas.Util.log("html2canvas: Renderer: Canvas renderer done - returning canvas obj"); if (options.elements.length === 1) { if (typeof options.elements[0] === "object" && options.elements[0].nodeName !== "BODY") { // crop image to the bounds of selected (single) element bounds = _html2canvas.Util.Bounds(options.elements[0]); newCanvas = document.createElement('canvas'); newCanvas.width = bounds.width; newCanvas.height = bounds.height; ctx = newCanvas.getContext("2d"); ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height); canvas = null; return newCanvas; } } return canvas; }; };
JavaScript
0
@@ -3679,16 +3679,26 @@ width = +Math.ceil( bounds.w @@ -3697,24 +3697,25 @@ bounds.width +) ;%0A ne @@ -3731,16 +3731,26 @@ eight = +Math.ceil( bounds.h @@ -3754,16 +3754,17 @@ s.height +) ;%0A
4caab5d11b93f3d2d1fe721325c5b70425895a28
Rename selectors
q.js
q.js
function q(path, matcher) { path = (typeof path === 'string') ? path.split("/").filter(nonEmpty) : path; matcher = matcher || valueDefined; var selectors = asSelectors(path, matcher); var defaultValue = undefined; function selectFrom(item) { if (typeof item === 'undefined') { return defaultValue; } var selector = selectors.shift(); if (selector) { return selectFrom(selector(item)); } else { return item; } } return function(item) { var value = selectFrom(item); if (matcher(value)) { return value; } else { return defaultValue; } }; } function valueDefined(selectedValue) { return typeof selectedValue !== 'undefined'; } function nonEmpty(selector) { return selector.length > 0; } function asSelectors(path, matcher) { if (path.length === 0) { return []; } var spec = parseComponents(path[0]); var remainingPath = path.slice(1); var selectors = []; if (spec.field.length > 0) { selectors.push(fieldSelector(spec.field)); } if (spec.index) { if (spec.index === '*') { selectors.push(anyIndexSelector(remainingPath, matcher)); remainingPath = []; // omit the remaining path } else { selectors.push(numericIndexSelector(spec.index)); } } var remainingSelectors = asSelectors(remainingPath); return selectors.concat(remainingSelectors); } function parseComponents(spec) { var indexed = spec[spec.length-1] === ']'; if (!indexed) { return { field : spec }; } else { var field = spec.substring(0, spec.lastIndexOf('[')); var index = spec.substring(spec.lastIndexOf('[')+1, spec.lastIndexOf(']')); return { field : field, index : index }; } } function fieldSelector(fieldName) { return function(object) { return object[fieldName]; }; } function numericIndexSelector(index) { index = (typeof index === 'string') ? parseInt(index, 10) : index; return function(array) { return array[index]; } } function anyIndexSelector(path, matcher) { return function(array) { var len = array.length; var match; for (var idx = 0; idx < len; idx++) { match = q(path, matcher)(array[idx]); if (typeof match !== 'undefined') { break; } } return match; } } module.exports = q;
JavaScript
0.000001
@@ -1137,29 +1137,27 @@ rs.push( -fieldSelector +selectField (spec.fi @@ -1253,32 +1253,40 @@ rs.push( -anyIndexSelector +selectFirstMatchingIndex (remaini @@ -1407,36 +1407,27 @@ rs.push( -numericIndexSelector +selectIndex (spec.in @@ -1927,21 +1927,19 @@ ion -fieldSelector +selectField (fie @@ -2035,28 +2035,19 @@ ion -numericIndexSelector +selectIndex (ind @@ -2203,24 +2203,32 @@ ion -anyIndexSelector +selectFirstMatchingIndex (pat
65d4d05d9516c70f0e78813d49a97c3b1cb4674e
build with scale param
ngGoogleStaticMaps.min.js
ngGoogleStaticMaps.min.js
!function(){function e(){var e,t;this.useApiKey=function(e){t=e},this.forceProtocol=function(t){return angular.isString(t)?(e=t?t.replace(/:$/,"")+":":t,this):e},this.$get=[function(){return{getProtocol:function(){return e||""},getApiKey:function(){return t||""}}}]}function t(e){function t(t,r,i){var o=r[0];if(!i.mapWidth)throw new Error("The `mapWidth` is required.");if(!i.mapHeight)throw new Error("The `mapHeight` is required.");if(!i.address)throw new Error("The `address` is required.");var a="&zoom=";a+=i.zoom?i.zoom:"14";var n=e.getProtocol()+"//maps.googleapis.com/maps/api/staticmap?center=",c="&size="+i.mapWidth+"x"+i.mapHeight,s=encodeURIComponent(i.address),p="&markers=color:red|"+s,u="&key="+e.getApiKey();o.alt=i.address,o.src=n+s+c+a+p+u}var r={link:t,template:'<img alt="Google Static Map">',replace:!0,restrict:"E"};return r}t.$inject=["staticMap"],angular.module("ngGoogleStaticMaps",[]).provider("staticMap",e).directive("staticMap",t)}();
JavaScript
0
@@ -24,17 +24,17 @@ )%7Bvar e, -t +r ;this.us @@ -53,17 +53,17 @@ tion(e)%7B -t +r =e%7D,this @@ -86,17 +86,17 @@ unction( -t +r )%7Breturn @@ -117,17 +117,17 @@ ing( -t +r )?(e= -t?t +r?r .rep @@ -144,17 +144,17 @@ %22%22)+%22:%22: -t +r ,this):e @@ -249,17 +249,17 @@ %7Breturn -t +r %7C%7C%22%22%7D%7D%7D%5D @@ -268,17 +268,17 @@ unction -t +r (e)%7Bfunc @@ -286,21 +286,21 @@ ion -t(t,r +r(r,t ,i)%7Bvar o=r%5B @@ -299,11 +299,11 @@ var -o=r +a=t %5B0%5D; @@ -492,17 +492,17 @@ .%22);var -a +o =%22&zoom= @@ -503,17 +503,17 @@ &zoom=%22; -a +o +=i.zoom @@ -531,16 +531,61 @@ %22;var n= +%22&scale=%22;n+=i.mapScale?i.mapScale:%221%22;var c= e.getPro @@ -643,17 +643,17 @@ enter=%22, -c +s =%22&size= @@ -681,17 +681,17 @@ pHeight, -s +p =encodeU @@ -713,17 +713,17 @@ ddress), -p +u =%22&marke @@ -741,11 +741,11 @@ d%7C%22+ -s,u +p,m =%22&k @@ -763,17 +763,17 @@ piKey(); -o +a .alt=i.a @@ -783,39 +783,41 @@ ess, -o +a .src= -n+s+c+a+p+u +c+p+s+o+u+n+m %7Dvar -r +t =%7Blink: -t +r ,tem @@ -890,11 +890,11 @@ urn -r%7Dt +t%7Dr .$in @@ -998,14 +998,14 @@ ticMap%22, -t +r )%7D();
c0bb6aa6a4a138551756c7d6d51ef5652ba41157
Attach the knownLength value to the body stream
node_modules/form-data.js
node_modules/form-data.js
'use strict' var path = require('path') var mime = require('mime-types') function generate (options) { var parts = [] Object.keys(options.multipart).forEach(function (key) { var part = options.multipart[key] parts.push({ 'content-disposition': 'form-data; name="' + key + '"' + getContentDisposition(part), 'content-type': getContentType(part), body: part.value || part }) }) return parts } function getContentDisposition (part) { var body = part.value || part , options = part.options || {} var filename = '' if (options.filename) { filename = options.filename } // fs- and request- streams else if (body.path) { filename = body.path } // http response else if (body.readable && body.hasOwnProperty('httpVersion')) { filename = body.client._httpMessage.path } var contentDisposition = '' if (filename) { contentDisposition = '; filename="' + path.basename(filename) + '"' } return contentDisposition } function getContentType (part) { var body = part.value || part , options = part.options || {} var contentType = '' if (options.contentType) { contentType = options.contentType } // fs- and request- streams else if (body.path) { contentType = mime.lookup(body.path) } // http response else if (body.readable && body.hasOwnProperty('httpVersion')) { contentType = body.headers['content-type'] } else if (options.filename) { contentType = mime.lookup(options.filename) } else if (typeof body === 'object') { contentType = 'application/octet-stream' } else if (typeof body === 'string') { contentType = 'text/plain' } return contentType } exports.generate = generate
JavaScript
0.000052
@@ -67,16 +67,51 @@ types')%0A + , isstream = require('isstream')%0A %0A%0Afuncti @@ -248,16 +248,179 @@ rt%5Bkey%5D%0A +%0A var body = part.value %7C%7C part%0A if (isstream(body) && part.options && part.options.knownLength) %7B%0A body._knownLength = part.options.knownLength%0A %7D%0A%0A part @@ -584,34 +584,20 @@ body: -part.value %7C%7C part +body %0A %7D)%0A
b32b0ebecb992900ece16c112a7c96af6c9c3041
Remove logs
tcms/media/js/ckeditor_config.js
tcms/media/js/ckeditor_config.js
CKEDITOR.editorConfig = function(config) { console.log("ACA"); config.toolbar_tCMS = [ ['Source'], ['Cut','Copy','Paste','PasteText','PasteFromWord'], ['Undo','Redo','-','Find','Replace','-','Link','Unlink','Anchor'], ['Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['Bold','Italic','Underline','Strike'], ['Styles','Format','TextColor','FontSize','-','RemoveFormat'] ]; console.log("ACA2"); };
JavaScript
0.000001
@@ -42,33 +42,8 @@ %7B%0D%0A - console.log(%22ACA%22);%0D%0A %09con @@ -437,34 +437,8 @@ %5D;%0D%0A - console.log(%22ACA2%22);%0D%0A %7D;%0D%0A
a83fa3539c31885b76f2102c4359dfa985000626
fix mongoose versioning
db.js
db.js
const mongoose = require('mongoose'); exports.mongoose = mongoose; // -------------------------------------------------------------------------------------- var logs_schema = mongoose.Schema({ timestamp : Date, realm : String, viscountry : String, visinst : String, csi : String, pn : String, result : String }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.logs_schema = logs_schema; var logs = mongoose.model('logs', logs_schema, 'logs'); exports.logs = logs; // -------------------------------------------------------------------------------------- var users_mac_schema = mongoose.Schema({ username : String, addrs : Array }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.users_mac_schema = users_mac_schema; var users_mac = mongoose.model('users_mac', users_mac_schema, 'users_mac'); exports.users_mac = users_mac; // -------------------------------------------------------------------------------------- var privileged_ips_schema = mongoose.Schema({ ip : String }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.privileged_ips_schema = privileged_ips_schema; var privileged_ips = mongoose.model('privileged_ips', privileged_ips_schema, 'privileged_ips'); exports.privileged_ips = privileged_ips; // -------------------------------------------------------------------------------------- var mac_count_schema = mongoose.Schema({ username : String, count : Number, addrs : Array, timestamp : Date }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.mac_count_schema = mac_count_schema; var mac_count = mongoose.model('mac_count', mac_count_schema, 'mac_count'); exports.mac_count = mac_count; // -------------------------------------------------------------------------------------- var roaming_schema = mongoose.Schema({ inst_name : String, used_count : Number, provided_count : Number, timestamp : Date }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.roaming_schema = roaming_schema; var roaming = mongoose.model('roaming', roaming_schema, 'roaming'); exports.roaming = roaming; // -------------------------------------------------------------------------------------- var failed_logins_schema = mongoose.Schema({ username : String, timestamp : Date, fail_count : Number, ok_count : Number, ratio : Number }); // -------------------------------------------------------------------------------------- exports.failed_logins_schema = failed_logins_schema; var failed_logins = mongoose.model('failed_logins', failed_logins_schema, 'failed_logins'); exports.failed_logins = failed_logins; // -------------------------------------------------------------------------------------- var realm_admins_schema = mongoose.Schema({ realm : String, admins : Array }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.realm_admins_schema = realm_admins_schema; var realm_admins = mongoose.model('realm_admins', realm_admins_schema, 'realm_admins'); exports.realm_admins = realm_admins; // -------------------------------------------------------------------------------------- var shared_mac_schema = mongoose.Schema({ timestamp : Date, mac_address : String, users : Array, count : Number }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.shared_mac_schema = shared_mac_schema; var shared_mac = mongoose.model('shared_mac', shared_mac_schema, 'shared_mac'); exports.shared_mac = shared_mac; // -------------------------------------------------------------------------------------- var heat_map_schema = mongoose.Schema({ timestamp : Date, realm : String, institutions : Array }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.heat_map_schema = heat_map_schema; var heat_map = mongoose.model('heat_map', heat_map_schema, 'heat_map'); exports.heat_map = heat_map; // -------------------------------------------------------------------------------------- var realms_schema = mongoose.Schema({ realm : String }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.realms_schema = realms_schema; var realms = mongoose.model('realms', realms_schema, 'realms'); exports.realms = realms; // -------------------------------------------------------------------------------------- var succ_logins_schema = mongoose.Schema({ timestamp : Date, username : String, count : Number }, { versionKey: false }); // -------------------------------------------------------------------------------------- exports.succ_logins_schema = succ_logins_schema; var succ_logins = mongoose.model('succ_logins', succ_logins_schema, 'succ_logins'); exports.succ_logins = succ_logins; // -------------------------------------------------------------------------------------- mongoose.connection.on('error', console.error.bind(console, 'connection error:')); mongoose.connection.once('open', function (callback) { console.log("sucesfully connected do mongodb database on localhost"); }); // -------------------------------------------------------------------------------------- // connect to the databse // -------------------------------------------------------------------------------------- exports.connect = function() { mongoose.connect('mongodb://localhost/etlog'); } // -------------------------------------------------------------------------------------- // disconnect from the databse // -------------------------------------------------------------------------------------- exports.disconnect = function() { mongoose.connection.close(); } // --------------------------------------------------------------------------------------
JavaScript
0.000002
@@ -2664,16 +2664,39 @@ Number%0A +%7D,%0A%7B versionKey: false %7D);%0A// -
bcc51bb45735eeb273de40d969d82ec0e8636e81
Fix ga.js hostname control
ga.js
ga.js
// Analytics for Vaadin Components (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-658457-6', 'auto'); function locationHashChanged() { if(window.location.hostname === 'vaadin.github.io') { var pageViewUrl = (window.location.pathname + window.location.hash).replace('#', '/'); ga('send', 'pageview', pageViewUrl) } } window.onhashchange = locationHashChanged; locationHashChanged();
JavaScript
0.005199
@@ -423,16 +423,30 @@ %7B%0A if( +/vaadin/.test( window.l @@ -465,31 +465,9 @@ name - === 'vaadin.github.io' +) ) %7B%0A
de891b326b79969085dedaf2463fb7abbd96cb64
remove ioctl pledge
pp.js
pp.js
#!/usr/bin/env node // Quick example of a pledged node app. // usage: // $ echo '{"a":1,"b":3}' | ./pp.js var data = '', pledge = require('node-pledge'); pledge.init('stdio ioctl rpath wpath tty'); process.stdin.setEncoding('utf8'); process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) { data += chunk; } }); process.stdin.on('end', function() { data = JSON.parse(data); console.log(JSON.stringify(data, null, 2)); });
JavaScript
0
@@ -172,14 +172,8 @@ dio -ioctl rpat
3c71172f801581f92d08c192dc7cf250c98d6317
test to see if the fetch event handler function is breaking resitration
sw.js
sw.js
this.addEventListener('install', function(event) { event.waitUntil( caches.create('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyHunters.jpg', '/sw-test/gallery/myLittleVader.jpg', '/sw-test/gallery/snowTroopers.jpg' ); }) ); }); // You could also do // this.addEventListener('install', function(event) { // var starWarsAssets = new Cache(); // event.waitUntil( // starWarsAssets.add( // '/sw-test/index.html', // '/sw-test/style.css', // '/sw-test/app.js', // '/sw-test/image-list.js', // '/sw-test/star-wars-logo.jpg', // '/sw-test/gallery/', // '/sw-test/gallery/bountyHunters.jpg', // '/sw-test/gallery/myLittleVader.jpg', // '/sw-test/gallery/snowTroopers.jpg' // ) // ) // caches.set('v1', starWarsResources); // )}; // this.addEventListener('fetch', function(event) { // event.respondWith( // caches.match(event.request).catch(function() { // return event.default().then(function(response) { // caches.get('v1').then(function(cache) { // cache.put(event.request, response.clone()); // return response; // }); // }); // }).catch(function() { // return caches.match('/sw-test/gallery/myLittleVader.jpg'); // }); // ); // });
JavaScript
0.000004
@@ -1075,19 +1075,16 @@ // )%7D;%0A%0A -// this.add @@ -1124,19 +1124,16 @@ vent) %7B%0A -// event. @@ -1145,19 +1145,16 @@ ndWith(%0A -// cach @@ -1196,25 +1196,22 @@ ion() %7B%0A -// - return e @@ -1251,26 +1251,24 @@ onse) %7B%0A -// caches. @@ -1255,25 +1255,24 @@ ) %7B%0A - caches.get(' @@ -1295,27 +1295,24 @@ on(cache) %7B%0A -// ca @@ -1353,19 +1353,16 @@ one());%0A -// @@ -1380,19 +1380,16 @@ sponse;%0A -// @@ -1394,19 +1394,16 @@ %7D); %0A -// %7D) @@ -1404,19 +1404,16 @@ %7D);%0A -// %7D).c @@ -1430,24 +1430,21 @@ ion() %7B%0A -// - return c @@ -1498,19 +1498,16 @@ ');%0A -// %7D);%0A // @@ -1506,18 +1506,12 @@ %7D);%0A -// - );%0A -// %7D);
67ea5c184f39e934f21c008dee29b3e53389e34a
remove bogus pointer zeroing code
mark_sweep.js
mark_sweep.js
Allocation = function(start, length) { this.start = start; this.length = length; this.marked = false; }; MarkSweep = function(heapSize, heapSegmentSize) { this.heapSize = heapSize || 262138; this.heap = new Int32Array(this.heapSize); this.heapSegmentSize = heapSegmentSize || 262138; this.heapUsage = 0; this.allocationIndex = {}; this.allocationArray = []; }; MarkSweep.prototype.expandHeapBy = function(size) { while (size > 0) { size -= this.heapSegmentSize; this.heapSize += this.heapSegmentSize; } var newHeap = new Int32Array(this.heapSize); newHeap.set(this.heap); this.heap = newHeap; }; MarkSweep.prototype.findFreeSpace = function(size) { var all = this.allocationArray; var prevEnd = 0; for (var i=0; i<all.length; i++) { var a = all[i]; if (a.start - prevEnd >= size) { return prevEnd; } prevEnd = a.start + a.length; } if (this.heapSize - prevEnd >= size) { return prevEnd; } return -1; }; MarkSweep.prototype.cmp = function(a,b) { return a.start - b.start; }; MarkSweep.prototype.addAllocation = function(start, length) { var a = new Allocation(start, length); this.allocationArray.push(a); this.allocationArray.sort(this.cmp); this.allocationIndex[start | 0x80000000] = a; this.heapUsage += length; return a; }; MarkSweep.prototype.deleteAllocation = function(a) { var idx = this.allocationArray.indexOf(a); if (idx == -1) { return; } this.allocationArray.splice(idx, 1); delete this.allocationIndex[a.start | 0x80000000]; this.heapUsage -= a.length; }; MarkSweep.prototype.markPointers = function(start, length) { for (var last=start+length; start < last; start++) { var v = this.heap[start]; if (this.isPointer(v)) { var a = this.allocationIndex[v]; if (a === undefined) { this.heap[start] = 0; } else { a.marked = true; } } } }; MarkSweep.prototype.setPtr = function(offset, value) { this.heap[offset] = value | 0x80000000; }; MarkSweep.prototype.setWord = function(offset, value) { this.heap[offset] = value; }; MarkSweep.prototype.getWord = function(offset) { return this.heap[offset]; }; MarkSweep.prototype.unmarkAllocations = function() { for (var i=0, l=this.allocationArray.length; i<l; i++) { this.allocationArray[i].marked = false; } }; MarkSweep.prototype.allocate = function(size) { var ptr = this.findFreeSpace(size); if (ptr < 0) { this.expandHeapBy(size); ptr = this.findFreeSpace(size); } return this.addAllocation(ptr, size); }; MarkSweep.prototype.isPointer = function(v) { return ((v & 0x80000000) != 0); }; MarkSweep.prototype.gc = function() { this.mark(); this.sweep(); }; MarkSweep.prototype.mark = function() { var i,l,v,j,k,seg,a; this.unmarkAllocations(); var all = this.allocationArray; for (i=0, l=all.length; i<l; i++) { a = all[i]; this.markPointers(a.start, a.length); } }; MarkSweep.prototype.sweep = function() { var i, a, l; var all = this.allocationArray; var freed = []; for (i=0, l=all.length; i<l; i++) { a = all[i]; if (!a.marked) { freed.push(a); } } for (i=0, l=freed.length; i<l; i++) { this.deleteAllocation(freed[i]); } };
JavaScript
0.000001
@@ -1838,17 +1838,17 @@ if (a -= +! == undef @@ -1859,46 +1859,8 @@ ) %7B%0A -%09%09this.heap%5Bstart%5D = 0;%0A%09 %7D else %7B%0A %09%09a.
a318287bc9449499cfea594bc328f85a4e63c6c8
修复如果用户首次未点授权登录后面在个人页点"重新授权登录"始终无效的问题
pages/my/index.js
pages/my/index.js
const app = getApp() const CONFIG = require('../../config.js') const WXAPI = require('../../wxapi/main') Page({ data: { balance:0.00, freeze:0, score:0, score_sign_continuous:0 }, onLoad() { }, onShow() { let that = this; let userInfo = wx.getStorageSync('userInfo') if (!userInfo) { app.goLoginPageTimeOut() } else { that.setData({ userInfo: userInfo, version: CONFIG.version, vipLevel: app.globalData.vipLevel }) } this.getUserApiInfo(); this.getUserAmount(); }, aboutUs : function () { wx.showModal({ title: '关于我们', content: '本系统基于开源小程序商城系统 https://github.com/EastWorld/wechat-app-mall 搭建,祝大家使用愉快!', showCancel:false }) }, getPhoneNumber: function(e) { if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") { wx.showModal({ title: '提示', content: '无法获取手机号码:' + e.detail.errMsg, showCancel: false }) return; } var that = this; WXAPI.bindMobile({ token: wx.getStorageSync('token'), encryptedData: e.detail.encryptedData, iv: e.detail.iv }).then(function (res) { if (res.code === 10002) { app.goLoginPageTimeOut() return } if (res.code == 0) { wx.showToast({ title: '绑定成功', icon: 'success', duration: 2000 }) that.getUserApiInfo(); } else { wx.showModal({ title: '提示', content: '绑定失败', showCancel: false }) } }) }, getUserApiInfo: function () { var that = this; WXAPI.userDetail(wx.getStorageSync('token')).then(function (res) { if (res.code == 0) { let _data = {} _data.apiUserInfoMap = res.data if (res.data.base.mobile) { _data.userMobile = res.data.base.mobile } that.setData(_data); } }) }, getUserAmount: function () { var that = this; WXAPI.userAmount(wx.getStorageSync('token')).then(function (res) { if (res.code == 0) { that.setData({ balance: res.data.balance.toFixed(2), freeze: res.data.freeze.toFixed(2), score: res.data.score }); } }) }, relogin:function(){ app.goLoginPageTimeOut() }, goAsset: function () { wx.navigateTo({ url: "/pages/asset/index" }) }, goScore: function () { wx.navigateTo({ url: "/pages/score/index" }) }, goOrder: function (e) { wx.navigateTo({ url: "/pages/order-list/index?type=" + e.currentTarget.dataset.type }) } })
JavaScript
0
@@ -2294,16 +2294,49 @@ tion()%7B%0A + app.navigateToLogin = false;%0A app.
5cc77cfae7fcc95b5bbddc24ebb81a1539d357b5
improve footer style
App.js
App.js
import React, { Component } from 'react'; import { Text, View, StyleSheet, Image } from 'react-native'; import Config from 'react-native-config'; import ForecastView from './jsx/ForecastView'; export default class App extends Component { render() { let apiBaseUrl = Config.INTENSITY_API_BASE_URL let apiKey = Config.INTENSITY_API_KEY return ( <View style={{flex: 1}}> <View style={styles.header}> <Text style={styles.headertext}>UK Grid Forecast</Text> </View> <ForecastView apiBaseUrl={apiBaseUrl} apiKey={apiKey}/> <View style={styles.footer}> <Image style={styles.footerimage} source={{ uri: "https://www.edf.org/sites/all/themes/edf/images/footLogo.gif" }} /> <Text style={styles.footertext}>Data from the National Grid</Text> </View> </View> ); } } const styles = StyleSheet.create({ header: { backgroundColor: '#bfd45f', paddingTop: 25, paddingLeft: 10, height: 70, borderBottomWidth: 2, borderColor: 'rgb(38,121,173)', marginBottom: 2, }, headertext: { color: 'white', fontWeight: 'bold', fontSize: 30, }, footer: { height: 100, flexDirection: "row", backgroundColor: '#d8e8f4', alignItems: 'center', borderTopWidth: 1, borderColor: '#c5d3de', }, footertext: { flex: 1, color: 'black', paddingLeft: 20, paddingRight: 20, }, footerimage: { flex: 1, height: 55, width: 154, }, });
JavaScript
0.000001
@@ -790,20 +790,27 @@ t%7D%3EData -from +provided by the Nat @@ -819,16 +819,59 @@ nal Grid +. Visit carbonintensity.org.uk for details. %3C/Text%3E%0A @@ -1254,18 +1254,17 @@ height: -10 +8 0,%0A f @@ -1458,44 +1458,42 @@ -padd +marg in -g Left: -2 +1 0,%0A -padd +marg in -g Right: -2 +1 0,%0A @@ -1522,47 +1522,54 @@ -flex: 1,%0A height: 55,%0A width: 154 +height: 60,%0A width: 170,%0A marginLeft: 10 ,%0A
406559e54a1c62ba09b7f088be3db1d6dcec244c
Fix body template runtime for Meteor 0.8.3 Closes #50
plugin/handler.js
plugin/handler.js
var sourceHandler = function (compileStep) { // XXX Code copied from // packages/templating/plugin/compile-template.js:6 if (! compileStep.arch.match(/^browser(\.|$)/)) return; // Parse and compile the content var content = compileStep.read().toString('utf8'); var parser = new Parser(content, compileStep.inputPath, { lexer: Lexer }); var results = new Compiler(parser.parse()).compile(); // Head if (results.head !== null) { compileStep.appendDocument({ section: "head", data: HTML.toHTML(results.head) }); } // Generate the final js file // XXX generate a source map var jsContent = ""; // Body if (results.body !== null) { jsContent += "\nUI.body.contentParts.push(UI.Component.extend({"; jsContent += "render: " + SpacebarsCompiler.codeGen(results.body, { isBody: true }); jsContent += "}));\n"; jsContent += "\nMeteor.startup(function () { if (! UI.body.INSTANTIATED) {\n"; jsContent += " UI.body.INSTANTIATED = true; UI.materialize(UI.body, document.body);\n"; jsContent += "}});\n"; } // Templates _.forEach(results.templates, function (tree, tplName) { jsContent += "\nTemplate.__define__(\"" + tplName +"\", "; jsContent += SpacebarsCompiler.codeGen(tree, { isTemplate: true }); jsContent += ");\n"; }); if (jsContent !== "") { compileStep.addJavaScript({ path: compileStep.inputPath + '.js', sourcePath: compileStep.inputPath, data: jsContent }); } }; Plugin.registerSourceHandler("jade", { isTemplate: true }, sourceHandler); // Backward compatibility with Meteor <= 0.8 // This is related to the following Meteor hack: // https://github.com/meteor/meteor/blob/ae67643a3f2de0dd9fb8db7f7bd8e1c6fe2ba285/tools/files.js#L42 Plugin.registerSourceHandler("jade.html", function(/* arguments */) { console.warn("The .jade.html extension is deprecated. Use .jade instead."); return sourceHandler(arguments); });
JavaScript
0
@@ -704,87 +704,154 @@ %22%5Cn -UI.body.contentParts.push(UI.Component.extend(%7B%22;%0A jsContent += %22render: %22 +Template.__body__.__contentParts.push(Blaze.View(%22;%0A jsContent += %22'body_content_'+Template.__body__.__contentParts.length, %22;%0A jsContent + += Spa @@ -924,17 +924,16 @@ ent += %22 -%7D ));%5Cn%22;%0A @@ -950,18 +950,16 @@ ent += %22 -%5Cn Meteor.s @@ -969,169 +969,39 @@ tup( -function () %7B if (! UI.body.INSTANTIATED) %7B%5Cn%22;%0A jsContent += %22 UI.body.INSTANTIATED = true; UI.materialize(UI.body, document.body);%5Cn%22;%0A jsContent += %22%7D%7D +Template.__body__.__instantiate );%5Cn
3a0bf28b364b896b8e38ab3930f4d3e8d310b2c3
remove debug shit
plugins/lastfm.js
plugins/lastfm.js
var request = require('request'); var nowplaying = function(user, apikey, bot, event){ console.log('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + user + '&api_key=' + apikey + '&format=json'); request('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + user + '&api_key=' + apikey + '&format=json', function(error, response, body){ console.log(body); var message = 'Could not get now playing data for ' + user + '.'; if(body){ var results = JSON.parse(body); if(results.error){ message = results.message; }else if(results.recenttracks && results.recenttracks.track){ song = results.recenttracks.track[0]; message = user + ' is listening to ' + song.name + ' by ' + song.artist['#text']; } } bot.message(event.target, event.source.nick + ': ' + message); }); }; module.exports = function(bot){ var apikey = bot.PluginConfigs.get('lastfm.apikey'), user; bot.addCommand('np', 'Show what the user is playing on last.fm', '<user>', USER_LEVEL_NORMAL, true, function(event){ if(event.params[0]){ user = event.params[0]; }else{ user = event.source.nick; } nowplaying(user, apikey, bot, event); }); bot.addCommand('lastfm', 'Show what the user is playing on last.fm', '<user>', USER_LEVEL_NORMAL, false, function(event){ if(event.params[0]){ user = event.params[0]; }else{ user = event.source.nick; } nowplaying(user, apikey, bot, event); }); };
JavaScript
0.000029
@@ -84,139 +84,8 @@ t)%7B%0A -console.log('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=' + user + '&api_key=' + apikey + '&format=json');%0A %09req
f0b14b14741ad6ddc7ee81c4fff27889a602b451
add required semicolons
app.js
app.js
const express = require('express'); const path = require('path'); const logger = require('morgan'); const cookieParser = require('cookie-parser'); const bodyParser = require('body-parser'); const compression = require('compression'); const session = require('express-session'); const csurf = require('csurf'); const tokenInjector = require('./helpers/csrf'); // template stuff const handlebars = require('handlebars'); const layouts = require('handlebars-layouts'); const handlebarsWax = require('handlebars-wax'); const authHelper = require('./helpers/authentication'); const app = express(); app.use(compression()); app.set('trust proxy', true); const themeName = process.env.SC_THEME || 'default'; // view engine setup const handlebarsHelper = require('./helpers/handlebars'); const wax = handlebarsWax(handlebars) .partials(path.join(__dirname, 'views/**/*.{hbs,js}')) .helpers(layouts) .helpers(handlebarsHelper.helpers); wax.partials(path.join(__dirname, `theme/${themeName}/views/**/*.{hbs,js}`)); const viewDirs = [path.join(__dirname, 'views')]; viewDirs.unshift(path.join(__dirname, `theme/${themeName}/views/`)); app.set('views', viewDirs); app.engine('hbs', wax.engine); app.set('view engine', 'hbs'); app.set('view cache', true); // uncomment after placing your favicon in /public // app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, `build/${themeName}`))); const sessionStore = new session.MemoryStore(); app.use(session({ cookie: { maxAge: 60000 }, store: sessionStore, saveUninitialized: true, resave: 'true', secret: 'secret', })); if (process.env.DISABLE_CSRF) { app.use(csurf({ ignoreMethods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE'] })) } else { app.use(csurf()) } app.use(tokenInjector); const defaultBaseDir = (req, res) => { let dir = process.env.DOCUMENT_BASE_DIR || 'https://s3.hidrive.strato.com/schul-cloud-hpi/'; dir += `${themeName}/`; if (themeName === 'open' && res.locals && res.locals.currentUser && res.locals.currentUser.schoolId) { // fixme currentUser missing here (after login) dir += `${res.locals.currentUser.schoolId}/`; } return dir; }; const defaultDocuments = require('./helpers/content/documents.json'); // Custom flash middleware app.use(async (req, res, next) => { if (!req.session.currentUser) { await authHelper.populateCurrentUser(req, res).then(() => { if (res.locals.currentUser) { // user is authenticated req.session.currentUser = res.locals.currentUser; req.session.save(); } }); } else { res.locals.currentUser = req.session.currentUser; } // if there's a flash message in the session request, make it available in the response, then delete it res.locals.notification = req.session.notification; res.locals.inline = req.query.inline || false; res.locals.theme = { title: process.env.SC_TITLE || 'HPI Schul-Cloud', short_title: process.env.SC_SHORT_TITLE || 'Schul-Cloud', documents: Object.assign({}, { baseDir: defaultBaseDir(req, res), privacy: process.env.PRIVACY_DOCUMENT || 'Onlineeinwilligung/Datenschutzerklaerung-Muster-Schulen-Onlineeinwilligung.pdf', termsOfUse: process.env.TERMS_OF_USE_DOCUMENT || 'Onlineeinwilligung/Nutzungsordnung-HPI-Schule-Schueler-Onlineeinwilligung.pdf', }, defaultDocuments), federalstate: process.env.SC_FEDERALSTATE || 'Brandenburg', }; res.locals.domain = process.env.SC_DOMAIN || false; delete req.session.notification; next(); }); const methodOverride = require('method-override'); app.use(methodOverride('_method')); // for GET requests app.use(methodOverride((req, res, next) => { // for POST requests if (req.body && typeof req.body === 'object' && '_method' in req.body) { // eslint-disable-next-line no-underscore-dangle const method = req.body._method; // eslint-disable-next-line no-underscore-dangle delete req.body._method; return method; } })); // Initialize the modules and their routes app.use(require('./controllers/')); app.get('/', (req, res, next) => { res.redirect('/login/'); }); // catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use((err, req, res, next) => { // set locals, only providing error in development const status = err.status || err.statusCode || 500; if (err.statusCode && err.error) { res.setHeader('error-message', err.error.message); res.locals.message = err.error.message; } else { res.locals.message = err.message; } res.locals.error = req.app.get('env') === 'development' ? err : { status }; if (res.locals.currentUser) res.locals.loggedin = true; // render the error page res.status(status); res.render('lib/error', { loggedin: res.locals.loggedin, inline: res.locals.inline ? true : !res.locals.loggedin, }); }); module.exports = app;
JavaScript
0.999999
@@ -1889,16 +1889,17 @@ CE'%5D %7D)) +; %0A%7D else @@ -1917,16 +1917,17 @@ csurf()) +; %0A%7D%0A%0Aapp.
bb7145c65351378e34107395f9e178fd32654d99
build fix
app.js
app.js
/** * Module dependencies. */ var express = require('express') , routes = require('./routes') , user = require('./routes/user') , jquery = require('./routes/jquery') , http = require('http') , https = require('https') , fs = require('fs') , path = require('path'); var environment = process.env.NODE_ENV || 'development'; var httpPort = process.env.PORT || 3000; var httpsPort = process.env.HTTPS_PORT || process.env.PORT || 3443; var app = express(); app.configure('production', function(){ app.enable('trust proxy');//for https which is set to X-Forwarded-Proto request header by Heroku app.set('https port', httpsPort); app.use(function(req, res, next) { if (req.headers['x-forwarded-proto'] != 'https') { res.redirect('https://' + req.headers.host + req.path); } else { return next(); }); }); app.configure('development', function(){ /*app.use(express.errorHandler());*/ app.set('port', httpPort); }); app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'hbs'); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('apifythyself')); app.use(express.cookieSession({ key: 'apify.session' })); app.use(app.router); app.use(require('less-middleware')({ src: path.join(__dirname, 'public') })); app.use(express.static(path.join(__dirname, 'public'))); app.use(require('express-bunyan-logger').errorLogger()); }); app.get('/', routes.index); app.get('/jquery', jquery.fetch); app.get('/snapshot', jquery.snapshot); if(environment === 'development') { http.createServer(app).listen(app.get('port'), function(){ console.log("Http Express server listening on port " + app.get('port')); }); } if(environment === 'production') { var certificate_authority = fs.readFileSync( path.join(__dirname, 'sslforfree/ca_bundle.crt') ); var certificate = fs.readFileSync( path.join(__dirname, 'sslforfree/certificate.crt') ); https.createServer( { ca: certificate_authority, cert: certificate, key: process.env.FREESSL_PRIVATE_KEY || '' },app) .listen(app.get('https port'), function(){ console.log("Https Express server listening on port " + app.get('https port')); }); }
JavaScript
0.000001
@@ -865,18 +865,16 @@ ;%0D%0A %7D -); %0D%0A%7D);%0D%0Aa
b3140168312827dc7ae10ec165a7586e9602db8e
add command
app.js
app.js
var dotenv = require('dotenv'); dotenv.load(); var express = require('express'); var app = express(); var server = require('http').createServer(app); app.use(express.static(__dirname + '/tmp')); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); var fs = require('fs'); var request = require('superagent'); var twilio = require('twilio'); require('shelljs/global'); var client = new twilio.RestClient(process.env.TWILIO_AUTH_SID, process.env.TWILIO_AUTH_TOKEN); var port = process.env.PORT || 3000; server.listen(port); console.log('Listening at port: ' + port); if(process.env.NODE_ENV === 'PRODUCTION') { var baseUrl = 'domain.com'; } else { var baseUrl = 'http://46cfc4a8.ngrok.com'; } app.post('/incoming', function(req, res) { function search(query, cb) { request .get('http://partysyncwith.me:3005/search/'+ query +'/1') .end(function(err, res) { if(err) { console.log(err); } else { if (typeof JSON.parse(res.text).data !== 'undefined') { if (JSON.parse(res.text).data[0].duration < 600) { var url = JSON.parse(res.text).data[0].video_url; cb(url); } else { cb(null); } } } }) } function startCall(url) { if (exec('youtube-dl --extract-audio --prefer-ffmpeg --audio-format mp3 --audio-quality 0 -o "tmp/%(id)s.%(ext)s" ' + url).code === 0) { var call = client.calls.create({ to: req.body.From, from: process.env.PHONE_NUMBER, url: baseUrl + '/xml/' + url.substring(url.length - 11) }); } } search(req.body.Body, function(url) { startCall(url); }); res.sendStatus(200); }); app.post('/xml/:id', function(req, res) { res.set('Content-Type', 'text/xml'); res.send('<Response><Play>' + baseUrl + '/' + req.params.id + '.mp3' + '</Play><Redirect/></Response>'); });
JavaScript
0.000292
@@ -778,16 +778,67 @@ res) %7B%0A + if(req.body.Body.substring(0, 3) === 'play') %7B%0A functi @@ -846,16 +846,21 @@ n search +Music (query, @@ -861,24 +861,26 @@ uery, cb) %7B%0A + request%0A @@ -1295,24 +1295,38 @@ cb(null);%0A + %7D%0A %7D%0A @@ -1346,21 +1346,21 @@ %7D +) %0A %7D -)%0A %7D%0A%0A +%0A%0A fu @@ -1379,24 +1379,28 @@ Call(url) %7B%0A + if (exec @@ -1530,24 +1530,28 @@ 0) %7B%0A + var call = c @@ -1579,16 +1579,20 @@ + to: req. @@ -1610,16 +1610,20 @@ + from: pr @@ -1646,16 +1646,20 @@ NUMBER,%0A + @@ -1724,23 +1724,39 @@ + %7D);%0A + %7D%0A + %7D%0A%0A + se @@ -1787,24 +1787,28 @@ tion(url) %7B%0A + startCal @@ -1817,19 +1817,28 @@ url);%0A -%7D); + %7D); %0A %7D %0A%0A res.
dfa0a2a8561e97776977e52e2e303c88fccae1a3
Update lint
app.js
app.js
'use strict'; /** * Module dependencies. */ var express = require('express'); //var routes = require('./routes'); //var soundCloud = require('./routes/soundCloud.js'); //var api = require('./routes/api.js'); var http = require('http'); //var path = require('path'); //var MongoStore = require('connect-mongo')(express); var fs = require('fs'); var passport = require('passport'); var logger = require('mean-logger'); // Load configurations var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var config = require('./backend/config/config'); var auth = require('./backend/config/middlewares/authorization'); var mongoose = require('mongoose'); // Bootstrap db connection mongoose.connect(config.db); var dbConnexion = mongoose.connection; dbConnexion.on('error', function error(error) { console.log('Error MongoDB: ' + error) }); dbConnexion.once('open', function callback() { console.log('MongoDB successfully connected.') }); // Bootstrap models var modelsPath = __dirname + '/backend/models'; var walk = function (path) { fs.readdirSync(path).forEach(function (file) { var newPath = path + '/' + file; var stat = fs.statSync(newPath); if (stat.isFile()) { if (/(.*)\.(js$|coffee$)/.test(file)) { require(newPath); } } else if (stat.isDirectory()) { walk(newPath); } }); }; walk(modelsPath); // Bootstrap passport config require('./backend/config/passport')(passport); // Create express var app = express(); // Express settings require('./backend/config/express')(app, env, passport, dbConnexion); // Bootstrap routes require('./backend/config/routes')(app, passport, auth); // Start the app by listening on the port var port = config.port; http.createServer(app).listen(port, function () { console.log('Express server listening on port ' + port); }); //Initializing logger logger.init(app, passport, mongoose); // Expose app module.exports = app;
JavaScript
0.000001
@@ -800,19 +800,16 @@ error(er -ror ) %7B%0A co @@ -844,12 +844,10 @@ + er -ror ) +; %0A%7D); @@ -943,16 +943,17 @@ ected.') +; %0A%7D);%0A%0A//
27dcad547599bf80af010d7090419f33c2af076c
add routes
app.js
app.js
var path = require('path'); var express = require('express'); var config = require('./config').config; var app = express(); var routes = require('./routes'); var userproxy = require('./proxy/userproxy'); /** * configuration in all env **/ app.configure(function(){ var viewsRoot = path.join(__dirname, 'views'); app.set('view engine', 'html'); app.set('views', viewsRoot); app.engine('html', require('ejs').renderFile); app.use(express.static(__dirname + '/public')); app.use(express.bodyParser()); app.use(express.cookieParser()); app.use("/public", express.static(__dirname + '/public')); app.use(express.session({ secret:'mozillapersona' })); }); // set routes //routes(app); app.get('/test',function(req,res,next){ userproxy.saveOrUpdateUser('testuser5','[email protected]',function(err,user){}); }); // start app app.listen(config.port); console.log("sinter listening on port %d in %s mode",config.port,app.settings.env); if (process.env.NODE_ENV == 'test') { console.log("sinter listening on port %d in %s mode",config.port,app.settings.env); }; module.exports = app;
JavaScript
0.000006
@@ -698,17 +698,16 @@ %0A%7D);%0A// - set rout @@ -709,18 +709,16 @@ routes%0A -// routes(a
62afdb86823cff2c0e15df0724ed37f9cb177d03
Fix PORT
app.js
app.js
const restify = require("restify"); const builder = require("botbuilder"); const api = require("./consumer"); // Create chat connector for communicating with the Bot Framework Service console.log(process.env); const connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); // Create Bot Instance const bot = new builder.UniversalBot(connector); // Dialogs Waterfall bot.dialog('/', [ (session) => { session.replaceDialog('/menu'); } ]); bot.dialog('/menu', [ function (session) { session.send("A continuación encontrarás diferentes organizaciones, centros de acopio o formas de ayudar a los afectados o rescatistas del sismo."); session.send("Si conoces alguna otra forma de ayudar Contáctanos en Twitter @comoayudarmx o envianos un email a [email protected]"); var choices = ["Listado general", "Filtrado por locación", "Filtrado por tipo de donacion"]; builder.Prompts.choice(session, "Que accion le gustaria realizar?", choices, { listStyle: builder.ListStyle.button }); }, function (session, results) { if (results.response) { var selection = results.response.entity; // route to corresponding dialogs switch (selection) { case "Listado general": session.replaceDialog('/findAll'); break; case "Filtrado por locación": session.replaceDialog('/findByLocation'); break; case "Filtrado por tipo de donacion": session.replaceDialog('/findByDonationType'); break; default: session.reset('/'); break; } } } ]); bot.dialog('/findAll', [ (session, args, next) => { // Connected to API let result = api.ObtenerTodos(); session.replaceDialog('/displayResults', { result }); } ]); bot.dialog('/findByLocation', [ (session, args, next) => { // Connected to API let donationTypes = api.Locations(); session.userData.location = ''; builder.Prompts.choice(session, "Filtrar por locación?", donationTypes, { listStyle: builder.ListStyle.button }); }, (session, results, next) => { if (results.response) { let selection = results.response.entity; session.userData.location = selection; // Connected to API console.log({selection}); let result = api.FilterByLocation(selection); console.log({result}); session.replaceDialog('/displayResults', { result }); } } ]); bot.dialog('/findByDonationType', [ (session, args, next) => { // Connected to API let donationTypes = api.DonationTypes(); session.userData.donationType = ''; builder.Prompts.choice(session, "Filtrar por tipo de donación?", donationTypes, { listStyle: builder.ListStyle.button }); }, (session, results, next) => { if (results.response) { let selection = results.response.entity; session.userData.donationType = selection; // Connected to API console.log({selection}); let result = api.FilterByDonationType(selection); console.log({result}); session.replaceDialog('/displayResults', { result }); } } ]); bot.dialog('/displayResults', (session, args, next) => { if (args.result) { console.log(args.result) var searchResult = args.result; // Create Reply Layout var reply = new builder.Message(session).attachmentLayout(builder.AttachmentLayout.carousel); let cards = searchResult.map((element) => { return new builder.HeroCard(session) .title(element.title) .subtitle(element.address) .text(element.description) .buttons([ builder.CardAction.openUrl(session, element.link, element.title) ]); }); reply.attachments(cards); session.send(reply); session.endConversation(); } else { session.endConversation("Lo siento, no pude obtener informacion :("); } } ); // Setup Restify Server const server = restify.createServer(); server.use(restify.plugins.acceptParser(server.acceptable)); server.use(restify.plugins.queryParser()); server.use(restify.plugins.bodyParser()); server.listen(process.env.port || 3978, function () { console.log('%s listening to %s', server.name, server.url); }); server.post('/api/messages', connector.listen());
JavaScript
0.000354
@@ -4615,12 +4615,12 @@ env. -port +PORT %7C%7C
8f655ed45c21b25766878c583d495286fbfaf584
add debug
app.js
app.js
var express = require('express'), path = require('path'), config = require('./config'), async = require('async'), gpio = require('pi-gpio'), app = express(); app.set('port', process.env.PORT || 3001); app.use('/', express.static(__dirname + '/public')); function delayPinWrite(pin, value, callback) { setTimeout(function() { gpio.write(pin, value, callback); }, config.RELAY_TIMEOUT); } app.get("/api/ping", function(req, res) { res.json("pong"); }); app.post("/api/garage/control", function(req, res) { console.log('Control Garage Door'); async.series([ function(callback) { // Open pin for output gpio.open(config.RELAY_PIN, "output", callback); }, function(callback) { // Turn the relay on gpio.write(config.RELAY_PIN, config.RELAY_ON, callback); }, function(callback) { // Turn the relay off after delay to simulate button press delayPinWrite(config.RELAY_PIN, config.RELAY_OFF, callback); }, function(err, results) { setTimeout(function() { // Close pin from further writing gpio.close(config.RELAY_PIN); // Return json res.json("ok"); }, config.RELAY_TIMEOUT); } ]); }); console.log(app.get('port')); app.listen(app.get('port'));
JavaScript
0.000001
@@ -435,16 +435,43 @@ res) %7B%0A +%09console.log('Ping/Pong');%0A %09res.jso
6fd786c529910398c28e7edb9e002b47030341c4
change rule before grow
app.js
app.js
/** * @Author: Paul Joannon * @Date: 2016-04-15T23:45:19+02:00 * @Email: [email protected] * @Last modified by: Paul Joannon * @Last modified time: 2016-04-19T22:32:53+02:00 */ 'use strict'; const express = require('express'); const logger = require('./src/logger'); let app = express(); let roomManager = require('./src/rooms'); app.get('/404', function(req, res) { // Oops, it seems that you're looking for something that doesn't exist. // Link to / res.redirect('/'); }); app.get('/', function(req, res) { // List rooms w/ uptime and population // User can join a room or create a new one res.render('index', { rooms: roomManager.getAll(), now: Date.now() }); }); app.post('/r', function(req, res) { // Create new room let newRoom = roomManager.create(); if (newRoom != null) { res.redirect(`/r/${newRoom.UUID}`); } }); app.get('/r/:ruuid', function(req, res) { const roomUUID = req.params.ruuid; logger.debug(`Trying to access room ${roomUUID}`); // Check if room exists if (roomManager.exists(roomUUID)) { res.render('room', { room : roomManager.get(roomUUID) }); } else { logger.error(`Room ${roomUUID} does not exist`); res.redirect('/404'); } }); app.set('view engine', 'pug'); app.use('/static', express.static('static/')); app.use('/static/lib/socket-io', express.static('node_modules/socket.io-client/', { extensions: ['js'] })); app.use('/static/lib/howler', express.static('node_modules/howler/', { extensions: ['js'] })); app.use('/static/lib/csshake', express.static('node_modules/csshake/dist/', { extensions: ['min.css'] })); app.listen(3000, function() { logger.info('Listening on 0.0.0.0:3000...'); const server = require('http').createServer(app); server.listen(3001); logger.info('Listening on socket 0.0.0.0:3001...'); let io = require('socket.io')(server); io.on('connection', function(sock) { logger.debug('New socket connection') sock.on('register', function(data) { if (roomManager.exists(data.roomUUID)) { let room = roomManager.get(data.roomUUID), member; let mustRegisterMember = function() { logger.debug(`Ask register for ${data.roomUUID}`); if (room.members.count(false, true) >= (room.size[0] * room.size[1]) / 2) { room.grow(); logger.info(`${room.UUID} must grow!`); } return room.registerMember(); }; if (data.memberUUID != null) { logger.debug(`Ask register for ${data.memberUUID}@${data.roomUUID}`); member = room.members.get(data.memberUUID) || room.registerMember(); if (member.dead || Date.now() - member.lastaction >= 30000) { member = mustRegisterMember(); } } else { member = mustRegisterMember(); } member.sock = sock; member.sock.emit('registered', { me: member.getInfo(), }); member.sock.on('startplay', function() { member.sock.emit('startedplay', { room: { members: room.members.getAllInfo(), size: room.size, societyDownLimit: room.societyDownLimit } }); room.members.emit('connected', member.getInfo()); }); member.sock.on('move', function(instruction) { if (room.isCellFree(instruction.x, instruction.y)) { member.move(instruction); room.members.emit('moved', { member: member.UUID, instruction: instruction }); } else { member.sock.emit('nomoved'); } }); member.sock.on('changestate', function(data) { member.state = data.state; member.stateDirection = data.stateDirection; if (member.state <= 0) { member.dead = true; member.sock.emit('gameover', { world: false }); } room.updateScores(member.type.name); room.members.emit('changedstate', { member: member.UUID, state: data.state }); }); member.sock.on('disconnect', function() { logger.debug(`${member.UUID} disconnected`); room.members.emit('disconnected', member.UUID); member.disconnect(); setTimeout(function() { if (room.members.countActives() <= 0) { roomManager.remove(room.UUID); } }, 5000); }); } }); }); });
JavaScript
0
@@ -163,19 +163,19 @@ -04- -19T22:32:53 +20T00:43:00 +02: @@ -2329,32 +2329,64 @@ if ( +(room.size%5B0%5D * room.size%5B1%5D) - room.members.cou @@ -2405,44 +2405,12 @@ ue) -%3E= (room.size%5B0%5D * room.size%5B1%5D) / 2 +%3C= 3 ) %7B%0A
d597481e63afb4c7540af7f9cf9e39b547496cc3
fix negative milliseconds for update
app.js
app.js
var express = require('express'); var exphbs = require('express-handlebars'); var app = express(); var redis = require('redis').createClient(); var moment = require('moment'); const path = require('path'); app.engine('hbs', exphbs({defaultLayout: 'index', extname: '.hbs', layoutsDir: 'views/'})); app.set('view engine', 'hbs'); app.set('port', (process.env.PORT || 3000)); app.get('/', function (req, res) { res.render('index', {name: 'index'}); }); app.get('/:dashboard', function(req, res) { res.render('index', {name: req.params.dashboard, layout: false}); }); app.get('/widgets/:widget.json', function(req, res) { redis.get(req.params.widget, function(err, reply) { if(err) { res.json({'error': err}); } else { var reply_json = JSON.parse(reply); var next_time = moment(reply_json.next_time); delete reply_json.next_time; var now = moment(); if (now.isBefore(next_time)) { reply_json.updates_in_millis = moment.duration(now.diff(next_time)).asMilliseconds(); } else { reply_json.updates_in_millis = 5000; } res.json(reply_json); } }) }); app.listen(app.get('port'), function () { console.log("Up and running on port " + app.get('port')); }); // Serve our bundle if(process.env.NODE_ENV === 'production') { // serve the contents of the build folder app.use("/assets", express.static('build')); } else { // serve using webpack middleware var webpack = require('webpack'); var webpackDevMiddleware = require('webpack-dev-middleware'); var config = require('./webpack.config'); var compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { publicPath: '/assets/', stats: {colors: true} })); } // load our jobs require(__dirname + '/jobs.js');
JavaScript
0.000182
@@ -988,25 +988,25 @@ on(n -ow.diff(next_time +ext_time.diff(now )).a
19eecaa18d9749cfa6d2958b6c58296ec59e2491
resolve #2
app.js
app.js
var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server), colors = require('colors'), mongoose = require('mongoose'), connectCounter = "0"; server.listen(3000); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res) { res.sendfile(__dirname + '/index.html'); }); // Setting vars var currentTime = "" var dayLightStartTime = "" var dayLightEndTime = "" var dayLightState = "" var motionState = "" var motionCountdown = "" var waterlevel = "" function getCurrentTime() { var date = new Date(); var current_hour = date.getHours(); var current_minutes = date.getMinutes(); // console.log(current_minutes); } var five = require("johnny-five"), board, button; board = new five.Board(); board.on("ready", function() { var nightlights = new five.Relay({ pin: 4, type: "NO" }); var daylights = new five.Relay({ pin: 5, type: "NO" }); ping = new five.Ping(9); nightlights.off(); daylights.off(); // "data" get the current reading from the ping ping.on("data", function( err, value ) { // console.log( "data", value ); }); ping.on("change", function( err, value ) { // console.log( "Object is " + this.inches + "inches away" ); waterlevel = this.inches; }); // this.wait(3000, function() { // console.log('Day Lights On'); // daylights.on(); // }); function lightScheduler(){ getCurrentTime(); // if (current_minutes <= 36) { // daylights.on(); // nightlights.on(); // console.log(current_minutes); // }else{ // daylights.off(); // console.log("nightlights only") // }; // if (true) { // nightlights.off(); // }; }; setInterval(lightScheduler, 5000); console.log("boardready"); // Create a new `motion` hardware instance. motion = new five.IR.Motion(8); // Inject the `motion` hardware into // the Repl instance's context; // allows direct command line access this.repl.inject({ motion: motion }); // Pir Event API // "calibrated" occurs once, at the beginning of a session, motion.on("calibrated", function(err, ts) { console.log("calibrated", ts); }); // "motionstart" events are fired when the "calibrated" // proximal area is disrupted, generally by some form of movement motion.on("motionstart", function(err, ts) { console.log("motionstart", ts); nightlights.on(); motionState= "active"; console.log('Night lights trigered'); }); // "motionsend" events are fired following a "motionstart event // when no movement has occurred in X ms motion.on("motionend", function(err, ts) { console.log("no more motion lights off in 1 minute", ts); motionState = "none"; setTimeout(function(){ if (motionState == "none") { console.log('Night Lights Off') nightlights.off(); motionState = "none"; }; }, 1200000); }); // setInterval(function(){ // console.log(motionState) // }, 500); // On first client connection start a new game io.sockets.on('connection', function(socket){ connectCounter++; console.log("connections: "+connectCounter); console.log('New device connected'.green); io.emit('status', 'New device connected!'); socket.on('disconnect', function() { connectCounter--; console.log("connections: "+connectCounter); }); socket.on('status', function(data){ console.log(data); }); socket.on('schedule', function(data){ console.log(data); lightSchedule = data; console.log('start is '+ lightSchedule[0]); console.log('end is '+ lightSchedule[1]); }) socket.on('lights', function(data){ console.log(data); if (data == "day-on") { console.log('data was dayon!!'); daylights.on(); }; if (data == "day-off") { console.log('data was dayon!!'); daylights.off(); }; if (data == "night-on") { console.log('data was dayon!!'); nightlights.on(); daylights.off(); }; if (data == "night-off") { console.log('data was dayon!!'); nightlights.off(); }; }); setInterval(function(){ io.emit('waterlevel', waterlevel); }, 1000); }); //end socket connection });
JavaScript
0.000085
@@ -2718,16 +2718,17 @@ ionState + = %22activ @@ -2727,24 +2727,24 @@ = %22active%22;%0A - cons @@ -3000,16 +3000,17 @@ in -1 +2 minute +s %22, t @@ -3202,46 +3202,8 @@ ();%0A - motionState = %22none%22;%0A @@ -3230,25 +3230,24 @@ , 1200000);%0A -%0A %7D);%0A%0A @@ -3433,25 +3433,16 @@ cket)%7B%0A%0A - %0A @@ -3616,25 +3616,16 @@ ed!');%0A%0A - %0A
6b43d505fd0e0de14a754eabaabe32088b76d585
no favicon
app.js
app.js
var express = require('express'); var http = require('http'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); if(!app.get('env') == 'test') { app.use(logger('dev')); } app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session({ store: new RedisStore({ host: "127.0.0.1", port: 6379, db: 2 }), secret: 'keyboard cat', saveUninitialized: true, resave: true })); require('./passport-config')(app); // initialise all the routes require('./routes')(app); // development error handler if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0.999928
@@ -87,49 +87,8 @@ ');%0A -var favicon = require('static-favicon');%0A var
8d4c465319a91928abbcccf870029315f2ab7eb9
Make it clearer which app has started in logging
app.js
app.js
'use strict'; var express = require( 'express' ); var app = express(); var bodyParser = require( 'body-parser' ); var config = require( './config/config.json' ); for ( var item in config ) { app.set( item, config[ item ] ); } app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: true } ) ); require( './src/api' )( app ); app.listen( app.get( 'port' ), function() { console.log( 'app running on port ' + app.get( 'port' ) + '!' ); } );
JavaScript
0.005752
@@ -411,19 +411,34 @@ e.log( ' -app +enketo-transformer running
be91527e0af231b948bc08ee308c5e4055b9f107
improve message :sparkles:
app.js
app.js
var restify = require('restify'); var builder = require('botbuilder'); var cheerio = require('cheerio'); var request = require('request'); var PDFParser = require('pdf2json'); var textract = require('textract'); //========================================================= // Bot Setup //========================================================= // Setup Restify Server var server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function() { console.log('%s listening to %s', server.name, server.url); }); // Create chat bot var connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); var bot = new builder.UniversalBot(connector); server.post('/api/messages', connector.listen()); var intents = new builder.IntentDialog(); //========================================================= // Bots Dialogs //========================================================= bot.dialog('/', intents); intents.matches(/^rk/i, [ function (session) { menu_rk(function(result) { session.send(result); }); } ]); intents.matches(/^gkk/i, [ function (session) { menu_gkk(function(result) { session.send(result); }); } ]); intents.matches(/^eiserne hand/i, [ function (session) { menu_eisernehand(function(result) { session.send(result); }); } ]); intents.matches(/^all/i, [ function (session) { //TODO maybe reuse other dialogs menu_eisernehand(function(result) { session.send(result); }); menu_gkk(function(result) { session.send(result); }); menu_rk(function(result) { session.send(result); }); } ]); intents.onDefault([ function (session, args, next) { session.send("Hey, I'm a pretty dumb bot. So far I only understand **RK**, **GKK** and **Eiserne Hand**.\n\nTeach me more here: https://github.com/fchtngr/catalysts-lunch-bot"); } ]); //========================================================= //parse the rk menu function menu_rk(callback) { var url = 'http://www.mandis-kantine.at/men1908-23082013'; request(url, function(error, response, html) { var result = "**RK**\n\n"; if (!error) { var day = new Date().getDay(); var row = day + 4; //thats just how their table is laid out var $ = cheerio.load(html); var r = $(`#pagetext > table > tbody > tr:nth-child(${row})`).text().replace(/\r\n\s*/g, '\n').trim(); result += r; } else { result += "Couldn't read todays menu, sorry!" } callback(result) }) } //parse eiserne hand menu function menu_eisernehand(callback) { var url = 'https://manager.yamigoo.com/public/weekly-menu/html/25'; request(url, function(error, response, html) { var result = "**Eiserne Hand**\n\n"; var day = new Date().getDay(); if (day < 1 || day > 5) { result += "No menu today."; callback(result); return; } if (!error) { var $ = cheerio.load(html); var r = $(`#content > div.row > div > div.weeklymenu > div:nth-child(${day})`).text().replace(/\n\s*/g, '\n').trim(); result += r; } callback(result) }) } function menu_gkk(callback) { var url = 'http://www.caseli.at/content/download/1363/6617/file/Speiseplan_O%C3%96_GKK_Hauptstelle.pdf' textract.fromUrl(url, function(error, text) { var result = "**GKK**\n\n" if (error) { result += "Couldnt read todays menu, sorry!" } else { var day = new Date().getDay(); if (day < 1 || day > 5) { result += "No menu today." callback(result); return; } var results = text.split(/(MONTAG|DIENSTAG|MITTWOCH|DONNERSTAG|FREITAG)/) /* 0...empty 1...MONTAG 2...<monday menu> 3...DIENSTAG 4...<tuesday menu> 5...WEDNESDAY 6...<wednesday menu> 7...THURSDAY 8...<thursday menu> 9...FRIDAY 10..<friday menu> Monday -> day==1 --> day+day==2 --> monday menu Tuesday -> day==2 --> day+day==4 --> tuesday menu */ var index = day+day; var menu = results[index].trim().replace(/Classic/g, "\n\nClassic").replace(/^, /g, ""); //console.log(results[index]); callback("**GKK**\n\n" + menu); } callback(result); }) } function menu_lack(callback) { var url = 'http://www.fleischerei-lackinger.at/lackinger/speiseplan/aktuellerspeiseplan'; request(url, function(error, response, html) { if (!error) { //TODO } }) }
JavaScript
0.000001
@@ -1908,16 +1908,27 @@ dumb bot + :innocent: . So far
4df44bce5ac4487ae7af3d69e1a50a7d1cacac51
rename 'svgIcons' option to 'icons'
protoss-config.js
protoss-config.js
module.exports = { templates: { src: './src/**/*.jade', filterFunc: false, inhBaseDir: './src/', dest: './build/', data: {}, prettify: true, hashes: { enabled: true, build_dir: './', src_path: './' }, w3c: { src: './build/*.html' } }, styles: { bundles: [ { name: 'app', src: ['./src/styles/app.scss'], dest: './build/static/css/', minify: true, hashes: true, postcss: false } ], lint: { src: ['./src/styles/**/*.scss'] } }, scripts: { bundles: [ { name: 'app', src: ['./src/scripts/**/*.js'], dest: './build/static/js/', concat: true, minify: true } ], lint: { src: ['./src/scripts/**/*.js'] } }, images: { src: ['./src/resources/images/**/*.{png,jpg,gif,svg}'], dest: './build/images/', minPath: './build/images/' }, spritesPng: { enabled: true, src: './src/sprites/png/', dest: './build/static/images/sprites/', retina: true, stylesName: '_sprites.scss', stylesDest: './src/styles/_global/_sprites/', spritePath: '#{$pathToImages}sprites/', template: __dirname + '/assets/sprite.mustache' }, spritesSvg: { enabled: true, src: './src/sprites/svg/', dest: './build/static/images/sprites-svg/', stylesName: '_sprites-svg.scss', stylesDest: './src/styles/_global/_sprites/', spritePath: '#{$pathToImages}svg-sprites/', template: __dirname + '/assets/sprite-svg.mustache', fallback: false }, svgIcons: { enabled: true, src: './src/icons/', dest: './build/static/images/icons/' }, watch: [ { path: './src/{blocks,pages}/**/*.jade', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/templates' } ] }, { path: './src/{blocks,styles}/**/*.scss', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/styles' } ] }, { path: './src/scripts/**/*.js', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/scripts' } ] }, { path: '**/*.{png,jpg,gif,svg}', config: { cwd: './src/resources/images/', ignoreInitial: true }, on: [ { event: 'add', task: 'protoss/images' }, { event: 'change', task: 'protoss/images' } ] }, { path: './src/sprites/png/**/*.png', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/sprites' } ] }, { path: './src/sprites/svg/**/*.svg', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/sprites-svg' } ] }, { path: './src/icons/**/*.svg', config: { ignoreInitial: true }, on: [ { event: 'all', task: 'protoss/icons' } ] } ], copy: [ ['./src/resources/fonts/**/*', './build/fonts/'] ], del: [ './build' ], favicons: { enabled: true, src: '.src/resources/favicon-master.png', dest: './build/static/favicons/', config: { appName: 'Protoss', background: '#ffffff', path: '/static/favicons/', display: 'standalone', orientation: 'portrait', version: 2.0, logging: false, online: false, html: false, replace: true, icons: { favicons: true, android: true, appleIcon: true, windows: true, appleStartup: false, coast: false, firefox: false, opengraph: false, twitter: false, yandex: false } } }, browserSync: { open: true, port: 9001, server: { directory: true, baseDir: './build/' }, reloadDelay: 200, logConnections: true, debugInfo: true, injectChanges: false, browser: 'default', startPath: '/', ghostMode: { clicks: false, forms: false, scroll: false } } };
JavaScript
0.000047
@@ -1615,12 +1615,9 @@ %0A%0A -svgI +i cons
18dfd7d3090e9c28183f8eab126207d19e5258cb
change credentials
app.js
app.js
// BASE SETUP // ============================================================================= var path = require('http'); var path = require('https'); var path = require('path'); var bodyParser = require('body-parser'); var express = require('express'); var request = require('request'); var app = express(); // define our app using express // configure app to use bodyParser() app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); var port = (process.env.VCAP_APP_PORT || process.env.PORT || 3000); var host = (process.env.VCAP_APP_HOST || process.env.HOST || 'localhost'); var defaultBaseURL = 'https://ibm-watson-ml.mybluemix.net'; var defaultAccessKey = 'bIVJmunsNzKFvCIypDtdch8Vc7cCIf0+b+3zkFFuu280aR4dSem3Pwi6xXuKe0eiHxGxQ3pIogjgEOjN0TGDTcL0h32gVzPkwMbmHXNpi+FQYUqQmv73SQJrb1WXWeZv'; // VCAP_SERVICES contains all the credentials of services bound to // this application. For details of its content, please refer to // the document or sample of each service. var serviceAccess = (url, accessKey) => { let _url = url; let _accessKey = accessKey; return { getBaseUrl: () => { let v1Url = '/pm/v1'; let result = _url.includes(v1Url) ? _url : _url + v1Url if (result.endsWith('/')) { result += '/'; } return result; }, getAccessKey: () => _accessKey, toString: () => `url: ${_url} access_key: ${_accessKey}` } } var serviceEnv = serviceAccess(defaultBaseURL, defaultAccessKey); //{ // "VCAP_SERVICES": { // "pm-20": [ // { // "credentials": { // "access_key": "access key", // "url": "scoring server url" // }, // "label": "pm-20", // "name": "Predictive Modeling-ct", // "plan": "free", // "tags": [ // "business_analytics", // "ibm_created", // "ibm_beta" // ] // } // ] // } //} var services = JSON.parse(process.env.VCAP_SERVICES || "{}"); var pmServiceName = process.env.PA_SERVICE_LABEL ? process.env.PA_SERVICE_LABEL : 'pm-20'; var service = (services[pmServiceName] || "{}"); var credentials = service[0].credentials; if (credentials != null) { serviceEnv = serviceAccess(credentials.url, credentials.access_key); } var rootPath = '/score'; // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // get an instance of the express Router // middleware to use for all requests router.use(function(req, res, next) { next(); // make sure we go to the next routes and don't stop here }); // env request router.get('/', function(req, res) { res.send(serviceEnv.toString()); }); // score request router.post('/', function(req, res) { var scoreURI = serviceEnv.getBaseUrl() + '/score/' + req.body.context + '?accesskey=' + serviceEnv.getAccessKey(); console.log('=== SCORE ==='); console.log(' URI : ' + scoreURI); console.log(' Input: ' + JSON.stringify(req.body.input)); console.log(' '); try { var r = request.post(scoreURI, { json: true, body: req.body.input }); req.pipe(r); r.pipe(res); } catch (e) { console.log('Score exception ' + JSON.stringify(e)); var msg = ''; if (e instanceof String) { msg = e; } else if (e instanceof Object) { msg = JSON.stringify(e); } res.status(200); return res.send(JSON.stringify({ flag: false, message: msg })); } process.on('uncaughtException', function (err) { console.log(err); }); }); // Register Service routes and SPA route --------------- // all of our service routes will be prefixed with rootPath app.use(rootPath, router); // SPA AngularJS application served from the root app.use(express.static(path.join(__dirname, 'public'))); // START THE SERVER with a little port reminder when run on the desktop // ============================================================================= app.listen(port, host); console.log('App started on port ' + port);
JavaScript
0.000001
@@ -654,43 +654,47 @@ = ' -https://ibm-watson-ml.myb +%3Cfrom your service instance on B luemix -.net +%3E ';%0Av @@ -720,136 +720,47 @@ = ' -bIVJmunsNzKFvCIypDtdch8Vc7cCIf0+b+3zkFFuu280aR4dSem3Pwi6xXuKe0eiHxGxQ3pIogjgEOjN0TGDTcL0h32gVzPkwMbmHXNpi+FQYUqQmv73SQJrb1WXWeZv +%3Cfrom your service instance on Bluemix%3E ';%0A%0A
fde9be1018cdf6e5c8105b52632505c80369fe78
Change dev port
app.js
app.js
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); require('colors'); var app = express(); // all environments app.set('port', process.env.PORT || 8080); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hjs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); app.get('/tags', function(req, res) { var clients = getClients(io.sockets.sockets); res.end(JSON.stringify(clients)); }); var server = http.createServer(app); server.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); }); require('./show-addrs').show(app.get('port')); var socketIO = require('socket.io'); var io = socketIO.listen(server); function getClients(roomClients) { var r = []; if (roomClients) { for (var socketId in roomClients) { if (roomClients.hasOwnProperty(socketId)) { var client = roomClients[socketId]; console.log('client, data=', client.store.data); var data; if (client.store.data) { data = client.store.data; } else { data = {}; } data.socketId = socketId; r.push(data); } } } return r; } io.sockets.on('connection', function(socket) { console.log('connection, id=', socket.id); //console.log('connection, sockets=', io.sockets.sockets); var clients = getClients(io.sockets.sockets); socket.emit('user.list', clients); socket.on('disconnect', function() { console.log('user.disconnect'); io.sockets.emit('user.disconnect', { id: socket.id }); }); /** * * @param {Object} * username: {String} * marker { * lat: {Float} * lng: {Float} * } */ socket.on('user.connect', function(userdata) { console.log('user.connect, latlng=', userdata.marker); setData(userdata, function() { io.sockets.emit('user.connect', userdata); }); }); socket.on('user.update', function(userdata) { console.log('user.update'); setData(userdata, function() { io.sockets.emit('user.update', { socketId: socket.id, marker: userdata.marker, username: userdata.username, tags: userdata.tags, }); }); }); function setData(userdata, cb) { var progress = 0; var maxProgress = 0; ['username', 'marker', 'tags'].forEach(function(prop, i) { if (userdata[prop] !== undefined) { maxProgress++; socket.set(prop, userdata[prop], function () { console.log('setData', arguments); progress++; if (maxProgress === progress) { cb(); } }); } }); //socket.set('username', userdata.username, function () { // socket.set('marker', userdata.marker, function () { // socket.set('tags', userdata.tags, function () { // cb(); // }); // }); //}); } });
JavaScript
0.000001
@@ -288,17 +288,17 @@ RT %7C%7C 80 -8 +0 0);%0Aapp.
c83523cb6e7630a6fa429a00f51c059e0986ca8b
add WEB_CONCURRENCY
app.js
app.js
const cluster = require('cluster'); if (cluster.isMaster) { let workerCount = +(process.env.WORKERS || require('os').cpus().length); while (workerCount--) { cluster.fork(); } cluster.on('exit', deadWorker => { let worker = cluster.fork(); console.log(`Worker ${deadWorker.process.pid} replaced by ${worker.process.pid}`); }); } else { console.log(`Starting worker ${process.pid}`); require('./src').start(); }
JavaScript
0.999664
@@ -94,45 +94,27 @@ nv.W -ORKERS %7C%7C require('os').cpus().length +EB_CONCURRENCY %7C%7C 1 );%0A%0A
dd8e15c0f1f81b2ea6fcb54f66c2e8060918ef12
check that door openings happen during the same 'door opening session', even when the order is correct and quiet period has passed.
app.js
app.js
var spawn = require('child_process').spawn; var https = require('https'); var Bacon = require('baconjs'); var _ = require('lodash'); var HOUMIO_SITEKEY = process.env.HOUMIO_SITEKEY; var HOUMIO_SCENEID = process.env.HOUMIO_SCENEID; var OUTER_DOOR_BLE_UUID = process.env.OUTER_DOOR_BLE_UUID; var INNER_DOOR_BLE_UUID = process.env.INNER_DOOR_BLE_UUID; var IS_DEBUG_SCAN = process.env.IS_DEBUG_SCAN && process.env.IS_DEBUG_SCAN === 'on' ? true : false || false; var IS_DEBUG_LOGGING = process.env.IS_DEBUG_LOGGING && process.env.IS_DEBUG_LOGGING === 'on' ? true : false || false; // quiet period separates door opening events from each other. that is needed // as the BLE stickers may report quite many door opening events when a person // enters to appartment. var REQUIRED_QUIET_PERIODS_MS = 15 * 1000; function splitLines(bufferedData) { return Bacon.fromArray(bufferedData.toString('utf-8').split('\n')); } function isNotEmpty(line) { return !_.isEmpty(line); } function toUUID(scanRow) { return scanRow.split(' ')[0]; } function isAmongMonitoredUuids(uuid) { return uuid === OUTER_DOOR_BLE_UUID || uuid === INNER_DOOR_BLE_UUID; } function decorateWithTimestamp(uuid) { return { uuid: uuid, timestamp: Date.now() }; } function isDuplicateDuringSameDoorOpeningSession(quietPeriodMs) { return function(previous, current) { return previous.uuid === current.uuid && current.timestamp - previous.timestamp < REQUIRED_QUIET_PERIODS_MS; } } function hasQuietPeriodPassed(quietPeriodMs) { return function(bleAdMessagesWithTime) { return bleAdMessagesWithTime.current.timestamp - bleAdMessagesWithTime.previous.timestamp >= quietPeriodMs; } } function toHumanReadable(uuidWithTimestamp) { var door = uuidWithTimestamp.uuid === OUTER_DOOR_BLE_UUID ? 'Outer door' : 'Inner door'; return door + ' / ' + (new Date(uuidWithTimestamp.timestamp)); } function debugLog(prefix, mappingFunc) { return function(val) { if (IS_DEBUG_LOGGING) { console.log('[' + prefix + ']', mappingFunc ? mappingFunc(val) : val); } } } function applyScene() { console.log('Entry detected. Applying scene...'); var options = { method: 'PUT', hostname: 'houm.herokuapp.com', path: '/api/site/' + HOUMIO_SITEKEY + '/scene/apply', headers: { 'Content-Type': 'application/json' } }; var req = https.request(options, function(res) { if (res.statusCode === 200) { console.log('Scene applied successfully.') } else { console.log('Applying scene failed. Status code: ' + res.statusCode); } }); req.write(JSON.stringify({ _id: HOUMIO_SCENEID })); req.end(); } var processToSpawn = IS_DEBUG_SCAN ? './ibeacon_scan_debug' : './ibeacon_scan'; console.log('Debug logging: ' + IS_DEBUG_LOGGING); console.log('Debug scan: ' + IS_DEBUG_SCAN); console.log('Turning on BLE device and starting entry detection...'); var beaconScanCmd = spawn(processToSpawn, ['-b']); var allBeaconUuidStream = Bacon.fromEventTarget(beaconScanCmd.stdout, 'data') .flatMap(splitLines) .filter(isNotEmpty) .map(toUUID); allBeaconUuidStream.take(1).onValue(function() { console.log('Entry detection in progress.'); }); var monitoredBeaconUuidAndTimestampStream = allBeaconUuidStream .filter(isAmongMonitoredUuids) .map(decorateWithTimestamp) .doAction(debugLog('ALL MONITORED', toHumanReadable)) .skipDuplicates(isDuplicateDuringSameDoorOpeningSession(REQUIRED_QUIET_PERIODS_MS)) .doAction(debugLog('NO DUPLICATES', toHumanReadable)); var monitoredBeaconUuidAndTimestampWithPreviousStream = monitoredBeaconUuidAndTimestampStream.skip(1) .zip(monitoredBeaconUuidAndTimestampStream, function(current, previous) { return { current: current, previous: previous }; }); var quietPeriodControlStream = Bacon.once(true) .merge(monitoredBeaconUuidAndTimestampWithPreviousStream.map(hasQuietPeriodPassed(REQUIRED_QUIET_PERIODS_MS))) .doAction(debugLog('Quiet period passed')); var applySceneStream = quietPeriodControlStream .zip(monitoredBeaconUuidAndTimestampWithPreviousStream, function(hasQuietPeriodPassed, uuidsAndTimestamps) { return hasQuietPeriodPassed && uuidsAndTimestamps.previous.uuid === OUTER_DOOR_BLE_UUID && uuidsAndTimestamps.current.uuid === INNER_DOOR_BLE_UUID; }) .filter(_.identity); applySceneStream.onValue(applyScene);
JavaScript
0
@@ -1225,24 +1225,179 @@ ow()%0A%09%7D;%0A%7D%0A%0A +function isWithinSameDoorOpeningSession(previous, current, quietPeriodMs) %7B%0A%09return current.timestamp - previous.timestamp %3C REQUIRED_QUIET_PERIODS_MS;%0A%7D%0A%0A function isD @@ -1535,74 +1535,72 @@ && -current.timestamp - previous.timestamp %3C REQUIRED_QUIET_PERIODS_MS +isWithinSameDoorOpeningSession(previous, current, quietPeriodMs) ;%0A%09%7D @@ -4001,52 +4001,8 @@ S))) -%0A%09.doAction(debugLog('Quiet period passed')) ;%0A%0Av @@ -4306,16 +4306,111 @@ BLE_UUID + && %0A%09%09%09isWithinSameDoorOpeningSession(uuidsAndTimestamps.previous, uuidsAndTimestamps.current) ;%0A%09%7D)%0A%09.
14df8e1af0f0789dc63b1d37ce90d1e63359ee4d
add proxy support
app.js
app.js
const _ = require('lodash') const express = require('express') const path = require('path') const favicon = require('serve-favicon') const logger = require('morgan') const cookieParser = require('cookie-parser') const bodyParser = require('body-parser') const proxyMiddleware = require('http-proxy-middleware') // 绑定视图的路由 const apis = require('./views/apis') const site = require('./views/site') // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware const proxyMap = { // '/api/**/*': 'http://localhost:8000' } // 应用根目录 const APP_ROOT = __dirname const app = express() // 视图存放位置和模板引擎 app.set('views', path.join(APP_ROOT, 'templates')) app.set('view engine', 'jade') // 把收藏夹图标放在 /public 目录后注释掉下面这一行 //app.use(favicon(path.join(APP_ROOT, 'public', 'favicon.ico'))) app.use(logger('dev')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use(express.static(path.join(APP_ROOT, 'public'))) // 路由 app.use('/', site) app.use('/api', apis) // proxy api requests _.map(proxyMap, (context, options) => { if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(context, options)) }) // catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error('Not Found') err.status = 404 next(err) }) // 开发环境错误回调 // 输出错误调用栈 if (app.get('env') === 'development') { app.use((err, req, res, next) => { res.status(err.status || 500) res.render('error', { message: err.message, error: err }) }) } // 生产环境错误回调 // 用户看不到错误调用栈 app.use((err, req, res, next) => { res.status(err.status || 500) res.render('error', { message: err.message, error: {} }) }) module.exports = app
JavaScript
0
@@ -698,16 +698,60 @@ ress()%0A%0A +// %E4%BB%A3%E7%90%86%E8%AE%BE%E7%BD%AE%0Aapp.set('trust proxy', 'loopback')%0A%0A // %E8%A7%86%E5%9B%BE%E5%AD%98%E6%94%BE%E4%BD%8D
1a1b71aa9f4db2c349400a19927e95b1b46400b2
fix syntax errors
app.js
app.js
'use strict'; var userName = prompt('Greetings! What is your name?'); console.log(userName + ' started the guessing game!'); alert('Welcome ' + userName + ', glad you\'re here!'); var answer1 = prompt('Do I listen to Avenged Sevenfold?').toLowerCase(); if (answer1 === 'yes' || answer1 === 'y') { console.log(userName + ' answered correctly!'); alert('Surprsingly, correct!'); } else { console.log(userName + ' answered incorrectly!'); alert('Wrongo! Maybe next time.'); } var answer2 = prompt('Do I know how to longboard?').toLowerCase(); if (answer2 === 'yes' || answer2 === 'y') console.log(userName + ' answered correctly!'); alert('Correct! Way to be.'); } else { console.log(userName + ' answered incorrectly!'); alert('Wrong, my friend.'); } var answer3 = prompt('Do I have a cat obsession?').toLowerCase(); if (answer3 === 'yes' || answer3 === 'y') { console.log(userName + ' answered correctly!'); alert('Right you are!'); } else { console.log(userName + ' answered incorrectly!'); alert('Wrongo.'); } var answer4 = prompt('Is my favorite color black? If that is even considered a color...').toLowerCase(); if (answer4 === 'yes' || answer4 === 'y') { console.log(userName + ' answered correctly!'); alert('Right you are! The only color that matches my soul.'); } else { console.log(userName + ' answered incorrectly!'); alert('Incorrect. Haven\'t you seen my clothes?'); } var answer5 = prompt('Do I know how to play the flute?').toLowerCase(); if (answer5 === 'yes' || answer5 === 'y'){ console.log(userName + ' answered correctly!'); alert('Oddly enough, yes! You\'re right. It\'s a gift.'); } else { console.log(userName + ' answered incorrectly!'); alert('Wrong again my friend.'); }
JavaScript
0.000009
@@ -585,16 +585,18 @@ === 'y') + %7B %0A conso
0cc27c29d2a9ed3de77611f6a5e456fcdaf57b7f
support incluse web h5 client
app.js
app.js
var express = require('express'), bodyParser = require('body-parser'), app = express(), port = 3000; var routes = require('./lib/routes'); app.use('/api/', routes.getRouter()); //obsługa JSON z POST app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); var db = require.main.require('./lib/db'); app.db=db; app.listen(port, function () { console.log('REST API app is listening on port %d!', port); });
JavaScript
0
@@ -89,16 +89,82 @@ ress(),%0A + ejs = require('ejs'),%0A favicon = require('serve-favicon'),%0A port @@ -172,16 +172,16 @@ = 3000;%0A - var rout @@ -215,46 +215,9 @@ );%0A%0A -app.use('/api/', routes.getRouter()); %0A + %0A//o @@ -368,16 +368,355 @@ db=db;%0A%0A +app.use('/api/', routes.getRouter());%0A%0Aapp.use(favicon(__dirname + '/h5client/public/favicon.ico'));%0Aapp.set('views', __dirname + '/h5client/');%09%0Aapp.engine('.html', ejs.__express);%0Aapp.set('view engine', 'html');%0Aapp.use('/',function(req, res) %7B%0A if(req.url !== '/favicon.ico')%7B%0A res.render('login', %7B title: 'user login' %7D);%0A %7D%0A%7D);%0A app.list
f4ad5a07e2b25ac2b803e0bab54fbdfe4d3ba6ac
Use the API method available to get a human readbale UA string
app.js
app.js
var express = require('express'); app = express(), polyfills = require('./index'), useragent = require('useragent'), uglify = require('uglify-js'), AliasResolver = require('./aliases'); var aliasResolver = new AliasResolver([ function(polyfill) { var aliases = polyfills.aliases[polyfill.name]; // If aliases exist, expand them adding aliasOf information to // each and tranferring the flags from the alias if (aliases) { return aliases.map(function(alias) { return { name: alias, flags: polyfill.flags, aliasOf: polyfill.name }; }); } return [polyfill]; } ]); app.get(/^\/polyfill(\.\w+)(\.\w+)?/, function(req, res) { var ua = useragent.lookup(req.header('user-agent')); var requestedPolyfills = getRequestPolyfills(req); var readableUAString = ua.family + ' ' + ua.major +'.' + ua.minor + '.' + ua.patch; var minified = req.params[0] === '.min' var extension = req.params[0]; if (minified) { extension = req.params[1]; } var explainerComment = [ req.originalUrl, 'Detected ' + readableUAString ]; var polyFills = []; if (extension === '.js') { res.set('Content-Type', 'application/javascript'); } else { res.set('Conent-Type', 'text/css'); } requestedPolyfills.defaultPolyfills.forEach(function(polyfillInfo) { var polyfill = polyfills.source[polyfillInfo.name]; if (!polyfill) { explainerComment.push(polyfillInfo.name + ' does not match any polyfills'); return; } explainerComment.push(polyfillInfo.name + ' - ' + polyfillInfo.aliasOf + ' (LICENSE TODO)'); polyFills.push(polyfill.file); }); var builtExplainerComment = '/* ' + explainerComment.join('\n * ') + '\n */\n'; var builtPolyfillString = polyFills.join('\n'); if (minified) { builtPolyfillString = uglify.minify(builtPolyfillString, {fromString: true}).code; } res.send(builtExplainerComment + builtPolyfillString); }); app.listen(3000); function getRequestPolyfills(req) { var maybeQuery = req.query.maybe ? req.query.maybe.split(',') : []; var defaultQuery= req.query.default ? req.query.default.split(',') : []; var maybePolyfills = maybeQuery.map(parseQueryString); var defaultPolyfills = defaultQuery.map(parseQueryString); return { maybePolyfills: aliasResolver.resolve(maybePolyfills), defaultPolyfills: aliasResolver.resolve(defaultPolyfills) }; } function parseQueryString(name) { var nameAndFlags = name.split('|'); return { flags: nameAndFlags.slice(1), name: nameAndFlags[0], aliasOf: nameAndFlags[0] }; }
JavaScript
0
@@ -802,93 +802,8 @@ q);%0A -%09var readableUAString = ua.family + ' ' + ua.major +'.' + ua.minor + '.' + ua.patch;%0A %09var @@ -988,24 +988,20 @@ ' + -readableUAString +ua.toAgent() %0A%09%5D;
8533a1856e59bc3334d0b9f4c35415d87bbffc55
use cluster
app.js
app.js
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var img = require('./routes/image'); var upload = require('./routes/upload'); var http = require('http'); var path = require('path'); var config = require("./config"); exports.apppath = __dirname; var fs=require('fs'); var errorLog=fs.createWriteStream(config.errorlog,{flags:'a'}); process.on('uncaughtException', function (err) { errorLog.write('['+new Date+']'+'Caught exception: ' + err); }); var app = express(); // all environments app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.bodyParser({ uploadDir:config.tmproot })); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get(/^\/[0-9a-f]{32}$/, img.read); app.post('/upload', upload.exec); http.createServer(app).listen(config.port, function(){ console.log('server listening:' + config.port); });
JavaScript
0.000002
@@ -1,9 +1,8 @@ -%0A /**%0A * M @@ -267,45 +267,17 @@ );%0A%0A -exports.apppath = __dirname;%0A%0A var fs -= + = requ @@ -299,17 +299,19 @@ errorLog -= + = fs.creat @@ -343,15 +343,17 @@ log, + %7Bflags: + 'a'%7D @@ -431,17 +431,19 @@ ('%5B' -+ + + new Date +'%5D' @@ -442,13 +442,17 @@ Date -+'%5D'+ + + '%5D' + 'Cau @@ -489,47 +489,60 @@ var -app = express();%0A%0A// all environments%0A%0A +start = function () %7B%0A var app = express();%0A%0A app. @@ -573,24 +573,28 @@ '/views');%0A + app.set('vie @@ -613,16 +613,20 @@ jade');%0A + app.use( @@ -646,16 +646,20 @@ arser(%7B%0A + uplo @@ -664,16 +664,17 @@ loadDir: + config.t @@ -684,13 +684,21 @@ oot%0A + %7D));%0A + app. @@ -717,24 +717,28 @@ favicon());%0A + app.use(expr @@ -753,24 +753,28 @@ er('dev'));%0A + app.use(expr @@ -788,24 +788,28 @@ yParser());%0A + app.use(expr @@ -831,16 +831,20 @@ ide());%0A + app.use( @@ -856,16 +856,20 @@ outer);%0A + app.use( @@ -919,16 +919,20 @@ ')));%0A%0A%0A + // devel @@ -943,16 +943,20 @@ nt only%0A + if ('dev @@ -986,16 +986,22 @@ nv')) %7B%0A + app.us @@ -1031,11 +1031,19 @@ ));%0A -%7D%0A%0A + %7D%0A%0A app. @@ -1064,24 +1064,28 @@ s.index);%0A%0A%0A + app.get(/%5E%5C/ @@ -1113,16 +1113,20 @@ ead);%0A%0A%0A + app.post @@ -1152,17 +1152,22 @@ exec);%0A%0A -%0A +%09%0A http.cre @@ -1213,12 +1213,20 @@ tion + () + %7B%0A + co @@ -1271,14 +1271,538 @@ .port);%0A -%7D);%0A%0A + %7D);%0A%7D%0A%0A/******************************************************************%0A * use cluster%0A */%0Avar cpuNums = require('os').cpus().length;%0Avar cluster = require('cluster');%0Avar workers = %7B%7D;%0Aif (cluster.isMaster) %7B%0A cluster.on('death', function (worker) %7B%0A delete workers%5Bworker.pid%5D;%0A worker = cluster.fork();%0A workers%5Bworker.pid%5D = worker;%0A %7D);%0A for (var i = 0; i %3C cpuNums; i++) %7B%0A var worker = cluster.fork();%0A %0A workers%5Bworker.pid%5D = worker;%0A %7D%0A%7D else %7B%0A start();%0A%7D %0A
f6f6c9701fadd84cf7a04a6e34a8d84b115be469
Add decay to distance, add device info to /
app.js
app.js
// ---- // -- Setup // ---- var express = require('express'); var noble = require('noble'); var SpotifyWebApi = require('spotify-web-api-node'); var config = require('./config'); var app = express(); var spotifyApi = new SpotifyWebApi(config.spotify); var assocs = config.assocs; var current = config.default; // ---- // -- Routes // ---- app.get('/cb', function(req, res) { spotifyApi.authorizationCodeGrant(req.query.code).then(function(data) { spotifyApi.setAccessToken(data.body['access_token']); spotifyApi.setRefreshToken(data.body['refresh_token']); noble.startScanning([], true); res.redirect('/'); }, function(err) { console.log('Token error', err); }); }); app.use(function(req, res, next) { if(spotifyApi.getRefreshToken()) { spotifyApi.refreshAccessToken().then(function(data) { spotifyApi.setAccessToken(data.body['access_token']); next(); }, function(err) { console.log('Could not refresh access token', err); next(); }); } else { res.redirect(spotifyApi.createAuthorizeURL(['user-read-playback-state', 'user-modify-playback-state'], 'the-state')); } }); app.get('/', function(req, res) { res.send('home'); }); // ---- // -- Functions // ---- // Returns the rough distance in meters from the beacon var calculateDistance = function(rssi) { var txPower = -59; //hard coded power value. Usually ranges between -59 to -65 if (rssi == 0) { return -1.0; } var ratio = rssi * 1.0 / txPower; if (ratio < 1.0) { return Math.pow(ratio, 10); } else { var distance = (0.89976) * Math.pow(ratio, 7.7095) + 0.111; return distance; } } var calculateNearest = function() { var newHigh = null; for(var uuid in assocs) { console.log(uuid); if(assocs[uuid].proximity < assocs[current].proximity) { newHigh = uuid; } } if(newHigh && newHigh != current) { current = newHigh; spotifyApi.transferMyPlayback({ deviceIds: [assocs[newHigh].spotify], play: true }, function(err) { console.log('transferred', err); }) } }; // Logs info about the beacons var handleDiscover = function(peripheral) { var macAddress = peripheral.uuid; var rssi = peripheral.rssi; var localName = peripheral.localName; /*if(peripheral.advertisement.serviceData.length) { console.log('found device: ', macAddress, ' ', localName, ' ', rssi, ' ', calculateDistance(rssi), ' ', peripheral.advertisement.serviceData[0].data.toString()); console.log(peripheral.advertisement.serviceData[0].data.toString()); }*/ //console.log('found device: ', macAddress, ' ', localName, ' ', rssi, ' ', calculateDistance(rssi)); if(Object.keys(assocs).indexOf(macAddress) > -1) { console.log(macAddress, ' ', localName, ' ', rssi, ' ', calculateDistance(rssi)); assocs[macAddress].proximity = calculateDistance(rssi); calculateNearest(); } }; noble.on('stateChange', function(state) { if (state === 'poweredOn') { //noble.startScanning([], true); } else { noble.stopScanning(); } }); noble.on('discover', handleDiscover); app.listen(8000);
JavaScript
0
@@ -1181,23 +1181,406 @@ %7B%0A -res.send('home' +spotifyApi.getMyDevices().then(function(data) %7B%0A var response = '%3Ctable%3E%3Cthead%3E%3Cth%3EName%3C/th%3E%3Cth%3EType%3C/th%3E%3Cth%3EID%3C/th%3E%3C/thead%3E';%0A for (var i = 0; i %3C data.body.devices.length; i++) %7B%0A response += '%3Ctr%3E%3Ctd%3E' + data.body.devices%5Bi%5D.name + '%3C/td%3E%3Ctd%3E' + data.body.devices%5Bi%5D.type + '%3C/td%3E%3Ctd%3E' + data.body.devices%5Bi%5D.id + '%3C/td%3E';%0A %7D%0A response += '%3C/table%3E';%0A res.send(response);%0A %7D );%0A%7D @@ -2113,32 +2113,126 @@ n assocs) %7B%0A +assocs%5Buuid%5D.proximity = assocs%5Buuid%5D.proximity + 0.1;%0A %7D%0A%0A for(var uuid in assocs) %7B%0A // console.log(uuid @@ -2481,19 +2481,20 @@ play: -tru +fals e%0A %7D,
a6933ce8a013d52dd8dfbbc7fc239a2c2960e625
Remove whitespace
app.js
app.js
'use strict' const express = require('express'); const fs = require('fs'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const logger = require('./utilities/logger'); const httpLog = require('morgan') const path = require('path'); const config = require('./config'); // Start the app const app = express(); // Middlewares app.use(bodyParser.json()); // Http Logging const accessLogStream = fs.createWriteStream(path.join(__dirname,'/log/', config.env +'.log'), {flags: 'a'}); app.use(httpLog('combined', {stream: accessLogStream})); // DB mongoose.connect(config.db_host); // Auth app.use('/', require('./utilities/authentication')); // Mount Routes app.use(require('./routes')); // Listen for requests const port = config.port || process.env.PORT; const server = app.listen(port, () => logger.info("Listening on port " + port)); module.exports = server;
JavaScript
0.999999
@@ -19,29 +19,24 @@ express - = require('e @@ -58,29 +58,24 @@ fs - = require('f @@ -96,21 +96,16 @@ yParser - = requir @@ -139,21 +139,16 @@ goose - = requir @@ -175,29 +175,24 @@ logger - = require('. @@ -225,29 +225,24 @@ httpLog - = require('m @@ -262,29 +262,24 @@ path - = require('p @@ -298,29 +298,24 @@ config - = require('.
0de1ee173c28509b4bfae5c98311391cb747afd6
Double next is bad
app.js
app.js
/* PlanHub https://planhub.me Licensed under the MIT License. */ var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var KnexSessionStore = require('connect-session-knex')(session); var app = express(); var basePath = ""; global.basePath = basePath; var env = "development"; global.env = ((app.get("env") == "production") ? app.get("env") : env); var config = require("./config"); global.mysqlConnection = config.dbConnection; global.knex = require('knex')({ client: 'mysql', connection: global.mysqlConnection, pool: { min: 2, max: 10 } }); global.sessionStore = new KnexSessionStore({ knex: global.knex }); global.isApiPath = function(path) { return path.indexOf("api") > -1; }; global.requireUser = function(req, res, next) { if (req.session.loggedIn) { next(); } else { if (global.isApiPath(req.url)) { res.json({ status: "auth_required", message: "Authentication is required." }); } else { res.redirect(global.basePath + "/login"); } } }; global.getUserRecord = function(req, res, next) { // TODO: error on api pages? global.knex("users").select("*").where({ username: req.session.username }).then(function(obj) { if (obj.length > 1) { res.render("error", { title: "Error", msg: "A database error has occurred, and there is a duplicate user record. Please contact us for assistance." }); return; } if (obj.length == 0) { res.render("error", { title: "Error", msg: "A database error has occurred. Your user record is missing. Please log out and log back in. If you have lost data, please contact us as soon as possible."}); return; } res.locals.user = obj[0]; next(); });/*.catch(fction() { res.render("error", { title: "Error", msg: "A database communication error has occurred. Please try to log out and log back in. If you have lost data, please contact us as soon as possible."}); });*/ }; global.requireViewFeedback = function(req, res, next) { if (res.locals.user.canFeedback != 1) { if (global.isApiPath(req.url)) { res.json({ status: "forbidden", message: "You are not permitted to access this resource." }); } else { res.redirect(global.basePath + "/login"); } } else { next(); } }; global.requireEditAnnouncements = function(req, res, next) { if (res.locals.user.canAnnouncements != 1) { if (global.isApiPath(req.url)) { res.json({ status: "forbidden", message: "You are not permitted to modify this resource." }); } else { res.redirect(global.basePath + "/login"); } } else { next(); } }; global.apiCall = function(req, res, next) { res.locals.apiCall = true; if (req.session.nonces.indexOf(req.param("nonce")) > 0) { req.session.nonces.splice(req.session.nonces.indexOf(req.param("nonce")), 1); next(); } else { /*res.json({ status: "error", error: "The nonce is invalid." });*/ } next(); }; global.getOptionalUserRecord = function(req, res, next) { if (!req.session.loggedIn) { next(); return; } global.knex("users").select("*").where({ username: req.session.username }).then(function(obj) { if (obj.length > 1) { res.render("error", { title: "Error", msg: "A database error has occurred, and there is a duplicate user record. Please contact us for assistance." }); return; } if (obj.length == 0) { res.render("error", { title: "Error", msg: "A database error has occurred. Your user record is missing. Please log out and log back in. If you have lost data, please contact us as soon as possible."}); return; } res.locals.user = obj[0]; next(); }); }; if (!String.prototype.encodeHTML) { String.prototype.encodeHTML = function () { return this.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); }; } // require routes here so they can access globals var routes = require('./routes/index'); var appRouter = require('./routes/app'); var api_main = require('./routes/api_main'); var api_planner = require('./routes/api_planner'); var api_admin = require('./routes/api_admin'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); // sessions var sess = { store: global.sessionStore, secret: 'keyboard cat', cookie: {} }; if (global.env == "production") { sess.cookie.secure = true; // serve secure cookies } app.use(session(sess)); app.use(basePath + '/', express.static(path.join(__dirname, 'public'))); app.use(basePath + '/', routes); app.use(basePath + '/app', appRouter); app.use(basePath + '/api/v1/', api_main); app.use(basePath + '/api/v1/planner', api_planner); app.use(basePath + '/api/v1/admin', api_admin); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { //res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0.999997
@@ -2956,24 +2956,26 @@ e%22)), 1);%0A%09%09 +// next();%0A%09%7D e
712a93a0465151e3af78d88a04c247786081035a
Use config-d host & port
app.js
app.js
var express = require('express'); var session = require('cookie-session') var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var config = require('./config/config.js'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'untapdlulz', secureProxy : false })); app.locals.config = config; app.use(require('less-middleware')(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', require('./routes/index')); app.use('/oauth', require('./routes/oauth')); app.use('/match', require('./routes/match')); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { console.log('Express server listening on port ' + server.address().port); }); module.exports = app;
JavaScript
0
@@ -1722,32 +1722,19 @@ t', -process.env.PORT %7C%7C 3000 +config.port );%0A%0A @@ -1773,16 +1773,29 @@ 'port'), + config.host, functio
09d6583e0db577a9875f9199f82db518e8b00a4c
Change app.js
app.js
app.js
"use strict"; // Load configuration and initialize server var anyfetchProvider = require('anyfetch-provider'); var serverConfig = require('./lib/'); var server = anyfetchProvider.createServer(serverConfig.connectFunctions, serverConfig.updateAccount, serverConfig.workers, serverConfig.config); // Expose the server module.exports = server;
JavaScript
0.000003
@@ -222,56 +222,67 @@ ns, -serverConfig.updateAccount, serverConfig.workers +__dirname + '/lib/workers.js', __dirname + '/lib/update.js' , se
21d5e584f1e8f9c975efdcb34fda205a1572fe0a
add keys, comments, passport, routes // databaseurl
app.js
app.js
var express = require('express'), app = express(), mongoose = require('mongoose'), bodyParser = require('body-parser'), methodOverride = require('method-override'), flash = require('connect-flash') var url = process.env.DATABASEURL || 'http://localhost/keys-to-teach' mongoose.connect(url); app.set('view engine', 'ejs'); app.use(express.static(__dirname + '/public')); app.use(methodOverride('_method')); app.use(bodyParser.urlencoded({ extended: true })); app.use(require('express-session')({ secret: 'Keys to teach session', resave: false, saveUninitialized: false })); app.use(flash()); // app.use(passport.initialize()); // app.use(passport.session()); // passport.use(new LocalStrategy(User.authenticate())); // passport.serializeUser(User.serializeUser()); // passport.deserializeUser(User.deserializeUser()); app.use(function(req, res, next) { res.locals.error = req.flash('error'); res.locals.success = req.flash('success'); next(); }); var indexRoutes = require('./routes/index') app.use('/', indexRoutes); var PORT = 8080; app.listen(process.env.PORT || PORT, process.env.IP, function() { console.log('Keys to Learn server started'); })
JavaScript
0
@@ -133,160 +133,515 @@ -methodOverride = require('method-override'),%0A flash = require('connect-flash')%0A%0Avar url = process.env.DATABASEURL %7C%7C 'http://localhost/keys-to-teach' +passport = require('passport'),%0A LocalStrategy = require('passport-local'),%0A methodOverride = require('method-override'),%0A Key = require('./models/keys'),%0A Comment = require('./models/comments'),%0A User = require('./models/users'),%0A methodOverride = require('method-override'),%0A flash = require('connect-flash')%0A%0Avar commentRoutes = require('./routes/comments'),%0A keysRoutes = require('./routes/keys'),%0A indexRoutes = require('./routes/index');%0A%0Amongoose.promise = global.Promise;%0A %0A%0Amo @@ -980,19 +980,16 @@ sh());%0A%0A -// app.use( @@ -1012,19 +1012,16 @@ ize());%0A -// app.use( @@ -1037,27 +1037,24 @@ session());%0A -// passport.use @@ -1091,27 +1091,24 @@ ticate()));%0A -// passport.ser @@ -1145,11 +1145,8 @@ ));%0A -// pass @@ -1188,24 +1188,305 @@ zeUser());%0A%0A +app.use(function(req, res, next) %7B%0A res.locals.currentUser = req.user;%0A res.locals.error = req.flash('error');%0A res.locals.success = req.flash('success');%0A next();%0A%7D);%0A%0Aapp.use(indexRoutes);%0Aapp.use('/keys', keysRoutes);%0Aapp.use('/keys/:id/comments', commentRoutes);%0A%0A%0A app.use(func
5566698c36fe521eface725eeb0cf8dd705c5aa7
Refactor readdir/readdfile
app.js
app.js
// Globals for now.. var userPrompt = 'guest@title:/$ '; var path = '/'; function getChar(event) { return String.fromCharCode(event.keyCode || event.charCode); } function newline(element, text) { var p = document.createElement('p'); p.innerText = text; element.appendChild(p); } function readfile(file, callback) { fetch(file, { method: 'get' }).then(function(response) { if (response.status === 200) { return response.text(); } else { return ''; } }).then(function(content) { callback(content); }); } function readdir(directory, callback) { fetch(directory, {method: 'get'}).then(function(response) { if (response.status === 200) { return response.text(); } else { return ''; } }, function(resp) { console.log('failed'); }).then(function(content) { var elements = []; if (content !== '') { parser = new DOMParser(); htmlDoc = parser.parseFromString(content, 'text/html'); var text = ''; elements = htmlDoc.getElementsByTagName('a'); } callback(elements); }, function(content) { console.log('failed'); }); } function executeCommand(display, cmdstr) { // Handle null string case. if (cmdstr.length === 0) { newline(display, ''); return; } var arg = ''; var args = cmdstr.split('\u00A0'); // TODO: handle multiple arguments? if (args.length >= 2) { arg = args[1]; } var cmd = args[0]; switch (cmd) { case 'cat': var file = window.location.origin + path + arg; readfile(file, function(text) { if (text === '') { newline(display, 'cat: \'' + arg + '\': No such file or directory'); } else { newline(display, text); } }); break; case 'clear': while (display.hasChildNodes()) { display.removeChild(display.childNodes[0]); } break; case 'echo': newline(display, arg); break; case 'ls': var dir = window.location.origin + path + arg; var text = ''; readdir(dir, function(files) { for (var i = 0; i < files.length; i++) { text += ' ' + files[i].innerText; } if (text === '') { newline(display, 'ls: cannot access \'' + arg + '\': No such file or directory'); } else { newline(display, text); } }); break; case 'pwd': newline(display, path); break; default: newline(display, '-shelljs: ' + cmd + ': command not found'); break; } } document.addEventListener('DOMContentLoaded', function() { // FIXME: those globals.. var cursor = document.getElementById('cursor'); var display = document.getElementById('display'); var text = document.getElementById('text'); setInterval(function() { if (cursor.className) { cursor.className = ''; } else { cursor.className = 'cursor-on'; } }, 800); document.onkeydown = function(event) { switch (event.keyCode) { // Backspace case 8: event.preventDefault(); if (text.innerText.length > 0) { text.innerText = text.innerText.slice(0, -1); } break; // Tab case 9: event.preventDefault(); break; } }; document.onkeypress = function(event) { // FIXME: when inserting text, disable cursor blinking.. switch (event.keyCode) { // Enter case 13: var p = document.createElement('p'); p.innerText = userPrompt + text.innerText; display.appendChild(p); executeCommand(display, text.innerText); text.innerText = ''; break; // Space case 32: text.innerText += '\u00A0'; break; default: var character = getChar(event || window.event); // Any other special key if (character) { text.innerText += character; } } cursor.scrollIntoView({block: 'end', behavior: 'smooth'}); }; });
JavaScript
0
@@ -543,589 +543,8 @@ %0A%7D%0A%0A -function readdir(directory, callback) %7B%0A fetch(directory, %7Bmethod: 'get'%7D).then(function(response) %7B%0A if (response.status === 200) %7B%0A return response.text();%0A %7D else %7B%0A return '';%0A %7D%0A %7D, function(resp) %7B console.log('failed'); %7D).then(function(content) %7B%0A var elements = %5B%5D;%0A%0A if (content !== '') %7B%0A parser = new DOMParser();%0A htmlDoc = parser.parseFromString(content, 'text/html');%0A%0A var text = '';%0A elements = htmlDoc.getElementsByTagName('a');%0A %7D%0A%0A callback(elements);%0A %7D, function(content) %7B console.log('failed'); %7D);%0A%0A%7D%0A%0A func @@ -1412,16 +1412,92 @@ + arg;%0A +%0A readfile(dir, function(content) %7B%0A%0A if (content !== '') %7B%0A va @@ -1513,46 +1513,173 @@ '';%0A -%0A + -readdir(dir, function(files) %7B%0A +parser = new DOMParser();%0A htmlDoc = parser.parseFromString(content, 'text/html');%0A%0A var elements = htmlDoc.getElementsByTagName('a');%0A @@ -1702,20 +1702,23 @@ 0; i %3C -file +element s.length @@ -1732,24 +1732,26 @@ %7B%0A + text += ' ' @@ -1752,20 +1752,23 @@ = ' ' + -file +element s%5Bi%5D.inn @@ -1779,24 +1779,26 @@ xt;%0A + %7D%0A%0A i @@ -1796,32 +1796,56 @@ -if (text === '') + newline(display, text);%0A %7D else %7B%0A @@ -1935,59 +1935,8 @@ ');%0A - %7D else %7B%0A newline(display, text);%0A
1ac76d45e70cd623a80c0b73666bb8d78c07c1cf
use PORT env variable with 1234 as a fallback
app.js
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var MongoClient = require('mongodb').MongoClient; var handlebars = require('express-handlebars'); var nconf = require('nconf'); var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('hbs', handlebars({ extname: 'hbs', defaultLayout: 'layout.hbs' })); app.set('view engine', 'hbs'); // helpers for the handlebars templating platform handlebars = handlebars.create({ helpers: { toJSON : function(object) { return JSON.stringify(object); }, niceBool : function(object) { if(object === undefined){ return "No"; } if(object === true){ return "Yes"; }else{ return "No"; } }, formatBytes : function(bytes) { if(bytes == 0) return '0 Byte'; var k = 1000; var decimals = 2; var dm = decimals + 1 || 3; var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; var i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i]; } } }); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json({limit: '16mb'})); app.use(bodyParser.urlencoded({extended: false })); app.use(cookieParser()); // front-end modules loaded from NPM app.use("/ace", express.static(path.join(__dirname, 'node_modules/ace-builds/src-min/'))); app.use("/font-awesome", express.static(path.join(__dirname, 'node_modules/font-awesome/'))); app.use("/jquery", express.static(path.join(__dirname, 'node_modules/jquery/dist/'))); app.use("/bootstrap", express.static(path.join(__dirname, 'node_modules/bootstrap/dist/'))); app.use(express.static(path.join(__dirname, 'public'))); // setup nconf to read in the file // create config dir and blank files if they dont exist var fs = require('fs'); if (!fs.existsSync("config")){ fs.mkdirSync("config"); } if (!fs.existsSync("config/config.json")){ fs.writeFileSync("config/config.json", "{}"); } if (!fs.existsSync("config/app.json")){ fs.writeFileSync("config/app.json", "{}"); } var connection_config = path.join(__dirname, 'config', 'config.json'); var app_config = path.join(__dirname, 'config', 'app.json'); // if config files exist but are blank we write blank files for nconf if (fs.existsSync(app_config, "utf8")) { if(fs.readFileSync(app_config, "utf8") == ""){ fs.writeFileSync(app_config, "{}", 'utf8'); } } if (fs.existsSync(connection_config, "utf8")) { if(fs.readFileSync(connection_config, "utf8") == ""){ fs.writeFileSync(connection_config, "{}", 'utf8'); } } // setup the two conf. 'app' holds application config, and connections // holds the mongoDB connections nconf.add('connections', { type: 'file', file: connection_config }); nconf.add('app', { type: 'file', file: app_config }); // set app defaults var app_host = '0.0.0.0'; var app_port = 1234; // get the app configs and override if present if(nconf.stores.app.get('app:host') != undefined){ app_host = nconf.stores.app.get('app:host'); } if(nconf.stores.app.get('app:port') != undefined){ app_port = nconf.stores.app.get('app:port'); } // Make stuff accessible to our router app.use(function (req, res, next) { req.nconf = nconf.stores; req.handlebars = handlebars; next(); }); app.use('/', routes); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); // lift the app app.listen(app_port, app_host, function () { console.log('adminMongo listening on host: http://' + app_host + ':' + app_port); }); module.exports = app;
JavaScript
0
@@ -3304,16 +3304,36 @@ p_port = + process.env.PORT %7C%7C 1234;%0A%0A
332d93bf9d43e68c0b3f08590b2d52087a8eba6b
fix misled log
app.js
app.js
'use strict'; // Include dependencies var log = require('npmlog'); var express = require('express'); var http = require('http'); var config = require('./config/environment'); var mongoose = require('mongoose'); // connect to mongo mongoose.connect('mongodb://localhost/test'); // create app object var app = express(); // Set configurations for server require('./config/express')(app); // Set routes for server require('./routes')(app); // Create server object var server = http.createServer(app) // Start server function startServer() { server.listen(config.port, config.ip, function() { log.info('Express', 'Listening on port %s', app.get('port')); // console.log('Express server listening on %d, in %s mode', config.port, app.get('env')); }); } if (process.env.NODE_ENV === 'dev') { setImmediate(startServer); }; // Expose app exports = module.exports = app;
JavaScript
0.000001
@@ -594,12 +594,10 @@ ) %7B%0A - +%09%09 log. @@ -613,78 +613,8 @@ ress -', 'Listening on port %25s', app.get('port'));%0A%09%09// console.log('Express ser
4e21e761ad2609c101ff94444e0a03d7668e1539
Remove flash messages view helper
app.js
app.js
/** * Module dependencies. */ var express = require('express'); var flash = require('express-flash'); var less = require('less-middleware'); var path = require('path'); var mongoose = require('mongoose'); var passport = require('passport'); var expressValidator = require('express-validator'); /** * Load controllers. */ var homeController = require('./controllers/home'); var userController = require('./controllers/user'); var apiController = require('./controllers/api'); var contactController = require('./controllers/contact'); /** * API keys + Passport configuration. */ var secrets = require('./config/secrets'); var passportConf = require('./config/passport'); /** * Mongoose configuration. */ mongoose.connect(secrets.db); mongoose.connection.on('error', function() { console.log('✗ MongoDB Connection Error. Please make sure MongoDB is running.'.red); setTimeout(function() { mongoose.connect(secrets.db); }, 5000); }); var app = express(); /** * Express configuration. */ app.locals.cacheBuster = Date.now(); app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.compress()); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.cookieParser()); app.use(express.json()); app.use(express.urlencoded()); app.use(expressValidator()); app.use(express.methodOverride()); app.use(express.session({ secret: 'your secret code' })); app.use(passport.initialize()); app.use(passport.session()); app.use(function(req, res, next) { res.locals.user = req.user; next(); }); app.use(flash()); app.use(function(req, res, next) { res.locals.flash = req.flash.bind(req); next(); }); app.use(less({ src: __dirname + '/public', compress: true })); app.use(app.router); app.use(express.static( path.join(__dirname, 'public'), { maxAge: 864000000 } )); app.use(function(req, res) { res.render('404', { status: 404 }); }); app.use(express.errorHandler()); /** * Application routes. */ app.get('/', homeController.index); app.get('/login', userController.getLogin); app.post('/login', userController.postLogin); app.get('/logout', userController.logout); app.get('/signup', userController.getSignup); app.post('/signup', userController.postSignup); app.get('/contact', contactController.getContact); app.post('/contact', contactController.postContact); app.get('/account', passportConf.isAuthenticated, userController.getAccount); app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile); app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword); app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount); app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink); app.get('/api', apiController.getApi); app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare); app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr); app.get('/api/facebook', passportConf.isAuthenticated, apiController.getFacebook); app.get('/api/scraping', apiController.getScraping); app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub); app.get('/api/lastfm', apiController.getLastfm); app.get('/api/nyt', apiController.getNewYorkTimes); app.get('/api/twitter', passportConf.isAuthenticated, apiController.getTwitter); app.get('/api/aviary', apiController.getAviary); app.get('/api/paypal', apiController.getPayPal); app.get('/api/paypal/success', apiController.getPayPalSuccess); app.get('/api/paypal/cancel', apiController.getPayPalCancel); app.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' })); app.get('/auth/github', passport.authenticate('github')); app.get('/auth/github/callback', passport.authenticate('github', { successRedirect: '/', failureRedirect: '/login' })); app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' })); app.get('/auth/google/callback', passport.authenticate('google', { successRedirect: '/', failureRedirect: '/login' })); app.get('/auth/twitter', passport.authenticate('twitter')); app.get('/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' })); app.get('/auth/foursquare', passport.authorize('foursquare')); app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) { res.redirect('/api/foursquare'); }); app.get('/auth/tumblr', passport.authorize('tumblr')); app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) { res.redirect('/api/tumblr'); }); app.listen(app.get('port'), function() { console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0
@@ -1629,99 +1629,8 @@ ));%0A -app.use(function(req, res, next) %7B%0A res.locals.flash = req.flash.bind(req);%0A next();%0A%7D);%0A app.
dcc6bce02285e71e5ebe27b1eafb00b237a67c49
Use deprecated parameter for now.
app.js
app.js
var express = require('express'); var path = require('path'); var fs = require('fs'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var session = require('express-session'); var validator = require('express-validator'); var flash = require('connect-flash'); var passport = require('passport'); var configuration = require('./config/config.js'); var md5 = require('MD5'); var RedisStore = require('connect-redis')(session); var app = express(); mongoose.connect(configuration.mongoUri); var db = mongoose.connection; db.on('error', function(err) { console.log(err); process.exit(1); }); db.once('open', function callback() { console.log('Connected to DB'); }); require('./config/passport')(passport); // pass passport for configuration // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(favicon()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(validator()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session( { secret: configuration.COOKIE_KEY, //cookie: { domain:'.statik.io', path: '/' }, store: new RedisStore(require('redis-url').connect(configuration.redisUri)) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use(function(req, res, next) { res.locals.user = req.user; res.locals.error = req.flash('error'); res.locals.success = req.flash('success'); if (req.user != undefined && req.user.selectedEmail != undefined) { res.locals.gravatar = 'http://www.gravatar.com/avatar/' +md5(req.user.selectedEmail); } else { res.locals.gravatar = 'http://www.gravatar.com/avatar/00000000000000000'; } next(); }); // Log to file if required var log = process.env.LOG || false; if (log) { var logFile = fs.createWriteStream(log, {flags: 'w'}); app.use(logger('dev', ({stream: logFile}))); console.log("Using " + log + " for logging"); } else { app.use(logger('dev')); console.log("Using stdout for logging"); } //CSP app.get('/*',function(req, res, next) { var csp = "default-src 'none'; script-src 'self' data: cdnjs.cloudflare.com cdn.jsdelivr.net; object-src 'self'; style-src 'self' cdnjs.cloudflare.com maxcdn.bootstrapcdn.com fonts.googleapis.com 'unsafe-inline'; img-src 'self'; media-src 'self'; frame-src 'self'; font-src 'self' cdnjs.cloudflare.com maxcdn.bootstrapcdn.com fonts.googleapis.com fonts.gstatic.com; connect-src 'self'"; res.header('Content-Security-Policy' , csp); next(); }); //We load the routes app.use('/', require('./routes/index')); app.use('/users', require('./routes/users')); app.use('/plugins', require('./routes/plugin')); app.use('/ucp', require('./routes/ucp')); /// catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); app.locals.pretty = true; } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0
@@ -891,17 +891,16 @@ ration%0A%0A -%0A // view @@ -1317,37 +1317,14 @@ ore( -require('redis-url').connect( +%7Burl: conf @@ -1341,17 +1341,17 @@ redisUri -) +%7D )%0A%7D));%0A%0A
9033f2ea01b12e3337aa0817f9be4706cf6b162c
Move var declaration to top of function
app.js
app.js
var config = require('./config'), httpServer, express = require('express'), partials = require('express-partials'), authManager = require('./lib/authentication'), passport = authManager.passport, socketAuthenticator = require('./lib/socket-auth'), refresh = require('./lib/refresh.js'), pullManager = require('./lib/pull-manager'), dbManager = require('./lib/db-manager'), pullQueue = require('./lib/pull-queue'), mainController = require('./controllers/main'), hooksController = require('./controllers/githubHooks'), reqLogger = require('debug')('pulldasher:server:request'), debug = require('debug')('pulldasher'); var app = express(); httpServer = require('http').createServer(app); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); /** * Middleware */ app.use("/public", express.static(__dirname + '/public')); app.use("/spec", express.static(__dirname + '/views/current/spec')); app.use("/css", express.static(__dirname + '/views/current/css')); app.use("/html", express.static(__dirname + '/views/current/html')); app.use("/fonts", express.static(__dirname + '/bower_components/font-awesome/fonts')); app.use("/lib", express.static(__dirname + '/bower_components')); app.use(partials()); app.use(express.urlencoded()); app.use(express.json()); app.use(express.cookieParser()); app.use(express.session({secret: config.session.secret})); app.use(passport.initialize()); app.use(passport.session()); app.use(function(req, res, next) { reqLogger("%s %s", req.method, req.url); next(); }); /** * Routes */ authManager.setupRoutes(app); app.get('/', mainController.index); app.post('/hooks/main', hooksController.main); // Load open pulls from the DB so we don't start blank. dbManager.getOpenPulls(config.repo.name).then(function(pulls) { pullQueue.pause(); pulls.forEach(function(pull) { pullManager.updatePull(pull); }); pullQueue.resume(); }) // Get the most recent version of each pull from the API .then(function () { return refresh.openPulls(); }).done(); /* @TODO: Update pulls which were open last time Pulldasher ran but are closed now. dbManager.closeStalePulls(); */ //==================================================== // Socket.IO var io = require('socket.io').listen(httpServer); io.sockets.on('connection', function (socket) { socket.on('authenticate', function(token) { // They did respond. No need to drop their connection for not responding. clearTimeout(autoDisconnect); var user = socketAuthenticator.retrieveUser(token); if (user) { socket.emit('authenticated'); pullManager.addSocket(socket); } else { socket.emit('unauthenticated'); socket.disconnect(); } }); socket.on('refresh', function(number) { refresh.pull(number); }); var unauthenticated_timeout = config.unauthenticated_timeout !== undefined ? config.unauthenticated_timeout : 10 * 1000; var autoDisconnect = setTimeout(function() { socket.disconnect(); }, unauthenticated_timeout); }); debug("Listening on port %s", config.port); httpServer.listen(config.port);
JavaScript
0
@@ -2378,16 +2378,255 @@ cket) %7B%0A + var unauthenticated_timeout = config.unauthenticated_timeout !== undefined ?%0A config.unauthenticated_timeout : 10 * 1000;%0A%0A var autoDisconnect = setTimeout(function() %7B%0A socket.disconnect();%0A %7D, unauthenticated_timeout);%0A%0A socke @@ -3119,247 +3119,8 @@ %7D); -%0A%0A var unauthenticated_timeout = config.unauthenticated_timeout !== undefined ?%0A config.unauthenticated_timeout : 10 * 1000;%0A%0A var autoDisconnect = setTimeout(function() %7B%0A socket.disconnect();%0A %7D, unauthenticated_timeout); %0A%7D);
85f0c5030398578e207eaba93e64614e0b1cc306
drop too many connexions
app.js
app.js
var Twit = require('twit'); var express = require('express'); var http = require('http'); var ws = require('ws'); var app = express(); var S = { PORT: 80, IP: "195.154.48.49" }; var version = Math.round(Math.random()*65535).toString(16); console.log("Version:", version); var T = new Twit({ consumer_key: 'zgIdJmHhhEdyk66dzMDvj7vo9' , consumer_secret: 'NJbfbSYPT9FZyvpreAKZP3G5CXwliLW053PpYNRmhQA5EgMW07' , access_token: '61424983-UtOSpYipe4cnetiB8akMJ1C4daeqO9mvaxRrxyRqb' , access_token_secret: '7BD0cPgcv7rsMNAJvp5GKOOqWzpE5aHc1lQG8PnCAui4M' }); var clients = []; var stream = T.stream('statuses/filter', { track: [ '#PJLRenseignement', "#LoiRenseignement", 'terrorisme', 'liberté', 'vie privé', "droits de l'homme"] }); stream.on('tweet', function (tweet) { //console.log(tweet); clients.forEach(function(client) { var data = JSON.stringify({ name:tweet.user.name, screen_name: tweet.user.screen_name, text:tweet.text, id_str: tweet.id_str, img: tweet.user.profile_image_url, url: "https://twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str}); try { client.send(data); } catch(e) { console.log(e); } }); }) app.use("/pub", express.static(__dirname + '/pub')); app.get("/", function(req, res) { res.sendfile('./pub/index.html'); }); if (process.getuid() !== 0) { S.PORT *= 100; S.IP = ""; } var server = http.createServer(app); server.listen(S.PORT, S.IP, function() { if (process.getuid() === 0) { process.setgid(1000); process.setuid(1000); if (process.getuid() !== 0) { console.log("no root anymore..."); } } console.log("Listening on", S.PORT, S.IP); }); var max = 0; function log() { max = Math.max(max, clients.length); var txt = "["+clients.length+"/"+max+"] "; for (e in arguments) { txt += arguments[e] + " "; } console.log(txt); } var wss = new ws.Server({server: server}); wss.on('connection', function(client) { clients.push(client); var ip = client._socket.remoteAddress; log("new client connected from", ip); client.send(JSON.stringify({ version: version })); client.on("message", function(data) { var j = JSON.parse(data); for(var i=0; i < j.name.length; i++) { var l = j.name[i]; if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-.0123456789".indexOf(l) === -1) { console.log("name invalid"); return } } log(data); clients.forEach(function(c) { if (c !== client) { try { c.send(data); } catch(e) { console.log(e); } } }); }); client.on("close", function() { var id = clients.indexOf(client); clients.splice(id, 1); log("client", id, "disconnected from", ip); }); });
JavaScript
0.000001
@@ -606,16 +606,31 @@ = %5B%5D;%0A%0A +var ips = %7B%7D;%0A%0A var stre @@ -2268,16 +2268,308 @@ ddress;%0A +%0A if (ip) %7B%0A if (ips%5Bip%5D) %7B%0A ips%5Bip%5D++;%0A if (ips%5Bip%5D %3E 20) %7B%0A var id = clients.indexOf(client);%0A clients.splice(id, 1);%0A client.close();%0A log(%22client rejected, too many connexions%22);%0A return;%0A %7D%0A %7D else %7B%0A ips%5Bip%5D = 1;%0A %7D%0A %7D%0A%0A log(%22n @@ -3224,24 +3224,62 @@ Of(client);%0A + if (ip) %7B%0A ips%5Bip%5D--;%0A %7D%0A%0A clients.
5d826f26642d2f8127d959e88da5f146abfa5c59
Add test console.log
app.js
app.js
var http = require('http'); var https = require('https'); var path = require('path'); var fs = require('fs'); var gitHubWebhookHandler = require('github-webhook-handler'); var settings = {}; settings.hooks = [{name: '/gitHubPuller', localPath: '/var/www/gitHubPuller'}]; for (var i = 0; i < settings.hooks.length; i++) { var localPath = settings.hooks[i].localPath, handler = gitHubWebhookHandler({ path: settings.hooks[i].name, secret: 'lorcanvida' }); handler.on('push', function (event) { var added = event.payload.head_commit.added, removed = event.payload.head_commit.removed, modified = event.payload.head_commit.modified, remotePath = event.payload.head_commit.url, j; for (j = 0; j < modified.length; j++) { https.get(remotePath + '/' + modified[j], function(res) { fs.write(path.join(localPath, modified[j]), res.body, function(err) { if (err) { errorHandler(err, 'push2'); return; } }); }) .on('error', function(err) { if (err) { errorHandler(err, 'push1'); return; } }); } console.log('Received a push event for %s to %s', event.payload.repository.name, event.payload.ref); /// get https://github.com/seethespark/i-flicks/archive/master.zip }); handler.on('error', function (err) { console.error('Error:', err.message); }); settings.hooks[i].handler = handler; } http.createServer(function (req, res) { for (var i = 0; i < settings.hooks.length; i++) { if (req.url === settings.hooks[i].name) { settings.hooks[i].handler(req, res); return; } } res.statusCode = 404; res.end('no such location'); }).listen(7777); function errorHandler(err, location, res) { var message = err; if (err.message) { message = err.message; } console.log('Error at ', location, '.', 'Message: ', message); if (res) { res.status(500); res.end(); } } /* gitHubPullerHandler.on('issues', function (event) { console.log('Received an issue event for %s action=%s: #%d %s', event.payload.repository.name, event.payload.action, event.payload.issue.number, event.payload.issue.title); });*/
JavaScript
0.000002
@@ -744,16 +744,48 @@ j;%0A + console.log(localPath);%0A @@ -820,24 +820,62 @@ gth; j++) %7B%0A + console.log(modified%5Bj%5D);%0A