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
6838eaf66b94445e314f087ec407d7e2b5bf1fb5
remove cruft from wallaby config
.wallaby.js
.wallaby.js
'use strict'; module.exports = () => { return { files: [ 'index.js', 'lib/**/*.{js,json}', 'test/setup.js', 'test/assertions.js', { pattern: 'test/node-unit/**/*.fixture.js', instrument: false }, { pattern: 'test/unit/**/*.fixture.js', instrument: false }, 'package.json', 'test/opts/mocha.opts', 'mocharc.yml' ], filesWithNoCoverageCalculated: [ 'test/**/*.fixture.js', 'test/setup.js', 'test/assertions.js', 'lib/browser/**/*.js' ], tests: ['test/unit/**/*.spec.js', 'test/node-unit/**/*.spec.js'], env: { type: 'node', runner: 'node' }, workers: {recycle: true}, testFramework: {type: 'mocha', path: __dirname}, setup(wallaby) { // running mocha instance is not the same as mocha under test, // running mocha is the project's source code mocha, mocha under test is instrumented version of the source code const runningMocha = wallaby.testFramework; runningMocha.timeout(200); // to expose it/describe etc. on the mocha under test const MochaUnderTest = require('./'); const mochaUnderTest = new MochaUnderTest(); mochaUnderTest.suite.emit( MochaUnderTest.Suite.constants.EVENT_FILE_PRE_REQUIRE, global, '', mochaUnderTest ); // to make test/node-unit/color.spec.js pass, we need to run mocha in the project's folder context const childProcess = require('child_process'); const execFile = childProcess.execFile; childProcess.execFile = function() { let opts = arguments[2]; if (typeof opts === 'function') { opts = {}; Array.prototype.splice.call(arguments, 2, 0, opts); } opts.cwd = wallaby.localProjectDir; return execFile.apply(this, arguments); }; require('./test/setup'); }, debug: true }; };
JavaScript
0
@@ -1067,17 +1067,18 @@ timeout( -2 +10 00);%0A @@ -1372,24 +1372,24 @@ haUnderTest%0A + );%0A @@ -1389,524 +1389,8 @@ );%0A - // to make test/node-unit/color.spec.js pass, we need to run mocha in the project's folder context%0A const childProcess = require('child_process');%0A const execFile = childProcess.execFile;%0A childProcess.execFile = function() %7B%0A let opts = arguments%5B2%5D;%0A if (typeof opts === 'function') %7B%0A opts = %7B%7D;%0A Array.prototype.splice.call(arguments, 2, 0, opts);%0A %7D%0A opts.cwd = wallaby.localProjectDir;%0A return execFile.apply(this, arguments);%0A %7D;%0A
6a6db2a15565422d42a54571e39d476448cb3fb5
use es6 arrow functions for the sake of consistency
test/MultiCompiler.test.js
test/MultiCompiler.test.js
"use strict"; const path = require("path"); const { createFsFromVolume, Volume } = require("memfs"); const webpack = require(".."); const createMultiCompiler = () => { const compiler = webpack([ { context: path.join(__dirname, "fixtures"), entry: "./a.js" }, { context: path.join(__dirname, "fixtures"), entry: "./b.js" } ]); compiler.outputFileSystem = createFsFromVolume(new Volume()); compiler.watchFileSystem = { watch(a, b, c, d, e, f, g) {} }; return compiler; }; describe("MultiCompiler", function () { jest.setTimeout(20000); it("should trigger 'run' for each child compiler", done => { const compiler = createMultiCompiler(); let called = 0; compiler.hooks.run.tap("MultiCompiler test", () => called++); compiler.run(err => { if (err) { throw err; } expect(called).toBe(2); done(); }); }); it("should trigger 'watchRun' for each child compiler", done => { const compiler = createMultiCompiler(); let called = 0; compiler.hooks.watchRun.tap("MultiCompiler test", () => called++); const watcher = compiler.watch(1000, err => { if (err) { throw err; } watcher.close(); expect(called).toBe(2); done(); }); }); it("should not be running twice at a time (run)", function (done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return done(); }); }); it("should not be running twice at a time (watch)", function (done) { const compiler = createMultiCompiler(); const watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return watcher.close(done); }); }); it("should not be running twice at a time (run - watch)", function (done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); }); compiler.watch({}, (err, stats) => { if (err) return done(); }); }); it("should not be running twice at a time (watch - run)", function (done) { const compiler = createMultiCompiler(); let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); }); compiler.run((err, stats) => { if (err) return watcher.close(done); }); }); it("should not be running twice at a time (instance cb)", function (done) { const compiler = webpack( { context: __dirname, mode: "production", entry: "./c", output: { path: "/", filename: "bundle.js" } }, () => {} ); compiler.outputFileSystem = createFsFromVolume(new Volume()); compiler.run((err, stats) => { if (err) return done(); }); }); it("should run again correctly after first compilation", function (done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first compilation", function (done) { const compiler = createMultiCompiler(); compiler.run((err, stats) => { if (err) return done(err); let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); watcher.close(done); }); }); }); it("should run again correctly after first closed watch", function (done) { const compiler = createMultiCompiler(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { compiler.run((err, stats) => { if (err) return done(err); done(); }); }); }); it("should watch again correctly after first closed watch", function (done) { const compiler = createMultiCompiler(); const watching = compiler.watch({}, (err, stats) => { if (err) return done(err); }); watching.close(() => { let watcher; watcher = compiler.watch({}, (err, stats) => { if (err) return done(err); watcher.close(done); }); }); }); });
JavaScript
0.000002
@@ -1251,39 +1251,31 @@ ime (run)%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -1496,39 +1496,31 @@ e (watch)%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -1788,39 +1788,31 @@ - watch)%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -2045,39 +2045,31 @@ ch - run)%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -2344,31 +2344,23 @@ e cb)%22, -function ( done -) + =%3E %7B%0A%09%09con @@ -2728,39 +2728,31 @@ mpilation%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -3003,31 +3003,23 @@ ation%22, -function ( done -) + =%3E %7B%0A%09%09con @@ -3314,39 +3314,31 @@ sed watch%22, -function ( done -) + =%3E %7B%0A%09%09const c @@ -3647,23 +3647,15 @@ h%22, -function ( done -) + =%3E %7B%0A%09
1963dddb4c4b85bac510c1f9fb930e3402dbf30b
use different value for rest input
test/bq-translator.test.js
test/bq-translator.test.js
// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*- var assert = require('chai').assert; var BooleanQueryTranslator = require('../lib/bq-translator').BooleanQueryTranslator; function testQuery(label, expected, query) { test('query: ' + label + ': ' + '<' + query + '> -> <' + expected + '>', function() { var translator = new BooleanQueryTranslator(); assert.equal(expected, translator.translate(query)); }); } function testExpression(label, expectedScriptGrnExpr, expectedOffset, expression) { test('expression: ' + label + ': ' + '<' + expression + '> -> <' + expectedScriptGrnExpr + '>', function() { var translator = new BooleanQueryTranslator(); var context = { defaultField: "field", offset: 0 }; var actualScriptGrnExpr = translator.translateExpression(expression, context); assert.deepEqual({ scriptGrnExpr: expectedScriptGrnExpr, offset: expectedOffset }, { scriptGrnExpr: actualScriptGrnExpr, offset: context.offset }); }); } suite('BoolanQueryTranslator', function() { testQuery("expression", 'type:"ModelName"', "type:'ModelName'"); testQuery("group: raw expressions", 'query query type:"ModelName"', "(and query query type:'ModelName')"); testQuery("group: quoted expression", '"query query" type:"ModelName"', "(and 'query query' type:'ModelName')"); testExpression("value only: stirng", "field @ \"keyword1 keyword2\"", "'keyword1 keyword2'".length, "'keyword1 keyword2' 'other keyword'"); testExpression("value only: unsigned integer", "field == 29", "29".length, "29 29"); })
JavaScript
0.00003
@@ -1920,17 +1920,17 @@ %2229 -29 +75 %22);%0A%7D)%0A
7f6bda8aeae435ca4f5d4ab3feec0f88b4a9cb5b
Fix bad test for tabbed nav presence
test/components/AppTest.js
test/components/AppTest.js
const assert = require('assert') const React = require('react') const ReactDOM = require('react-dom') const ReactRedux = require('react-redux') const Redux = require('redux') const TestUtils = require('react-addons-test-utils') const fetchMock = require('fetch-mock') const App = require('../../src/components/App') const reducer = require('../../src/reducers/reducer') const GitHubAuth = require('../../src/models/GitHubAuth') const Filter = require('../../src/models/Filter') const LastFilter = require('../../src/models/LastFilter') const Config = require('../../src/config.json') function renderPage(store) { return TestUtils.renderIntoDocument( <ReactRedux.Provider store={store}> <App /> </ReactRedux.Provider> ) } describe('App', () => { let store describe('when valid auth token is not set', () => { before(() => { store = Redux.createStore(reducer) fetchMock.mock('*', {}) }) after(() => { fetchMock.restore() }) it('renders', () => { const appComponent = renderPage(store) assert(ReactDOM.findDOMNode(appComponent)) }) it('has a tabbed nav', () => { const appComponent = renderPage(store) const app = ReactDOM.findDOMNode(appComponent) assert(app.querySelectorAll('tabbed-nav')) }) it('does not make request without a token', () => { renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(0, fetchedCalls.length, 'No fetch calls should be made.') }) it('fetches user when auth token is set', () => { GitHubAuth.setToken('test-whee') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(1, fetchedCalls.length, 'Only one fetch call should be made') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) describe('when valid auth token is set', () => { before(() => { store = Redux.createStore(reducer) GitHubAuth.setToken('test-whee') fetchMock.get(`${Config.githubApiUrl}/user`, { login: 'testuser123' }) fetchMock.get(`${Config.githubApiUrl}/search/issues?q=cats`, []) }) after(() => { fetchMock.restore() }) it('fetches user and issues when filter exists', () => { const filter = new Filter('Cool name') filter.store('cats') LastFilter.save('Cool name') renderPage(store) const fetchedCalls = fetchMock.calls().matched assert.equal(2, fetchedCalls.length, 'Two fetch calls should be made') assert(fetchedCalls[1][0].match(/\/search\/issues/), 'Fetch call should be to the search issues API') assert(fetchedCalls[0][0].match(/\/user/), 'Fetch call should be to the user API') }) }) })
JavaScript
0.000001
@@ -1272,13 +1272,11 @@ ctor -All (' +# tabb
c5aa570edcc9c0815c304939d9ded20b13a8e56f
Update loader.js
plugins/spoon/project_structure/app/loader.js
plugins/spoon/project_structure/app/loader.js
/*global requirejs*/ requirejs.config({ baseUrl: '/dev/src', paths: { 'mout': '../bower_components/mout/src', 'events-emitter': '../bower_components/events-emitter/src', 'address': '../bower_components/address/src', 'text': '../bower_components/requirejs-text/text', 'has': '../bower_components/has/has', {{paths}} }, shim: { {{shim}} }, map: { '*': { // App config (defaults to dev but changes during build) 'app-config': '../app/config/config_dev', // Spoon 'spoon': '../bower_components/spoonjs/src/index', // Spoon aliases 'spoon/Controller': '../bower_components/spoonjs/src/core/Controller', 'spoon/View': '../bower_components/spoonjs/src/core/View', // Spoon services 'services/broadcaster': '../bower_components/spoonjs/src/core/Broadcaster/BroadcasterFactory', 'services/address': '../bower_components/spoonjs/src/core/Address/AddressFactory', 'services/state': '../bower_components/spoonjs/src/core/StateRegistry/StateRegistryFactory' } }, packages: [ // CSS plugin { name: 'css', location: '../bower_components/require-css', main: 'css' } ] });
JavaScript
0.000002
@@ -808,16 +808,89 @@ e/View', +%0A 'spoon/Joint': '../bower_components/spoonjs/src/core/Joint', %0A%0A
18f957c3a7fd7e70a4e275b2a4f700a5231316ce
add real controller tests
test/factories/debounce.js
test/factories/debounce.js
/*global beforeEach,afterEach,describe,it*/ import debounce from '../../src/factories/debounce' import { reset, check, expect, expectCount } from '../helpers/chaiCounter' beforeEach(reset) afterEach(check) describe('debounce()', function () { it('should not call output more than twice when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should not call output again after timeout when immediate', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: true }) const args = { output: { continue () { continued++ if (continued === 3) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should not call output more than once', function (done) { expectCount(1) let terminated = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { expect(terminated).to.equal(4) done() }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) it('should call output again after timeout', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, [], { immediate: false }) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(4) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) setTimeout(() => { chain[0](args) chain[0](args) chain[0](args) }, 15) }) it('should respect defaults', function (done) { expectCount(1) let terminated = 0 let continued = 0 const chain = debounce(10, []) const args = { output: { continue () { continued++ if (continued === 2) { expect(terminated).to.equal(3) done() } }, terminate () { terminated++ } } } chain[0](args) chain[0](args) chain[0](args) chain[0](args) chain[0](args) }) })
JavaScript
0.000001
@@ -168,81 +168,1300 @@ er'%0A -%0AbeforeEach(reset)%0AafterEach(check)%0A%0Adescribe('debounce()', function () %7B +import controller from '../helpers/controller'%0A%0Afunction increaseCount (%7B state %7D) %7B%0A state.set('count', state.get('count') + 1)%0A%7D%0A%0Acontroller.addSignals(%7B%0A increaseImmediate: %7Bchain: %5Bdebounce(1, %5BincreaseCount%5D)%5D, sync: true%7D,%0A increaseNotImmediate: %7Bchain: %5Bdebounce(1, %5BincreaseCount%5D, %7B%0A immediate: false%0A %7D)%5D, sync: true%7D%0A%7D)%0A%0Aconst signals = controller.getSignals()%0Alet tree%0A%0AbeforeEach(reset)%0AafterEach(check)%0A%0Adescribe('debounce()', function () %7B%0A beforeEach(function () %7B%0A tree = controller.model.tree%0A tree.set(%7B%0A count: 0%0A %7D)%0A tree.commit()%0A %7D)%0A%0A it('should not call increase more than twice when immediate', function (done) %7B%0A signals.increaseImmediate()%0A signals.increaseImmediate()%0A signals.increaseImmediate()%0A signals.increaseImmediate()%0A signals.increaseImmediate()%0A%0A setTimeout(function () %7B%0A expect(tree.get('count')).to.equal(2)%0A done()%0A %7D, 10)%0A %7D)%0A%0A it('should not call increase more than once when not immediate', function (done) %7B%0A signals.increaseNotImmediate()%0A signals.increaseNotImmediate()%0A signals.increaseNotImmediate()%0A signals.increaseNotImmediate()%0A signals.increaseNotImmediate()%0A%0A setTimeout(function () %7B%0A expect(tree.get('count')).to.equal(1)%0A done()%0A %7D, 10)%0A %7D)%0A %0A i
684e42a48c008c1ab7c53e0ba3220db8f5f777dc
revert debugging
stream/osm_filter.js
stream/osm_filter.js
var through = require('through2'), features = require('../features'); function isAddress( item ){ return( item.tags.hasOwnProperty('addr:housenumber') && item.tags.hasOwnProperty('addr:street') ); } function isPOIFromFeatureList( item ){ return( 'string' === typeof item.tags.name && !!features.getFeature( item ) ); } var lastCommit = new Date().getTime(); var c = 0; function inc( type, record ){ c++; var now = new Date().getTime(); if( now >= lastCommit +1000 ){ lastCommit = now; console.log( c ); c = 0; } } module.exports = function(){ var stream = through.obj( function( item, enc, done ) { inc( 'a', item ); // filter items missing requires properties if( !!item && item.hasOwnProperty('id') && (( item.type === 'node' && item.hasOwnProperty('lat') && item.hasOwnProperty('lon') ) || ( item.type === 'way' && Array.isArray( item.refs ) && item.refs.length > 0 )) && 'object' == typeof item.tags && ( isAddress( item ) || isPOIFromFeatureList( item ) )){ this.push( item ); } return done(); }); // catch stream errors stream.on( 'error', console.error.bind( console, __filename ) ); return stream; };
JavaScript
0.000001
@@ -328,225 +328,8 @@ %0A%7D%0A%0A -var lastCommit = new Date().getTime();%0Avar c = 0;%0A%0Afunction inc( type, record )%7B%0A c++;%0A var now = new Date().getTime();%0A if( now %3E= lastCommit +1000 )%7B%0A lastCommit = now;%0A console.log( c );%0A c = 0;%0A %7D%0A%7D%0A%0A modu @@ -417,31 +417,8 @@ %7B%0A%0A - inc( 'a', item );%0A%0A
b90b374f30fbf043d2ecaa0f87d5911d3b4df4c5
test main reducer handling SET_INTERFACE_FONT_SIZE_SCALING_FACTOR
test/redux/modules/main.js
test/redux/modules/main.js
import test from 'ava'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import mainReducer, {setInterfaceFontSizeScalingFactor, SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, setAppFont, SET_APP_FONT, setAppLocale, SET_APP_LOCALE, setWriteDelay, SET_WRITE_DELAY, setIntl} from './../../../src/redux/modules/main'; import zhTwMessages from './../../../src/langs/zh-TW'; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); test('should create an action to set interface font size scaling factor', (t) => { const interfaceFontSizeScalingFactor = 1; const expectedAction = { type: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor }; t.deepEqual(setInterfaceFontSizeScalingFactor(interfaceFontSizeScalingFactor), expectedAction); }); test('should create an action to set app font', (t) => { const appFont = 'Tibetan Machine Uni'; const expectedAction = { type: SET_APP_FONT, appFont }; t.deepEqual(setAppFont(appFont), expectedAction); }); test('should create an action to set app locale', (t) => { const appLocale = 'bo'; const expectedAction = { type: SET_APP_LOCALE, appLocale }; t.deepEqual(setAppLocale(appLocale), expectedAction); }); test('should create an action to set write delay', (t) => { const writeDelay = 25; const expectedAction = { type: SET_WRITE_DELAY, writeDelay }; t.deepEqual(setWriteDelay(writeDelay), expectedAction); }); test('should create an action to set react intl', (t) => { const store = mockStore({}); const locale = 'zh-TW'; const expectedAction = { type: '@@intl/UPDATE', payload: { locale, messages: zhTwMessages } }; const resultAction = store.dispatch(setIntl(locale)); t.deepEqual(resultAction, expectedAction); }); test('main reducer should handle action SET_APP_LOCALE', (t) => { const appLocale = 'en'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_LOCALE, appLocale}); t.deepEqual(result.toJS(), {appLocale}); }); test('main reducer should handle action SET_WRITE_DELAY', (t) => { const writeDelay = 50; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_WRITE_DELAY, writeDelay}); t.deepEqual(result.toJS(), {writeDelay}); }); test('main reducer should handle action SET_APP_FONT', (t) => { const appFont = 'Tibetan Machine Uni'; const store = mockStore({}); const result = mainReducer(store.getState(), {type: SET_APP_FONT, appFont}); t.deepEqual(result.toJS(), {appFont}); });
JavaScript
0.000002
@@ -2609,16 +2609,380 @@ %7BappFont%7D);%0A%7D);%0A +%0Atest('main reducer should handle action SET_INTERFACE_FONT_SIZE_SCALING_FACTOR', (t) =%3E %7B%0A const interfaceFontSizeScalingFactor = 1.5;%0A const store = mockStore(%7B%7D);%0A const result = mainReducer(store.getState(), %7Btype: SET_INTERFACE_FONT_SIZE_SCALING_FACTOR, interfaceFontSizeScalingFactor%7D);%0A t.deepEqual(result.toJS(), %7BinterfaceFontSizeScalingFactor%7D);%0A%7D);%0A
f34715ee7520fdbc793d3f3a67b8eaf157154209
Clean up tests.
test/session/store.test.js
test/session/store.test.js
var $require = require('proxyquire'); var expect = require('chai').expect; var sinon = require('sinon'); var factory = require('../../app/session/store'); var MemoryStore = require('express-session').MemoryStore; describe('session/store', function() { var NODE_ENV; var container = new Object(); var logger = new Object(); beforeEach(function() { NODE_ENV = process.env.NODE_ENV; container.create = sinon.stub(); logger.emergency = sinon.spy(); logger.alert = sinon.spy(); logger.critical = sinon.spy(); logger.error = sinon.spy(); logger.warning = sinon.spy(); logger.notice = sinon.spy(); logger.info = sinon.spy(); logger.debug = sinon.spy(); }); afterEach(function() { process.env.NODE_ENV = NODE_ENV; }); it('should be annotated', function() { expect(factory['@singleton']).to.equal(true); }); it('should resolve with application-supplied store', function(done) { var store = new Object(); container.create.resolves(store); factory(container, logger) .then(function(obj) { expect(container.create).to.have.been.calledOnce; expect(container.create).to.have.been.calledWith('http://i.bixbyjs.org/http/SessionStore'); expect(obj).to.equal(store); done(); }) .catch(done); }); // should resolve with application-supplied store it('should re-throw error creating application-supplied store', function(done) { var error = new Error('Something went wrong'); container.create.withArgs('http://i.bixbyjs.org/http/SessionStore').rejects(error); var store = new Object(); container.create.withArgs('./store/memory').resolves(store); factory(container, logger) .catch(function(err) { expect(container.create).to.have.been.calledOnce; expect(container.create).to.have.been.calledWith('http://i.bixbyjs.org/http/SessionStore'); expect(err).to.equal(error); done(); }); }); // should re-throw error creating application-supplied store it('should re-throw error in production environment when implementation not found', function(done) { process.env.NODE_ENV = 'production'; var error = new Error('Cannot find implementation'); error.code = 'IMPLEMENTATION_NOT_FOUND'; error.interface = 'http://i.bixbyjs.org/http/SessionStore'; container.create.withArgs('http://i.bixbyjs.org/http/SessionStore').rejects(error); var store = new Object(); container.create.withArgs('./store/memory').resolves(store); factory(container, logger) .catch(function(err) { expect(container.create).to.have.been.calledOnce; expect(container.create).to.have.been.calledWith('http://i.bixbyjs.org/http/SessionStore'); expect(err).to.equal(error); done(); }); }); // should re-throw error in production environment when implementation not found it('should resolve with memory store in development environment when implementation not found', function(done) { process.env.NODE_ENV = 'development'; var error = new Error('Cannot find implementation'); error.code = 'IMPLEMENTATION_NOT_FOUND'; error.interface = 'http://i.bixbyjs.org/http/SessionStore'; container.create.withArgs('http://i.bixbyjs.org/http/SessionStore').rejects(error); var store = new Object(); container.create.withArgs('./store/memory').resolves(store); factory(container, logger) .then(function(obj) { expect(logger.notice).to.have.been.calledWith('Using in-memory HTTP session store during development'); expect(container.create).to.have.been.calledTwice; expect(container.create.getCall(0).args[0]).to.equal('http://i.bixbyjs.org/http/SessionStore'); expect(container.create.getCall(1).args[0]).to.equal('./store/memory'); expect(obj).to.equal(store); done(); }) .catch(done); }); // should resolve with memory store in development environment when implementation not found }); // session/store
JavaScript
0
@@ -152,66 +152,8 @@ ');%0A -var MemoryStore = require('express-session').MemoryStore;%0A %0A%0Ade
d311de104685d657427085ba3bb66b20a63d4b04
Fix unit tests
test/spec/CSSUtils-test.js
test/spec/CSSUtils-test.js
/* * Copyright 2011 Adobe Systems Incorporated. All Rights Reserved. */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, waitsFor: false, runs: false, $: false, brackets: false */ define(function (require, exports, module) { 'use strict'; var CSSUtils = require("CSSUtils"), SpecRunnerUtils = require("./SpecRunnerUtils.js"); describe("CSS Utils", function () { var content = ""; beforeEach(function () { var doneReading = false; // Read the contents of bootstrap.css. This will be used for all tests below runs(function () { var testFilePath = SpecRunnerUtils.getTestPath("/spec/CSSUtils-test-files/"); brackets.fs.readFile(testFilePath + "bootstrap.css", "utf8", function (err, fileContents) { content = fileContents; doneReading = true; }); }); waitsFor(function () { return doneReading; }, 1000); }); it("should find the first instance of the h2 selector", function () { var selector = CSSUtils._findAllMatchingSelectorsInText(content, "h2")[0]; expect(selector).not.toBe(null); expect(selector.line).toBe(292); expect(selector.ruleEndLine).toBe(301); }); it("should find all instances of the h2 selector", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "h2"); expect(selectors).not.toBe(null); expect(selectors.length).toBe(2); expect(selectors[0].start).toBe(292); expect(selectors[0].end).toBe(301); expect(selectors[1].start).toBe(318); expect(selectors[1].end).toBe(321); }); it("should return an empty array when findAllMatchingSelectors() can't find any matches", function () { var selectors = CSSUtils._findAllMatchingSelectorsInText(content, "NO-SUCH-SELECTOR"); expect(selectors.length).toBe(0); }); }); });
JavaScript
0.000005
@@ -1841,21 +1841,20 @@ tors%5B0%5D. -start +line ).toBe(2 @@ -1890,19 +1890,27 @@ tors%5B0%5D. -end +ruleEndLine ).toBe(3 @@ -1950,13 +1950,12 @@ %5B1%5D. -start +line ).to @@ -1999,11 +1999,19 @@ %5B1%5D. -end +ruleEndLine ).to
8567710f50eeee9a6bde3039895d1d91bc85b56f
Document ui/ContainerAnnotator.
ui/ContainerAnnotator.js
ui/ContainerAnnotator.js
'use strict'; var oo = require('../util/oo'); var _ = require('../util/helpers'); var Component = require('./Component'); var ContainerEditor = require('./ContainerEditor'); var $$ = Component.$$; /** Represents a flow annotator that manages a sequence of nodes in a container. Instantiate this class using {@link ui/Component.$$} within the render method of a component. Needs to be instantiated within a {@link ui/Controller} context. @class ContainerAnnotator @component @extends ui/ContainerEditor @example ```js var ContainerAnnotator = require('substance/ui/ContainerAnnotator'); var Component = require('substance/ui/Component'); var ToggleStrong = require('substance/packages/strong/ToggleStrong'); var MyAnnotator = Component.extend({ render: function() { var annotator = $$(ContainerAnnotator, { name: 'main', containerId: 'main', doc: doc, commands: [ToggleStrong] }).ref('annotator'); return $$('div').addClass('my-annotator').append(annotator); } }); ``` */ function ContainerAnnotator() { ContainerEditor.apply(this, arguments); } ContainerAnnotator.Prototype = function() { this.render = function() { var doc = this.getDocument(); var containerNode = doc.get(this.props.containerId); var el = $$("div") .addClass('surface container-node ' + containerNode.id) .attr({ spellCheck: false, "data-id": containerNode.id, "contenteditable": false }); // node components _.each(containerNode.nodes, function(nodeId) { el.append(this._renderNode(nodeId)); }, this); return el; }; }; oo.inherit(ContainerAnnotator, ContainerEditor); module.exports = ContainerAnnotator;
JavaScript
0
@@ -279,546 +279,404 @@ er. -Instantiate%0A this class using %7B@link ui/Component.$$%7D within the render method of a component. Needs to be%0A instantiated within a %7B@link ui/Controller%7D context.%0A%0A @class ContainerAnnotator%0A @component%0A @extends ui/ContainerEditor%0A%0A @example%0A%0A %60%60%60js%0A var ContainerAnnotator = require('substance/ui/ContainerAnnotator');%0A var Component = require('substance/ui/Component');%0A var ToggleStrong = require('substance/packages/strong/ToggleStrong');%0A%0A var MyAnnotator = Component.extend(%7B%0A render: function() %7B%0A var annotator = +Needs to%0A be instantiated within a ui/Controller context. Works like a %7B@link ui/ContainerEditor%7D%0A but you can only annotate, not edit.%0A%0A @class ContainerAnnotator%0A @component%0A @extends ui/ContainerEditor%0A%0A @prop %7BString%7D name unique editor name%0A @prop %7BString%7D containerId container id%0A @prop %7Bui/SurfaceCommand%5B%5D%7D commands array of command classes to be available%0A%0A @example%0A%0A %60%60%60js%0A $$( @@ -697,20 +697,16 @@ ator, %7B%0A - name @@ -708,27 +708,30 @@ name: ' -main',%0A +bodySurface',%0A cont @@ -751,20 +751,16 @@ n',%0A - - doc: doc @@ -761,20 +761,16 @@ c: doc,%0A - comm @@ -796,111 +796,10 @@ %5D%0A - %7D).ref('annotator');%0A return $$('div').addClass('my-annotator').append(annotator);%0A %7D%0A %7D); +%7D) %0A %60
fa32335f6e496a98ac9dc11821690839f81224f7
Make new UI tests faster.
test/test/util/ui_utils.js
test/test/util/ui_utils.js
/** * @license * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('shaka.test.UiUtils'); shaka.test.UiUtils = class { /** * @param {!HTMLElement} videoContainer * @param {!HTMLMediaElement} video * @param {!Object=} config * @return {!shaka.ui.Overlay} */ static createUIThroughAPI(videoContainer, video, config) { const player = new shaka.Player(video); // Create UI config = config || {}; const ui = new shaka.ui.Overlay(player, videoContainer, video); ui.getControls().addEventListener('error', (/** * */ e) => fail(e.detail)); ui.configure(config); return ui; } /** * @param {!Array.<!Element>} containers * @param {!Array.<!Element>} videos * @suppress {visibility} */ static async createUIThroughDOMAutoSetup(containers, videos) { const eventManager = new shaka.util.EventManager(); const waiter = new shaka.test.Waiter(eventManager); for (const container of containers) { container.setAttribute('data-shaka-player-container', ''); } for (const video of videos) { video.setAttribute('data-shaka-player', ''); } // Call UI's private method to scan the page for shaka // elements and create the UI. shaka.ui.Overlay.scanPageForShakaElements_(); await waiter.failOnTimeout(false).waitForEvent(document, 'shaka-ui-loaded'); } /** * @param {!HTMLElement} parent * @param {string} className */ static confirmElementFound(parent, className) { const elements = parent.getElementsByClassName(className); expect(elements.length).toBe(1); } /** * @param {!HTMLElement} parent * @param {string} className */ static confirmElementMissing(parent, className) { const elements = parent.getElementsByClassName(className); expect(elements.length).toBe(0); } /** * Thoroughly clean up after UI-related tests. * * The UI tests can create lots of DOM elements (including videos) that are * easy to lose track of. This is a universal cleanup system to avoid leaving * anything behind. */ static async cleanupUI() { // If we don't clean up the UI, these tests could pollute the environment // for other tests that run later, causing failures in unrelated tests. // This is causing particular issues on Tizen. const containers = document.querySelectorAll('[data-shaka-player-container]'); const destroys = []; for (const container of containers) { const ui = /** @type {shaka.ui.Overlay} */(container['ui']); // Destroying the UI destroys the controls and player inside. destroys.push(ui.destroy()); } await Promise.all(destroys); // Now remove all the containers from the DOM. for (const container of containers) { container.parentElement.removeChild(container); } } /** * @param {!Element} cssLink */ static async setupCSS(cssLink) { const head = document.head; cssLink.type = 'text/css'; cssLink.rel = 'stylesheet/less'; cssLink.href ='/base/ui/controls.less'; head.appendChild(cssLink); // LESS script has been added at the beginning of the test pass // (in test/test/boot.js). This tells it that we've added a new // stylesheet, so LESS can process it. less.registerStylesheetsImmediately(); await less.refresh(/* reload */ true, /* modifyVars*/ false, /* clearFileCache */ false); } /** * Simulates a native event (e.g. 'click') on the given element. * * @param {EventTarget} target * @param {string} name */ static simulateEvent(target, name) { const type = { 'click': 'MouseEvent', 'dblclick': 'MouseEvent', }[name] || 'CustomEvent'; // Note we can't use the MouseEvent constructor since it isn't supported on // IE11. const event = document.createEvent(type); event.initEvent(name, true, true); target.dispatchEvent(event); } };
JavaScript
0.000058
@@ -1670,24 +1670,186 @@ '');%0A %7D%0A%0A + // Create the waiter first so we can catch a synchronous event.%0A const p =%0A waiter.failOnTimeout(false).waitForEvent(document, 'shaka-ui-loaded');%0A%0A // Call @@ -1895,16 +1895,16 @@ r shaka%0A - // e @@ -1994,77 +1994,9 @@ ait -waiter.failOnTimeout(false).waitForEvent(document, 'shaka-ui-loaded') +p ;%0A
6e9cc6c6cc90055361373d0e21654ff8eb83e736
Add additional UgliffyJSPlugin options
ui/webpack/prodConfig.js
ui/webpack/prodConfig.js
/* eslint-disable no-var */ const webpack = require('webpack') const path = require('path') const ExtractTextPlugin = require('extract-text-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin') const package = require('../package.json') const dependencies = package.dependencies const babelLoader = { loader: 'babel-loader', options: { cacheDirectory: false, presets: ['env', 'react', 'stage-0'], }, } const config = { node: { fs: 'empty', module: 'empty', }, bail: true, devtool: false, entry: { app: path.resolve(__dirname, '..', 'src', 'index.js'), vendor: Object.keys(dependencies), }, output: { publicPath: '/', path: path.resolve(__dirname, '../build'), filename: '[name].[chunkhash].js', }, resolve: { alias: { app: path.resolve(__dirname, '..', 'app'), src: path.resolve(__dirname, '..', 'src'), shared: path.resolve(__dirname, '..', 'src', 'shared'), style: path.resolve(__dirname, '..', 'src', 'style'), utils: path.resolve(__dirname, '..', 'src', 'utils'), }, extensions: ['.ts', '.tsx', '.js'], }, module: { noParse: [ path.resolve( __dirname, '..', 'node_modules', 'memoizerific', 'memoizerific.js' ), ], loaders: [ { test: /\.js$/, exclude: [/node_modules/, /(_s|S)pec\.js$/], use: 'eslint-loader', enforce: 'pre', }, { test: /\.scss$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ 'css-loader', 'sass-loader', 'resolve-url-loader', 'sass-loader?sourceMap', ], }), }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader'], }), }, { test: /\.(ico|png|cur|jpg|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader: 'file-loader', }, { test: /\.js$/, exclude: /node_modules/, use: [{loader: 'thread-loader'}, babelLoader], }, { test: /\.ts(x?)$/, exclude: /node_modules/, use: [ { loader: 'thread-loader', options: { // there should be 1 cpu for the fork-ts-checker-webpack-plugin workers: require('os').cpus().length - 1, }, }, babelLoader, { loader: 'ts-loader', options: { happyPackMode: true, // required for use with thread-loader }, }, ], }, ], }, plugins: [ new webpack.DefinePlugin({ VERSION: JSON.stringify(require('../package.json').version), 'process.env.NODE_ENV': JSON.stringify('production'), }), new webpack.optimize.ModuleConcatenationPlugin(), new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true, }), new webpack.LoaderOptionsPlugin({ postcss: require('./postcss'), options: { eslint: { failOnWarning: false, failOnError: false, }, }, }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), new ExtractTextPlugin('chronograf.css'), new HtmlWebpackPlugin({ template: path.resolve(__dirname, '..', 'src', 'index.template.html'), inject: 'body', chunksSortMode: 'dependency', favicon: 'assets/images/favicon.ico', }), new UglifyJsPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks(module) { return module.context && module.context.indexOf('node_modules') >= 0 }, }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', }), function() { /* Webpack does not exit with non-zero status if error. */ this.plugin('done', function(stats) { if ( stats.compilation.errors && stats.compilation.errors.length && process.argv.indexOf('--watch') == -1 ) { console.log( stats.compilation.errors.toString({ colors: true, }) ) process.exit(1) } }) }, ], target: 'web', } module.exports = config
JavaScript
0
@@ -3731,24 +3731,105 @@ ifyJsPlugin( +%7B%0A parallel: true,%0A uglifyOptions: %7B%0A ie8: false,%0A %7D,%0A %7D ),%0A new w
e1230f472d33ea79b12e299c8585886686050d89
work with connection logigc
middleware.js
middleware.js
module.exports = { incoming: function (message, args) { console.log(args); console.log('users') console.log(global.users); console.log('************'); // WHERE do we create a user? on first run? // WHEN do we update the user's address? Conv id will change. // Store by convo id? // add message to transcript // update last active to help keep track of 'current' convos // TODO: this will BREAK with changing convoIds. fix it if (message.text) { // only execute on message event var userConvo = message.address.conversation.id; if (!message.address.user.isStaff && !global.users[userConvo]) { console.log('I am adding a new user') global.users[userConvo] = new global.User(message); } else if (!message.address.user.isStaff) { global.users[userConvo].transcript += message.text; } else { // TODO make real logic around agent global.agents[userConvo] = new global.User(message); } } else if (message.text === 'bot') { handoffToBot(message.user.conversation.id); } return message; }, outgoing: function (message, args) { // routing info goes here. // or default to user address, just change if they want to talk to a user? // like update addy value. Then we just look for our own entry and route accordingly console.log(message.address); console.log(args); if (!message.address.user.isStaff) { // route user messages to agent if appropriate. Otherwise send to the bot message.address = global.users[message.address.converation.id].routeMessagesTo ? global.users[message.address.converation.id].routeMessagesTo : message.address; } console.log('address'); console.log(message.address); console.log('==========='); return message }, handoffToAgent: function (user) { var agent = Object.keys(global.agents); // TODO choose how to filter for an agent, or factor out to another method // make agnostic enough that this can pass to agent from bot or another agent // keep in mind only letting 1 user talk to 1 agent. 1 agent can talk to many users global.users[user].routeMessagesTo = agent[0].address; }, handoffToBot: function (user) { // look up user global.users[user].routeMessagesTo = false; }, getCurrentConversations: function () { // return all current conversations }, transcribeConversation: function () { // store all messages between user/bot user/agent // do this in a way that speaker is obvious }, getTranscriptForAgent: function () { // end goal is to populate a webchat window so agent seamlessly joins existing conversation }, }
JavaScript
0
@@ -73,32 +73,98 @@ sole.log(args);%0A + console.log('agents')%0A console.log(global.agents);%0A console. @@ -175,16 +175,18 @@ 'users') +;%0A %0A @@ -2425,16 +2425,85 @@ ny users +%0A console.log('handoff to agent');%0A console.log(agent); %0A%0A @@ -2545,16 +2545,30 @@ o = +global.agents%5B agent%5B0%5D .add @@ -2563,16 +2563,17 @@ agent%5B0%5D +%5D .address
a23cbe516dc69ffd39c07e4bdf394a51c1374a04
Clarify the copy in the add liquids to deck hint (#2107)
protocol-designer/src/tutorial/hintManifest.js
protocol-designer/src/tutorial/hintManifest.js
// @flow type Hint = {title: string, body: string} const hintManifest: {[string]: Hint} = { add_liquids_and_labware: { title: 'Add Liquids to Deck', body: "Go to 'Labware & Liquids' and specify where liquids start on the deck before the robot starts moving." } } export type HintKey = $Keys<typeof hintManifest> export default hintManifest
JavaScript
0.000001
@@ -164,38 +164,60 @@ dy: -%22 +' Go to -'Labware & Liquids' and +Starting Deck State and hover over labware to spe @@ -245,20 +245,8 @@ art -on the deck befo @@ -276,9 +276,9 @@ ing. -%22 +' %0A %7D
713c03cd946b03939517e3932ab822b00b95eaf5
fix the auto registering of app services
src/Kernel/Core.js
src/Kernel/Core.js
namespace('Sy.Kernel'); /** * Framework heart * * @package Sy * @subpackage Kernel * @class */ Sy.Kernel.Core = function () { this.config = new Sy.Configurator(); this.container = new Sy.ServiceContainer('sy::core'); }; Sy.Kernel.Core.prototype = Object.create(Object.prototype, { /** * Return the framework config object * * @return {Sy.Configurator} */ getConfig: { value: function () { return this.config; } }, /** * Return the service container object * * @return {Sy.ServiceContainer} */ getServiceContainer: { value: function () { return this.container; } }, /** * Initiate the kernel that will inspect the app and build necessary data * * @return {Sy.Kernel.Core} */ init: { value: function () { var parser = new Sy.Kernel.AppParser(); this.config.set('parameters.app.meta', { bundles: parser.getBundles(), controllers: parser.getControllers(), entities: parser.getEntities(), viewscreens: parser.getViewScreens() }); this.registerServices(parser.getServices()); } }, /** * Register the app services in the global container * * @param {Array} services * * @return {Sy.Kernel.Core} */ registerServices: { value: function (services) { for (var i = 0, l = services.length; i < l; i++) { if (services[i].creator) { this.container.set( services[i].name, services[i].creator ); } else if (typeof services[i].constructor === 'string') { var name = services[i].name; delete services[i].name; this.container.set( name, services[i] ); } } return this; } } });
JavaScript
0.000001
@@ -1841,16 +1841,50 @@ var +def = %7B%7D,%0A name = s @@ -1970,81 +1970,19 @@ -this.container.set(%0A name,%0A +def%5Bname%5D = ser @@ -1989,16 +1989,17 @@ vices%5Bi%5D +; %0A @@ -2003,32 +2003,54 @@ +this.container.set(def );%0A
0ebbea0ac8c1b0f6fe435623ae01549bbab7de55
Set element to play area on task detail on element exist
public/javascripts/app/views/projectManager.js
public/javascripts/app/views/projectManager.js
define([ 'Backbone', //Model 'app/models/project', //Collection 'app/collections/projects', //View 'app/views/taskController', 'app/views/projectsController', 'app/views/filterController', 'app/views/playersController', //Templates 'text!templates/project-page/gamePageTemplate.html', 'text!templates/project-page/errorTemplate.html' ], function( Backbone, //Model Project, //Collection Projects, //Views taskController, projectsController, filterController, playersController, //Templates gamePageTemplate, errorTemplate ){ var ProjectManager = Backbone.View.extend({ template: _.template(gamePageTemplate), errorTemplate: _.template(errorTemplate), model: new Project(), initialize: function(){ this.model.clear({silent: true}).off(); this.model.bind('change:error', this.error, this); this.model.bind('change:name', this.render, this); this.model.fetch({data: {id: this.options.projectId}}); this.players = new playersController({ collection: this.options.players, message: this.options.playerMessage, project: this.model }); this.projectsList = new projectsController({ collection: new Projects(), router: this.options.router }); this.taskList = new taskController({ projectId: this.options.projectId }); this.filter = new filterController({ collection: this.taskList.collection }); }, error: function(){ var message = this.model.get('error'); this.$el.html(this.errorTemplate({message: message})); }, render: function(){ var project = this.model.get('name'); var player = this.options.router.account.get('user'); socket.emit('add player', player, project); this.$el.html(this.template({project: {name: project}})); this.taskList.setElement('.js-taskList'); this.filter.setElement('.fn-filter-task'); this.players.setElement('.js-player-list'); this.players.options.message.trigger('change'); this.taskList.collection.fetch(); if(!$('.projects-list li')[0]){ this.projectsList.setElement('.projects-list').start(); } } }); return ProjectManager; });
JavaScript
0
@@ -2130,16 +2130,73 @@ fetch(); +%0A this.taskList.taskDetail.setElement('#play-area'); %0A%0A
8d8240cb90dd646bbf93ad8139bbadb4ed827b80
Remove double 'data' event on write
src/OrbitClient.js
src/OrbitClient.js
'use strict'; const EventEmitter = require('events').EventEmitter; const async = require('asyncawait/async'); const await = require('asyncawait/await'); const ipfsDaemon = require('orbit-common/lib/ipfs-daemon'); const PubSub = require('./PubSub'); const OrbitDB = require('./OrbitDB'); class OrbitClient { constructor(ipfs, daemon) { this._ipfs = ipfs; this._pubsub = null; this.user = null; this.network = null; this.events = new EventEmitter(); this.db = new OrbitDB(this._ipfs); } channel(channel, password, subscribe) { if(password === undefined) password = ''; if(subscribe === undefined) subscribe = true; this.db.use(channel, this.user, password); this.db.events.on('write', this._onWrite.bind(this)); this.db.events.on('sync', this._onSync.bind(this)); if(subscribe) this._pubsub.subscribe(channel, password, async((channel, message) => this.db.sync(channel, message))); return { iterator: (options) => this._iterator(channel, password, options), delete: () => this.db.deleteChannel(channel, password), del: (key) => this.db.del(channel, password, key), add: (data) => this.db.add(channel, password, data), put: (key, data) => this.db.put(channel, password, key, data), get: (key, options) => { const items = this._iterator(channel, password, { key: key }).collect(); return items[0] ? items[0].value : null; }, leave: () => this._pubsub.unsubscribe(channel) } } disconnect() { this._pubsub.disconnect(); this._store = {}; this.user = null; this.network = null; } _onWrite(channel, hash) { this._pubsub.publish(channel, hash) this.events.emit('data', channel, hash); } _onSync(channel, hash) { this.events.emit('data', channel, hash); } _iterator(channel, password, options) { const messages = this.db.query(channel, password, options); let currentIndex = 0; let iterator = { [Symbol.iterator]() { return this; }, next() { let item = { value: null, done: true }; if(currentIndex < messages.length) { item = { value: messages[currentIndex], done: false }; currentIndex ++; } return item; }, collect: () => messages } return iterator; } _connect(host, port, username, password, allowOffline) { if(allowOffline === undefined) allowOffline = false; try { this._pubsub = new PubSub(this._ipfs); await(this._pubsub.connect(host, port, username, password)); } catch(e) { if(!allowOffline) throw e; } this.user = { username: username, id: 'TODO: user id' } this.network = { host: host, port: port, name: 'TODO: network name' } } } class OrbitClientFactory { static connect(host, port, username, password, allowOffline, ipfs) { if(!ipfs) { let ipfsd = await(ipfsDaemon()); ipfs = ipfsd.ipfs; } const client = new OrbitClient(ipfs); await(client._connect(host, port, username, password, allowOffline)) return client; } } module.exports = OrbitClientFactory;
JavaScript
0.002583
@@ -1722,24 +1722,27 @@ l, hash)%0A + // this.events
e28e21d69e10dbcf4b276ad19447fede6e596bb8
update Popup
src/Popup/Popup.js
src/Popup/Popup.js
/** * @file Popup component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import BasePopup from '../_BasePopover'; import Theme from '../Theme'; import Position from '../_statics/Position'; import Event from '../_vendors/Event'; import Dom from '../_vendors/Dom'; import Util from '../_vendors/Util'; class Popup extends Component { static Position = Position; static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.mouseDownHandler = ::this.mouseDownHandler; } triggerHandler(el, triggerEl, popupEl, currentVisible, isAutoClose) { while (el) { if (el == popupEl) { return currentVisible; } el = el.parentNode; } return isAutoClose ? false : currentVisible; } mouseDownHandler(e) { const {visible, triggerEl, isAutoClose, triggerHandler, onRequestClose} = this.props, popupEl = this.refs.popup.getEl(); if (!triggerEl) { return; } let currVisible; if (triggerHandler) { currVisible = triggerHandler(e.target, triggerEl, popupEl, visible, isAutoClose); } else if (!Dom.isParent(e.target, triggerEl)) { currVisible = this.triggerHandler(e.target, triggerEl, popupEl, visible, isAutoClose); } if (currVisible === false) { setTimeout(() => { onRequestClose && onRequestClose(e); }, 0); } } /** * public */ resetPosition() { this.refs.popup.resetPosition(); } componentDidMount() { Event.addEvent(document, 'mousedown', this.mouseDownHandler); } componentWillUnmount() { Event.removeEvent(document, 'mousedown', this.mouseDownHandler); } render() { const { className, // not passing down these props triggerHandler, onRequestClose, ...restProps } = this.props, popupClassName = classNames('popup', { [className]: className }); return ( <BasePopup {...restProps} ref="popup" className={popupClassName} contentClassName="popup-content"/> ); } }; Popup.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * This is the DOM element that will be used to set the position of the popover. */ triggerEl: PropTypes.object, /** * If true,the popover is visible. */ visible: PropTypes.bool, /** * If true,the popover will have a triangle on the top of the DOM element. */ hasTriangle: PropTypes.bool, triangle: PropTypes.element, /** * The popover theme.Can be primary,highlight,success,warning,error. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The popover alignment.The value can be Popup.Position.LEFT or Popup.Position.RIGHT. */ position: PropTypes.oneOf(Util.enumerateValue(Position)), /** * If true,popup will have animation effects. */ isAnimated: PropTypes.bool, /** * The depth of Paper component. */ depth: PropTypes.number, isAutoClose: PropTypes.bool, isEscClose: PropTypes.bool, shouldPreventContainerScroll: PropTypes.bool, isTriggerPositionFixed: PropTypes.bool, /** * The function of popup event handler. */ triggerHandler: PropTypes.func, /** * The function of popup render. */ onRender: PropTypes.func, /** * Callback function fired when the popover is requested to be closed. */ onRequestClose: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; Popup.defaultProps = { className: null, style: null, depth: 6, triggerEl: null, visible: false, hasTriangle: true, theme: Theme.DEFAULT, position: Position.BOTTOM_LEFT, isAnimated: true, isAutoClose: true, isEscClose: true, shouldPreventContainerScroll: true, isTriggerPositionFixed: false }; export default Popup;
JavaScript
0.000001
@@ -200,25 +200,23 @@ %0Aimport -BasePopup +Popover from '. @@ -221,13 +221,8 @@ '../ -_Base Popo @@ -2304,17 +2304,15 @@ %3C -BasePopup +Popover %7B.. @@ -2323,18 +2323,16 @@ tProps%7D%0A - @@ -2369,34 +2369,32 @@ - className=%7Bpopup @@ -2404,18 +2404,16 @@ ssName%7D%0A -
a01ef325285fdc4f34972c3aa9cc9e0f377f1cff
Update ember-qunit to 0.4.2.
blueprints/ember-cli-qunit/index.js
blueprints/ember-cli-qunit/index.js
module.exports = { normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us }, afterInstall: function() { return this.addBowerPackagesToProject([ { name: 'qunit', target: '~1.17.1' }, { name: 'ember-cli/ember-cli-test-loader', target: '0.1.3' }, { name: 'ember-qunit-notifications', target: '0.0.7' }, { name: 'ember-qunit', target: '0.4.1' } ]); } };
JavaScript
0
@@ -522,17 +522,17 @@ t: '0.4. -1 +2 ' %7D%0A
ae349eeeb5a5cbd22f6050e3cb1b105ea90bf49a
add the ability to bootstrap an app with no account
blueprints/ember-pagefront/index.js
blueprints/ember-pagefront/index.js
var chalk = require('chalk'); var appendFileSync = require('fs').appendFileSync; var green = chalk.green; var white = chalk.white; var DEPLOY = 'ember deploy production'; var NEW_LINE = '\n'; var MESSAGE = NEW_LINE + green('Success! Now deploy your app: ') + white(DEPLOY) + NEW_LINE; var GITIGNORE = '.gitignore'; var DOT_ENV_FILE = '.env.deploy.*'; module.exports = { normalizeEntityName: function() {}, beforeInstall: function() { return this.addPackageToProject('ember-cli-deploy', '0.5.1'); }, afterInstall: function() { appendFileSync(GITIGNORE, NEW_LINE + DOT_ENV_FILE + NEW_LINE); this.ui.writeLine(MESSAGE); }, locals: function(options) { return { app: options.app, key: options.key }; } }
JavaScript
0.000001
@@ -1,12 +1,64 @@ +var Promise = require('ember-cli/lib/ext/promise');%0A var chalk = @@ -127,16 +127,74 @@ eSync;%0A%0A +var API = require('ember-cli-deploy-pagefront/lib/api');%0A%0A var gree @@ -301,23 +301,23 @@ n';%0Avar -MESSAGE +SUCCESS = NEW_L @@ -398,259 +398,1376 @@ var -GITIGNORE = '.gitignore';%0Avar DOT_ENV_FILE = '.env.deploy.*';%0A%0Amodule.exports = %7B%0A normalizeEntityName: function() %7B%7D,%0A%0A beforeInstall: function() %7B%0A return this.addPackageToProject('ember-cli-deploy', '0.5.1');%0A %7D,%0A%0A afterInstall: function() %7B +COMMAND= '%60ember g ember-pagefront --app=YOUR_APP_NAME%60';%0Avar MISSING_APP = 'No app was specified. Please run ' + COMMAND + ' to finish setting up.';%0Avar APP_TAKEN = 'Darn. That app name has already been taken. Try again with a new name: ' + COMMAND;%0Avar BOOTSTRAP_FAILED = 'Whoops. Something went wrong. Try again: ' + COMMAND;%0Avar GITIGNORE = '.gitignore';%0Avar DOT_ENV_FILE = '.env.deploy.*';%0Avar ECD = 'ember-cli-deploy';%0Avar ECD_VERSION = '0.5.1';%0Avar UNPROCESSABLE = 422;%0A%0Afunction bootstrap(app) %7B%0A var api = new API();%0A%0A return api.bootstrapApp(%7B app: app %7D);%0A%7D%0A%0Amodule.exports = %7B%0A availableOptions: %5B%0A %7B%0A name: 'app',%0A type: String%0A %7D,%0A %7B%0A name: 'key',%0A type: String%0A %7D%0A %5D,%0A%0A normalizeEntityName: function() %7B%7D,%0A%0A locals: function(options) %7B%0A return %7B%0A app: options.app,%0A key: options.key%0A %7D;%0A %7D,%0A%0A beforeInstall: function(options, locals) %7B%0A if (!options.app) %7B%0A return Promise.reject(MISSING_APP);%0A %7D%0A%0A if (!options.key) %7B%0A return bootstrap(options.app).then(function(response) %7B%0A locals.key = response.key;%0A %7D, function(response) %7B%0A if (response.statusCode === UNPROCESSABLE) %7B%0A throw APP_TAKEN;%0A %7D else %7B%0A throw BOOTSTRAP_FAILED%0A %7D%0A %7D);%0A %7D%0A %7D,%0A%0A afterInstall: function() %7B%0A var success = this.didSucceed.bind(this);%0A %0A @@ -1834,37 +1834,75 @@ E);%0A +%0A -this.ui.writeLine(MESSAGE +return this.addPackageToProject(ECD, ECD_VERSION).then(success );%0A @@ -1904,30 +1904,34 @@ s);%0A %7D,%0A%0A -locals +didSucceed : function(o @@ -1925,39 +1925,32 @@ d: function( -options ) %7B%0A return %7B%0A @@ -1941,69 +1941,34 @@ -return %7B%0A app: options.app,%0A key: options.key%0A %7D +this.ui.writeLine(SUCCESS) ;%0A
e93b6596dcd9a0b4d16248a106daa586780d2b8c
update passport local strategy to fetch actual user via sql query
config/passport.js
config/passport.js
const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const db = require('./database'); const { query } = require('../utils'); passport.use(new LocalStrategy({ usernameField: 'identifier' }, (username, password, done) => { const user = { fullname: 'Arnelle Balane', username: 'arnellebalane', email: 'arnellebalane@gmail.com', avatar: 'static/images/default-avatar.png' }; done(null, user); })); passport.serializeUser((user, done) => { done(null, user.email); }); passport.deserializeUser(async (email, done) => { const getUsersWithEmailQuery = await query('03-get-users-with-email.sql', { email }); const users = await db.query(getUsersWithEmailQuery); if (users.rows.length > 0) { const user = users.rows[0]; user.avatar = 'static/images/default-avatar.png'; done(null, users.rows[0]); } else { done(null, new Error('User not found.')); } }); module.exports = passport;
JavaScript
0
@@ -235,17 +235,23 @@ %0A%7D, -(username +async (idenfier , pa @@ -283,129 +283,244 @@ nst -user = %7B%0A fullname: 'Arnelle Balane',%0A username: 'arnellebalane',%0A email: 'arnellebalane@gmail.com', +getUserWithCredentialsQuery = await query('05-get-user-with-credentials.sql', %7B identifier, password %7D);%0A const users = await db.query(getUserWithCredentialsQuery);%0A%0A if (users.rows.length %3E 0) %7B%0A const user = users.row%5B0%5D; %0A @@ -528,15 +528,21 @@ +user. avatar -: + = 'st @@ -576,16 +576,14 @@ png' +; %0A -%7D;%0A @@ -599,16 +599,85 @@ , user); +%0A %7D else %7B%0A done(null, new Error('User not found.'));%0A %7D %0A%7D));%0A%0Ap
99320746931af6f7b5da58aed7f211f85bfc3673
add style changing support
ui/app.js
ui/app.js
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); //// var PhraseData = require('./data'); var Engine = require('./engine'); var PhrasePrompt = require('./phrase_prompt'); var eng = new Engine({ complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var prompt = new PhrasePrompt({ generatePhrase: PhraseData.generatePhrase, displayTime: 1500, inputTime: 10000, maxErrorPerWord: 1, repromptDelay: 200, complexity: eng.complexity }); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); prompt.on('stopkey', function(event) { if (event.keyCode === 0x1b) ss.stop(); }); ss.on('start', prompt.start.bind(prompt)); ss.on('stop', prompt.stop.bind(prompt)); ss.on('keypress', function(event) { if (prompt.inputing) return; var char = String.fromCharCode(event.charCode); if (char !== prompt.expected[0]) return; event.stopPropagation(); event.preventDefault(); prompt.showInput(); prompt.inputElement.value = char; prompt.updateInput(); }); ss.addListeners(window); prompt.on('result', eng.onResult.bind(eng)); eng.on('idle', ss.stop.bind(ss));
JavaScript
0.000003
@@ -285,16 +285,702 @@ %7D));%0A%0A +// XXX use a module for this%0Afunction loadHash() %7B%0A var hash = window.location.hash;%0A if (hash && hash%5B0%5D === '#') hash = hash.slice(1);%0A var parts = hash.split(';');%0A var out = %7B%7D;%0A parts.forEach(function(part) %7B%0A var i = part.indexOf('=');%0A if (i === -1) %7B%0A out%5Bpart%5D = true;%0A %7D else %7B%0A var key = part.slice(0, i);%0A var val = part.slice(i + 1);%0A out%5Bkey%5D = val;%0A %7D%0A %7D);%0A return out;%0A%7D%0A%0Avar Hash = loadHash();%0A%0Avar style = Hash.style %7C%7C 'light';%0Adocument.head.appendChild(%0A h('link', %7B%0A rel: 'stylesheet',%0A type: 'text/css',%0A href: 'style-' + style + '.css'%0A %7D));%0A%0A ////%0A%0Ava
46b9e204203d7ce33cb99630c8a19d1e8d29231b
make maxErrorPerWord and repromptDelay defaults explicit
ui/app.js
ui/app.js
var h = require('hyperscript'); // XXX require('global/mumble') var window = global.window; var document = global.document; document.title = 'Flash Phrases'; document.head.appendChild( h('link', { rel: 'stylesheet', type: 'text/css', href: 'style.css' })); //// var fs = require('fs'); var Markov = require('../lib/markov'); var markov = Markov.load(JSON.parse(fs.readFileSync('markov_source.json'))); function generatePhrase(numPhrases, minLength) { var phrase = ''; while (phrase.length < minLength) { phrase = markov.chain(numPhrases).join(' '); } return phrase.toLowerCase(); } var PhrasePrompt = require('./phrase_prompt'); var prompt = new PhrasePrompt({ generatePhrase: generatePhrase, displayTime: 1500, inputTime: 10000, complexity: { initial: [2, 10], step: [1, 5], lo: [2, 10], hi: [10, 50] } }); var PromptLoop = require('./prompt_loop'); var loop = new PromptLoop(prompt); var StartStop = require('./start_stop'); var ss = new StartStop(); ss.contentElement.appendChild(prompt.element); document.body.appendChild(ss.element); var history = []; function onResult(result) { // TODO: prune and/or archive history? history.push(result); var k = 3; // TODO setting var lastK = history.slice(-k); var lastKExpired = lastK .reduce(function(allExpired, result) { return allExpired && Boolean(result.expired); }, lastK.length >= k); if (lastKExpired) return ss.stop(); console.log(result); } ss.on('start', loop.start.bind(loop)); ss.on('stop', loop.stop.bind(loop)); ss.addListeners(window); prompt.on('result', onResult);
JavaScript
0.000001
@@ -792,24 +792,72 @@ ime: 10000,%0A + maxErrorPerWord: 2,%0A repromptDelay: 200,%0A complexi
6a5f92d6d72c8cbe1e15f377de8b377bca79ff30
fix csp modification
chrome-extension/background.js
chrome-extension/background.js
/** * The default content security policy for github.com only allows AJAX posts to white-listed domains. * In order to allow us to post to our server, we intercept the content-security-policy header and whitelist our domain. */ chrome.webRequest.onHeadersReceived.addListener(function(details) { for(var i = 0; i < details.responseHeaders.length; ++i) { if (details.responseHeaders[i].name.toLowerCase() == 'content-security-policy') { console.log("Amending content-security-policy for " + details.url) details.responseHeaders[i].value += " whaler-on-fleek.appspot.com" } } return {responseHeaders:details.responseHeaders}; }, { urls: [ '*://github.com/*/pull/*' ] }, [ 'blocking', 'responseHeaders' ]); /** * Randomly generates a 24 character string. */ function getRandomToken() { var array = new Uint32Array(10); window.crypto.getRandomValues(array); var text = ""; for (var i = 0; i < array.length; i++) { text += intToChar(array[i] & 255) text += intToChar((array[i] >> 8 ) & 255) text += intToChar((array[i] >> 16) & 255) text += intToChar((array[i] >> 24) & 255) } return text; } function intToChar(input) { var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return possible.charAt(input % possible.length) } /** * Responds to messages posted by the content script. */ chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.message != "get_session_token") return false; chrome.cookies.get({"url": "https://github.com", "name": "whaler_session"}, function(cookie) { if (cookie == null) { session_id = getRandomToken(); expirationDate = new Date().getTime() / 1000 + 60 * 60 * 24 * 7 // Expire in 1 week chrome.cookies.set({"url": "https://github.com", "name": "whaler_session", "value": session_id, "expirationDate": expirationDate, "secure": true}) } else { session_id = cookie.value } sendResponse({session_token: session_id}); }); return true; // We will respond asynchronously. });
JavaScript
0
@@ -536,16 +536,26 @@ + var csp = details @@ -583,42 +583,150 @@ alue - += %22 whaler-on-fleek.appspot.com%22 +;%0A csp = csp.replace('connect-src', 'connect-src whaler-on-fleek.appspot.com');%0A details.responseHeaders%5Bi%5D.value = csp; %0A
7025074c082adc146b8b7b9a6db745d0be7d613f
Fix stdin processing
bf/index.js
bf/index.js
var Evaluator = require('./evaluator'); var unescape = function unescape(value){ return String(value) .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); } module.exports = function(argv, channel, response, logger) { var input = unescape(argv.slice(1).join('')), inputSplit = input.split(/\"/g); code = inputSplit[0], stdin = inputSplit[1].split('').map(function(c) { return c.charCodeAt(0); }); logger.log('evaluating', code); try { result = ''; Evaluator.bfEval(code, { input: function() { return stdin.shift() || 0; }, output: function(value) { result += String.fromCharCode(value); } }); response.end(result || 'Program produced no output'); } catch(e) { logger.error(e); response.end('Invalid BF program'); } };
JavaScript
0.000087
@@ -425,16 +425,17 @@ stdin = +( inputSpl @@ -439,16 +439,23 @@ Split%5B1%5D + %7C%7C '') .split('
d113834c865f6ef9a5e94c9824d09e4e1742b983
Fix unnamed function ESLint warning
jest.shim.js
jest.shim.js
if (!global.requestAnimationFrame) { global.requestAnimationFrame = function(callback) { setTimeout(callback, 0); }; }
JavaScript
0.999617
@@ -71,16 +71,38 @@ function + requestAnimationFrame (callbac
3dfdc465212392c3f137377e7831eeff4147bf50
Update player when width or height changes
src/ReactPlayer.js
src/ReactPlayer.js
import 'es6-promise' import React, { Component } from 'react' import { propTypes, defaultProps } from './props' import players from './players' export default class ReactPlayer extends Component { static displayName = 'ReactPlayer' static propTypes = propTypes static defaultProps = defaultProps static canPlay (url) { return players.some(player => player.canPlay(url)) } componentDidMount () { this.progress() } componentWillUnmount () { clearTimeout(this.progressTimeout) } shouldComponentUpdate (nextProps) { return ( this.props.url !== nextProps.url || this.props.playing !== nextProps.playing || this.props.volume !== nextProps.volume ) } seekTo = fraction => { const player = this.refs.player if (player) { player.seekTo(fraction) } } progress = () => { if (this.props.url && this.refs.player) { let progress = {} const loaded = this.refs.player.getFractionLoaded() const played = this.refs.player.getFractionPlayed() if (loaded !== null && loaded !== this.prevLoaded) { progress.loaded = this.prevLoaded = loaded } if (played !== null && played !== this.prevPlayed && this.props.playing) { progress.played = this.prevPlayed = played } if (progress.loaded || progress.played) { this.props.onProgress(progress) } } this.progressTimeout = setTimeout(this.progress, this.props.progressFrequency) } renderPlayer = Player => { const active = Player.canPlay(this.props.url) const { youtubeConfig, soundcloudConfig, vimeoConfig, fileConfig, ...activeProps } = this.props const props = active ? { ...activeProps, ref: 'player' } : {} return ( <Player key={Player.displayName} youtubeConfig={youtubeConfig} soundcloudConfig={soundcloudConfig} vimeoConfig={vimeoConfig} fileConfig={fileConfig} {...props} /> ) } render () { const style = { width: this.props.width, height: this.props.height } return ( <div style={style} className={this.props.className}> {players.map(this.renderPlayer)} </div> ) } }
JavaScript
0
@@ -688,17 +688,111 @@ s.volume + %7C%7C%0A this.props.height !== nextProps.height %7C%7C%0A this.props.width !== nextProps.width %0A - )%0A @@ -983,32 +983,8 @@ ) %7B%0A - let progress = %7B%7D%0A @@ -1116,335 +1116,69 @@ ded -!== null && loaded !== this.prevLoaded) %7B%0A progress.loaded = this.prevLoaded = loaded%0A %7D%0A if (played !== null && played !== this.prevPlayed && this.props.playing) %7B%0A progress.played = this.prevPlayed = played%0A %7D%0A if (p +%7C%7C played) %7B%0A this.props.onP rogress -. +(%7B loaded - %7C%7C progress.played) %7B%0A this.props.onProgress(progress +, played %7D )%0A
27f918f76634d500fe2856a61d93741a8db5e487
update tests
frontend/test/unit/specs/people/OrganizationAdd.spec.js
frontend/test/unit/specs/people/OrganizationAdd.spec.js
import { shallow, createLocalVue } from '@vue/test-utils' import Vuex from 'vuex' import OrganizationAdd from '@/registry/components/people/OrganizationAdd.vue' const localVue = createLocalVue() localVue.use(Vuex) describe('OrganizationAdd.vue', () => { let store let getters let mutations let actions beforeEach(() => { getters = { error: () => null } store = new Vuex.Store({ getters, actions, mutations }) }) it('has a title', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) expect(wrapper.find('h5.modal-title').text()).toEqual('Add an Organization') }) it('form has a reset button that clears fields', () => { const wrapper = shallow(OrganizationAdd, { localVue, store, stubs: ['router-link', 'router-view', 'v-select'] }) wrapper.vm.orgForm.name = 'Big Drilling Co' expect(wrapper.vm.orgForm.name).toEqual('Big Drilling Co') wrapper.find('#orgFormResetButton').trigger('reset') expect(wrapper.vm.orgForm.name).toEqual('') }) })
JavaScript
0.000001
@@ -674,22 +674,16 @@ dd a -n Organization + Company ')%0A
ec2e279626ed62572843f92cc872d4ed0d4eb7eb
Update SetState.js
routes/redis/SetState.js
routes/redis/SetState.js
/** * Created by Kun on 6/28/2015. */ //http://www.sitepoint.com/using-redis-node-js/ var express = require("express"); var Q = require('q'); var router = express.Router(); impredis = require("../../imp_services/impredis.js"); router.route('/:stateObject').get(function(req, res) { impredis.set(req.cookies.IMPId, "stateObject",req.params.stateObject,function(result, error){ if(error){ res.send("error: " + error); } else{ res.send("Success"); } }) }); module.exports = router;
JavaScript
0.000001
@@ -227,16 +227,106 @@ js%22);%0A%0A%0A +//TODO Make sure navigation object stringifies and parses stateObject request and response %0Arouter. @@ -638,8 +638,9 @@ router; +%0A
c5fb340fa27ae0b163fbb46fc4481db5598e7c0b
Use consistent method
lib/node_modules/@stdlib/math/base/special/uimuldw/test/test.js
lib/node_modules/@stdlib/math/base/special/uimuldw/test/test.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var uimuldw = require( './../lib' ); // FIXTURES // var data = require( './fixtures/c/data.json' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.strictEqual( typeof uimuldw, 'function', 'main export is a function' ); t.end(); }); tape( 'the function returns `NaN` if provided `NaN`', function test( t ) { var v; v = uimuldw( NaN, 1 ); t.equal( isnan( v ), true, 'returns expected value' ); v = uimuldw( 1, NaN ); t.equal( isnan( v ), true, 'returns expected value' ); v = uimuldw( NaN, NaN ); t.equal( isnan( v ), true, 'returns expected value' ); t.end(); }); tape( 'the function computes the doubleword product of two words, unsigned', function test( t ) { var expected; var actual; var a; var b; var i; a = data.a; b = data.b; expected = data.expected; for ( i = 0; i < expected.length; i++ ) { actual = uimuldw( a[ i ], b[ i ] ); t.deepEqual( actual, expected[ i ], 'returns expected value. a: '+a[i]+'. b: '+b[i]+'. expected: ['+expected[i].join(',')+']'); } t.end(); });
JavaScript
0.000072
@@ -1127,25 +1127,31 @@ aN, 1 );%0A%09t. -e +strictE qual( isnan( @@ -1210,33 +1210,39 @@ w( 1, NaN );%0A%09t. -e +strictE qual( isnan( v ) @@ -1307,17 +1307,23 @@ N );%0A%09t. -e +strictE qual( is @@ -1421,16 +1421,17 @@ e double + word pro @@ -1446,23 +1446,17 @@ two -words, +( unsigned ', f @@ -1451,16 +1451,23 @@ unsigned +) words ', funct
77ef3c180f6bd8f06b357cefd8e2142164cf3618
add item spec
client/js/components/assessments/item.spec.js
client/js/components/assessments/item.spec.js
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react/lib/ReactTestUtils'; import Item from './item'; describe('item', function() { var question = { title:"Test Question Title" }; var currentItemIndex = 0; var assessmentKind = "SUMMATIVE"; var assessment = {}; var questionCount = 10; var nextQuestion = () => {}; var previousQuestion = () => {}; var submitAssessment = () => {}; var result; var subject; var renderItem = () => { result = TestUtils.renderIntoDocument(<Item question={question} currentItemIndex={currentItemIndex} questionCount={questionCount} assessment={assessment} nextQuestion = {nextQuestion} prevQuestion = {previousQuestion} submitAssessment = {submitAssessment} assessment_kind={assessmentKind} />); subject = ReactDOM.findDOMNode(result); }; // Reset variables to default and render an item beforeEach(() => { question = { title:"Test Question Title" }; currentItemIndex = 0; assessmentKind = "SUMMATIVE"; assessment = {}; questionCount = 10; nextQuestion = () => {}; previousQuestion = () => {}; submitAssessment = () => {}; renderItem(); }); it('renders an item', () => { expect(subject.textContent).toContain("Test Question Title"); }); });
JavaScript
0
@@ -178,16 +178,17 @@ item';%0A%0A +f describe @@ -277,35 +277,35 @@ ar c -urrentItemIndex = 0 +heckedResponse = %7B%7D ;%0A var asse @@ -304,36 +304,28 @@ var -assessmentKind = %22SUMMATIVE%22 +currentItemIndex = 0 ;%0A @@ -374,109 +374,8 @@ 10; -%0A var nextQuestion = () =%3E %7B%7D;%0A var previousQuestion = () =%3E %7B%7D;%0A var submitAssessment = () =%3E %7B%7D; %0A%0A @@ -499,24 +499,64 @@ =%7Bquestion%7D%0A + checkedResponse=%7BcheckedResponse%7D%0A curren @@ -655,167 +655,8 @@ nt%7D%0A - nextQuestion = %7BnextQuestion%7D%0A prevQuestion = %7BpreviousQuestion%7D%0A submitAssessment = %7BsubmitAssessment%7D%0A assessment_kind=%7BassessmentKind%7D%0A @@ -870,42 +870,8 @@ 0;%0A - assessmentKind = %22SUMMATIVE%22;%0A @@ -914,103 +914,8 @@ 10; -%0A nextQuestion = () =%3E %7B%7D;%0A previousQuestion = () =%3E %7B%7D;%0A submitAssessment = () =%3E %7B%7D; %0A%0A @@ -1044,12 +1044,1243 @@ %0A %7D);%0A%0A + describe('feedback', () =%3E %7B%0A it('renders correct when item is correct', () =%3E %7B%0A checkedResponse = %7Bcorrect:true, feedback:'Correct answer'%7D;%0A renderItem();%0A%0A expect(subject.textContent).toContain(%22Correct%22);%0A expect(subject.textContent).toContain(%22Correct answer%22);%0A expect(subject.textContent).not.toContain(%22Incorrect%22);%0A expect(subject.textContent).not.toContain(%22Incorrect answer%22);%0A %7D);%0A%0A it('renders incorrect when item is incorrect', () =%3E %7B%0A checkedResponse = %7Bcorrect:false, feedback:'Incorrect answer'%7D;%0A renderItem();%0A%0A expect(subject.textContent).toContain(%22Incorrect%22);%0A expect(subject.textContent).toContain(%22Incorrect answer%22);%0A expect(subject.textContent).not.toContain(%22Correct%22);%0A expect(subject.textContent).not.toContain(%22Correct answer%22);%0A%0A %7D);%0A%0A it('renders without feedback when item is unchecked', () =%3E %7B%0A checkedResponse = %7B%7D;%0A renderItem();%0A%0A expect(subject.textContent).not.toContain(%22Incorrect%22);%0A expect(subject.textContent).not.toContain(%22incorrect answer%22);%0A expect(subject.textContent).not.toContain(%22Correct%22);%0A expect(subject.textContent).not.toContain(%22Correct answer%22);%0A %7D);%0A %7D);%0A%0A %7D);%0A
ce2317029178c6b07c79fb9c5be83a6ead953bd1
tag v0.5.0-beta3
client/js/ng-controllers/versionController.js
client/js/ng-controllers/versionController.js
mainModule.controller('versionController', function($scope, $routeParams, $location, defaultFactory) { // nText app by Dan McKeown | http://danmckeown.info/code/ntext $scope.nVersion = "0.5.0-beta3-dev"; // This is the app version number });
JavaScript
0.000001
@@ -195,12 +195,8 @@ eta3 --dev %22;%09/
aa5af759e0082b16d1e45b6b429c63dd1fd9853c
Add meta options for spawn/shell git exec options
node-services/sencha-cmd/lib/git.js
node-services/sencha-cmd/lib/git.js
"use strict"; var logger = require('./logger'), fs = require('fs'), child_process = require('child_process'); /** * Constructor for git execution wrapper */ var Git = module.exports = function(options) { if (typeof options == 'string') { options = { gitDir: options }; } else if (!options) { options = {}; } this.gitDir = options.gitDir || null; this.workTree = options.workTree || null; }; /** * Execute git command and return trimmed output */ Git.prototype.exec = function(command, options, args, done) { var execArgs = Array.prototype.slice.call(arguments), execOptions = { gitDir: this.gitDir, workTree: this.workTree }, commandArgs = [], gitOptions = {}, gitArgs = [], gitEnv = {}; // reset command, first arg might be an options object command = null; // get callback function done = typeof execArgs[execArgs.length - 1] == 'function' ? execArgs.pop() : null; // scan through all arguments while (execArgs.length) { args = execArgs.shift(); switch (typeof args) { case 'string': if (!command) { command = args; // the first string is the command break; } // fall through and get pushed with numbers case 'number': commandArgs.push(args.toString()); break; case 'object': // extract any exec options if ('$gitDir' in args) { execOptions.gitDir = args.$gitDir; delete args.$gitDir; } if ('$workTree' in args) { execOptions.workTree = args.$workTree; delete args.$workTree; } if ('$nullOnError' in args) { execOptions.nullOnError = args.$nullOnError; delete args.$nullOnError; } if ('$env' in args) { for (let key in args.$env) { gitEnv[key] = args.$env[key]; } delete args.$env; } if ('$indexFile' in args) { gitEnv.GIT_INDEX_FILE = args.$indexFile; delete args.$indexFile; } if ('$options' in args) { for (let key in args.$options) { execOptions[key] = args.$options[key]; } } // any remaiing elements are args/options commandArgs.push.apply(commandArgs, Array.isArray(args) ? args : cliOptionsToArgs(args)); break; default: throw 'unhandled exec argument' } } // sanity check if (typeof command != 'string') { throw 'command required'; } // apply git-level options if (execOptions.gitDir) { gitOptions['git-dir'] = execOptions.gitDir; } if (execOptions.workTree) { gitOptions['work-tree'] = execOptions.workTree; } execOptions.env = gitEnv; // compile git arguments gitArgs.push.apply(gitArgs, cliOptionsToArgs(gitOptions)); // git-level options come first gitArgs.push(command); // command name comes next gitArgs.push.apply(gitArgs, commandArgs);// command-level options come last // execute git command logger.debug('git', gitArgs.join(' ')); if (execOptions.spawn) { return child_process.spawn('git', gitArgs, execOptions); } else if(execOptions.shell) { child_process.exec('git ' + gitArgs.join(' '), execOptions, function (error, stdout, stderr) { if (error) { if (execOptions.nullOnError) { error = null; } else { error.stderr = stderr; } } if (done) { done(error, stdout.trim()); } }); } else { child_process.execFile('git', gitArgs, execOptions, function (error, stdout, stderr) { if (error) { if (execOptions.nullOnError) { error = null; } else { error.stderr = stderr; } } if (done) { done(error, stdout.trim()); } }); } }; /** * @private * Convert an options object into CLI arguments string */ function cliOptionsToArgs(options) { var args = [], k, val; for (k in options) { if (k[0] == '_') { continue; } val = options[k]; if (k.length == 1) { if (val === true) { args.push('-'+k); } else if (val !== false) { args.push('-'+k, val); } } else { if (val === true) { args.push('--'+k); } else if (val !== false) { args.push('--'+k+'='+val); } } } return args; } /** * @static * Gets complete path to git directory */ Git.getGitDirFromEnvironment = function(callback) { Git.prototype.exec('rev-parse', { 'git-dir': true }, function(error, output) { if (error) { return callback(error); } fs.realpath(output, function(error, resolvedPath) { if (error) { return callback(error); } callback(null, resolvedPath); }); }); }; /** * @static * Gets complete path to working tree */ Git.getWorkTreeFromEnvironment = function(callback) { Git.prototype.exec('rev-parse', { 'show-toplevel': true }, function(error, output) { if (error) { return callback(error); } fs.realpath(output, function(error, resolvedPath) { if (error) { return callback(error); } callback(null, resolvedPath); }); }); };
JavaScript
0
@@ -2042,32 +2042,336 @@ %7D%0A%0A + if ('$spawn' in args) %7B%0A execOptions.spawn = args.$spawn;%0A delete args.$spawn;%0A %7D%0A%0A if ('$shell' in args) %7B%0A execOptions.shell = args.$shell;%0A delete args.$shell;%0A %7D%0A%0A
f9ae2c2f1c6d46b0a7e3c07df2a965ba6e9ba2dc
fix example
examples/a.js
examples/a.js
"use strict"; var _ = require("lodash"); var ChangeLog = require("."); var properChange = "openstack (0.99.18-0ubuntu1~14.04.1~bleed1) trusty; urgency=medium\n\n" + " * Fix nclxd\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 25 Jun 2015 10:25:15 -0400\n\n" + "openstack (0.99.17-0ubuntu1~15.10.1~bleed1) wily; urgency=medium\n\n" + " * Fix typo in deploy command\n" + " * Upgrade juju compat\n\n" + " -- Adam Stokes <adam.stokes@ubuntu.com> Fri, 19 Jun 2015 17:01:14 -0400"; // var nonSemVerChange = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400\n\nmacumba (0.5-0ubuntu1) utopic; urgency=medium\n\n * Fix annotations\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Mon, 06 Oct 2014 11:52:49 -0400\n\nmacumba (0.3-0ubuntu1) utopic; urgency=medium\n\n * Add macumba-shell for interactively working with API\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Wed, 20 Aug 2014 12:41:16 -0400\n\nmacumba (0.2-0ubuntu1) utopic; urgency=medium\n\n * better exception handling\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 07 Aug 2014 01:25:49 +0200\n\nmacumba (0.1-0ubuntu1) utopic; urgency=low\n\n * Initial Release\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Tue, 08 Jul 2014 13:26:37 -0500\n"; // var logMultipleBody = "macumba (0.6-0ubuntu1) trusty; urgency=medium\n\n * Fix threaded execution\n * More fixes\n Spans additional line\n * Tartar sauce\n\n -- Adam Stokes <adam.stokes@ubuntu.com> Thu, 14 May 2015 08:43:11 -0400"; var svl = new ChangeLog(properChange); var logs = svl.splitLogs(); var log = _.first(logs); console.log("\n\nInput:"); console.log(log); console.log("Result:"); var model = svl.parse(log); console.log(model);
JavaScript
0
@@ -61,16 +61,17 @@ quire(%22. +. %22);%0A%0Avar
6be0e405f35f06d4cc48e483a621b0d96d3bb1d7
Fix change type typos
test/unit/remote/change.js
test/unit/remote/change.js
const {describe, it} = require('mocha') const remoteChange = require('../../../core/remote/change') describe('remote change sort', () => { it('sort correctly move inside move', () => { const parent = { 'doc': {'path': 'parent/dst/dir'}, 'type': 'FolderMoved', 'was': {'path': 'parent/src/dir'} } const child = { 'doc': {'path': 'parent/dst/dir/subdir/filerenamed'}, 'type': 'FileMoved', 'was': {'path': 'parent/dst/dir/subdir/file'} } const a = [child, parent] remoteChange.sort(a) a.should.deepEqual([parent, child]) }) })
JavaScript
0.000001
@@ -264,25 +264,24 @@ 'FolderMove -d ',%0A 'wa @@ -420,17 +420,16 @@ FileMove -d ',%0A
36ee0b25ccc81d60a52ed79e8f57c974e4a936ab
add new middlewares distinct on content range
ressources/middlewares.js
ressources/middlewares.js
var passport = require('passport'); require('./oauth.js')(passport); module.exports = { delete: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } }, create: { auth: function(req, res, context) { passport.authenticate('bearer', { session: false })(req, res, function() { // this is the function called after auth if(req.user){ context.continue(); } else { context.stop(); } }); } } }; // SCOPE VS context.criteria();
JavaScript
0
@@ -409,16 +409,226 @@ %7D%0A %7D,%0A + list: %7B%0A fetch: %7B%0A before: function (req, res, context) %7B%0A context.options = context.options %7C%7C %7B%7D;%0A context.options.distinct = true;%0A return context.continue;%0A %7D%0A %7D%0A %7D,%0A create
45cf4661b7e2463d9b4740d371112e6b26a6a46b
Add backwards dependency for old connectToStores with deprecation notices
connectToStores.js
connectToStores.js
/** * Copyright 2015, Yahoo Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var React = require('react'); var objectAssign = require('object-assign'); var contextTypes = require('fluxible').contextTypes; var hoistNonReactStatics = require('hoist-non-react-statics'); function createComponent(Component, stores, getStateFromStores, customContextTypes) { var componentName = Component.displayName || Component.name; var componentContextTypes = objectAssign({ getStore: contextTypes.getStore }, customContextTypes); var StoreConnector = React.createClass({ displayName: componentName + 'StoreConnector', contextTypes: componentContextTypes, getInitialState: function getInitialState() { return this.getStateFromStores(); }, componentDidMount: function componentDidMount() { stores.forEach(function storesEach(Store) { this.context.getStore(Store).addChangeListener(this._onStoreChange); }, this); }, componentWillUnmount: function componentWillUnmount() { stores.forEach(function storesEach(Store) { this.context.getStore(Store).removeChangeListener(this._onStoreChange); }, this); }, getStateFromStores: function () { return getStateFromStores(this.context, this.props); }, _onStoreChange: function onStoreChange() { if (this.isMounted()) { this.setState(this.getStateFromStores()); } }, render: function render() { return React.createElement(Component, objectAssign({}, this.props, this.state)); } }); hoistNonReactStatics(StoreConnector, Component); return StoreConnector; } /** * Registers change listeners and retrieves state from stores using the `getStateFromStores` * method. Concept provided by Dan Abramov via * https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750 * * Example: * connectToStores(Component, [FooStore], { * FooStore: function (store, props) { * return { * foo: store.getFoo() * } * } * }) * * Also supports the decorator pattern: * @connectToStores([FooStore], { * FooStore: function (store, props) { * return { * foo: store.getFoo() * } * } * }) * class ConnectedComponent extends React.Component { * render() { * return <div/>; * } * } * * @method connectToStores * @param {React.Component} [Component] component to pass state as props to. * @param {array} stores List of stores to listen for changes * @param {function} getStateFromStores function that receives all stores and should return * the full state object. Receives `stores` hash and component `props` as arguments * @returns {React.Component} or {Function} if using decorator pattern */ module.exports = function connectToStores(Component, stores, getStateFromStores) { // support decorator pattern if (arguments.length === 2) { stores = arguments[0]; getStateFromStores = arguments[1]; return function connectToStoresDecorator(ComponentToDecorate) { return createComponent(ComponentToDecorate, stores, getStateFromStores); }; } return createComponent.apply(null, arguments); };
JavaScript
0
@@ -1378,24 +1378,2534 @@ +if ('function' !== typeof getStateFromStores) %7B%0A //@TODO remove this branch in next minor%0A if ('production' !== process.env.NODE_ENV) %7B%0A console.warn('Using connectToStores with a state getter ' +%0A 'map has been deprecated. Please use the new API as ' +%0A 'documented at ' +%0A 'http://fluxible.io/api/addons/connectToStores.html');%0A %7D%0A var state = %7B%7D;%0A Object.keys(getStateFromStores).forEach(function (storeName) %7B%0A var stateGetter = getStateFromStores%5BstoreName%5D;%0A var store = this.context.getStore(storeName);%0A objectAssign(state, stateGetter(store, this.props));%0A %7D, this);%0A return state;%0A %7D%0A // @TODO remove merged context and pass only context to state getter%0A // in next minor version%0A var storeInstances = %7B%7D;%0A var context = this.context;%0A stores.forEach(function (store) %7B%0A var storeName = store.storeName %7C%7C store.name %7C%7C store;%0A if ('production' !== process.env.NODE_ENV) %7B%0A Object.defineProperty(storeInstances, storeName, %7B%0A get: function () %7B%0A console.warn(componentName + '%5C's connectToStores ' +%0A 'state getter is trying to access ' + storeName +%0A '. connectToStore no longer passes the ' +%0A 'stores to the state getter. The state getter ' +%0A 'signature is now (context, props) and you ' +%0A 'should access the store using ' +%0A '%60context.getStore(' + storeName + ')%60. See ' +%0A 'https://github.com/yahoo/fluxible/pull/124 ' +%0A 'for more details on this change.');%0A return context.getStore(store);%0A %7D%0A %7D);%0A %7D else %7B%0A storeInstances%5BstoreName%5D = this.context.getStore(store);%0A %7D%0A %7D, this);%0A var mergedContext = objectAssign(storeInstances, this.context);%0A return getStateFromStores(mergedContext, this.props);%0A%0A // @TODO just do this in next minor version%0A // return getSt
002532c4211d2923c6189e5ea87e413d5b970881
Handle missing entries in diff.js
bin/diff.js
bin/diff.js
#!/usr/bin/env node /** * Copyright 2012 Google, Inc. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /** * @fileoverview Diff tool. * * @author benvanik@google.com (Ben Vanik) */ var toolRunner = require('./tool-runner'); var util = toolRunner.util; toolRunner.launch(runTool); /** * Diff tool. * @param {!wtf.pal.IPlatform} platform Platform abstraction layer. * @param {!Array.<string>} args Command line arguments. * @return {number|!goog.async.Deferred} Return code or a deferred that is * called back when the tool exits. */ function runTool(platform, args) { var ALIGN_RIGHT = -8; // 8 chars wide, right aligned var inputFile1 = args[0]; var inputFile2 = args[1]; var filterString = args[2]; if (!inputFile1 || !inputFile2) { console.log('usage: diff.js file1.wtf-trace file2.wtf-trace [filter]'); return -1; } console.log('Diffing ' + inputFile1 + ' and ' + inputFile2 + '...'); console.log(''); var filter = null; if (filterString) { filter = new wtf.analysis.EventFilter(filterString); } // Create databases for querying. var db1 = wtf.analysis.loadDatabase(inputFile1); var db2 = wtf.analysis.loadDatabase(inputFile2); // Build event data tables. var table1 = new wtf.analysis.db.EventDataTable(db1, filter); var table2 = new wtf.analysis.db.EventDataTable(db2, filter); // Grab all event types from each table and divide by type. var allInstanceEntryNames = wtf.analysis.db.EventDataTable.getAllEventTypeNames( [table1, table2], wtf.data.EventClass.INSTANCE); var allScopeEntryNames = wtf.analysis.db.EventDataTable.getAllEventTypeNames( [table1, table2], wtf.data.EventClass.SCOPE); // Dump scope events. console.log(util.spaceValues( [ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT], 'Count', 'Total', 'Average')); console.log(''); allScopeEntryNames.sort(function(nameA, nameB) { var entryA1 = table1.getEventTypeEntry(nameA); var entryA2 = table2.getEventTypeEntry(nameA); var diffA = Math.abs(entryA1.getMeanTime() - entryA2.getMeanTime()); var entryB1 = table1.getEventTypeEntry(nameB); var entryB2 = table2.getEventTypeEntry(nameB); var diffB = Math.abs(entryB1.getMeanTime() - entryB2.getMeanTime()); return diffA - diffB; }); for (var n = 0; n < allScopeEntryNames.length; n++) { var eventTypeName = allScopeEntryNames[n]; var entry1 = table1.getEventTypeEntry(eventTypeName); var entry2 = table2.getEventTypeEntry(eventTypeName); var hasEntry1 = entry1 && entry1.getCount(); var hasEntry2 = entry2 && entry2.getCount(); if (!hasEntry1 && !hasEntry2) { continue; } var diff = (hasEntry1 ? entry1.getMeanTime() : 0) - (hasEntry2 ? entry2.getMeanTime() : 0); var color = ''; if (diff < 0) { color = '\033[31m'; } else if (diff > 0) { color = '\033[32m'; } console.log(color + eventTypeName + '\033[0m'); if (hasEntry1) { console.log(util.spaceValues( [ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT], String(entry1.getCount()), wtf.util.formatSmallTime(entry1.getUserTime()), wtf.util.formatSmallTime(entry1.getMeanTime()))); } else { console.log('(not present in input 1)'); } if (hasEntry2) { console.log(util.spaceValues( [ALIGN_RIGHT, ALIGN_RIGHT, ALIGN_RIGHT], String(entry2.getCount()), wtf.util.formatSmallTime(entry2.getUserTime()), wtf.util.formatSmallTime(entry2.getMeanTime()))); } else { console.log('(not present in input 2)'); } console.log(''); // drawDistribution(entry1.getDistribution()); // drawDistribution(entry2.getDistribution()); } db1.dispose(); db2.dispose(); return 0; }; function drawDistribution(buckets) { var first = buckets.length; var last = 0; var max = Number.MIN_VALUE; for (var n = 0; n < buckets.length; n++) { var value = buckets[n]; if (value) { first = Math.min(first, n); last = Math.max(last, n); max = Math.max(max, value); } } var span = last - first; for (var n = first; n <= last; n++) { var value = buckets[n]; var line = util.pad(n, -3) + 'ms - ' + util.pad(value, -4) + ': '; if (value) { var span = []; for (var m = 0; m < value; m++) { span.push('-'); } span.push('*'); line += span.join(''); } console.log(line); } };
JavaScript
0.000006
@@ -2115,24 +2115,35 @@ = Math.abs( +(entryA1 ? entryA1.getM @@ -2148,25 +2148,66 @@ tMeanTime() -- +: 0) -%0A (entryA2 ? entryA2.get @@ -2212,24 +2212,29 @@ etMeanTime() + : 0) );%0A var e @@ -2351,16 +2351,27 @@ ath.abs( +(entryB1 ? entryB1. @@ -2384,17 +2384,58 @@ nTime() -- +: 0) -%0A (entryB2 ? entryB2 @@ -2448,16 +2448,21 @@ anTime() + : 0) );%0A r
53d5700946baba9d535cc4493f6bcd8e6b52e9a7
Add view-header element for settings view
client/src/js/settings/components/Settings.js
client/src/js/settings/components/Settings.js
/** * * * @copyright 2017 Government of Canada * @license MIT * @author igboyes * */ import React from "react"; import { connect } from "react-redux"; import { withRouter, Switch, Redirect, Route } from "react-router-dom"; import { Nav, NavItem } from "react-bootstrap"; import { LinkContainer } from "react-router-bootstrap"; import SourceTypes from "./General/SourceTypes"; import InternalControl from "./General/InternalControl"; import UniqueNames from "./General/UniqueNames"; import SamplePermissions from "./General/SamplePermissions"; import HTTP from "./Server/HTTP"; import SSL from "./Server/SSL"; import Data from "./Data"; import Resources from "./Jobs/Resources"; import Tasks from "./Jobs/Tasks"; import Users from "../users/components/Users"; const General = () => ( <div> <SourceTypes /> <InternalControl /> <UniqueNames /> <SamplePermissions /> </div> ); const Server = () => ( <div> <HTTP /> <SSL /> </div> ); const Jobs = () => ( <div> <Resources /> <Tasks /> </div> ); const Settings = () => { return ( <div className="container"> <Nav bsStyle="tabs"> <LinkContainer to="/settings/general"> <NavItem>General</NavItem> </LinkContainer> <LinkContainer to="/settings/server"> <NavItem>Server</NavItem> </LinkContainer> <LinkContainer to="/settings/data"> <NavItem>Data</NavItem> </LinkContainer> <LinkContainer to="/settings/jobs"> <NavItem>Jobs</NavItem> </LinkContainer> <LinkContainer to="/settings/users"> <NavItem>Users</NavItem> </LinkContainer> </Nav> <Switch> <Redirect from="/settings" to="/settings/general" exact /> <Route path="/settings/general" component={General} /> <Route path="/settings/server" component={Server} /> <Route path="/settings/data" component={Data} /> <Route path="/settings/jobs" component={Jobs} /> <Route path="/settings/users" component={Users} /> </Switch> </div> ); }; Settings.propTypes = { source_types: React.PropTypes.object, get: React.PropTypes.func }; const mapStateToProps = (state) => { return { restrictSourceTypes: state.settings.data.restrict_source_types, allowedSourceTypes: state.settings.data.allowed_source_types }; }; const SettingsContainer = withRouter(connect( mapStateToProps )(Settings)); export default SettingsContainer;
JavaScript
0
@@ -1154,24 +1154,164 @@ container%22%3E%0A + %3Ch3 className=%22view-header%22%3E%0A %3Cstrong%3E%0A Settings%0A %3C/strong%3E%0A %3C/h3%3E%0A%0A
363703f81cf5be01e99ad04f9bcd0adde8404f28
Enable button after wromg file type
buckets/static/buckets/js/script.js
buckets/static/buckets/js/script.js
(function () { function getParentByTagName(el, tagName) { var p = el.parentElement; if (p.tagName === tagName.toUpperCase()) { return p; } else { return getParentByTagName(p, tagName); } } var uploads = 0; function disableSubmit(el, status) { if (status) uploads++; else uploads--; var form = getParentByTagName(el, 'form'); var submitBtn = form.querySelector('[type="submit"]'); submitBtn.disabled = (uploads > 0); } function error(el, msg) { el.querySelector('.file-url').value = ''; el.querySelector('.file-input').value = ''; if (errs = el.querySelector('.errors')) { errs.remove(); } var errorList = document.createElement('ul'); errorList.setAttribute('class', 'errors'); var errorMessage = document.createElement('li'); errorMessage.appendChild(document.createTextNode(msg)) errorList.appendChild(errorMessage); el.insertBefore(errorList, el.firstChild); } function update(el, fileUrl) { var link = el.querySelector('.file-link'), url = el.querySelector('.file-url'); if (errs = el.querySelector('.errors')) { errs.remove(); } url.value = fileUrl; link.href = fileUrl; link.innerHTML = fileUrl.split('/').pop(); el.classList.add('uploaded'); } function getCookie(name) { var value = '; ' + document.cookie, parts = value.split('; ' + name + '=') if (parts.length == 2) return parts.pop().split(';').shift() } function request(method, url, data, headers, el, callback) { var req = new XMLHttpRequest(); req.open(method, url, true); Object.keys(headers).forEach(function(key){ req.setRequestHeader(key, headers[key]) }); req.onload = function() { disableSubmit(el, false) callback(req.status, req.responseText); } req.onerror = req.onabort = function() { disableSubmit(el, false) error(el, 'Not able to upload file'); } req.send(data) } function uploadFile(e, data) { var el = e.target.parentElement, file = el.querySelector('.file-input').files[0], formData = new FormData(), headers = {'X-CSRFToken': getCookie('csrftoken')}; var url = data.url; Object.keys(data.fields).forEach(function(key){ formData.append(key, data.fields[key]) }) formData.append('file', file); request('POST', url, formData, headers, el, function(status, xml) { if (status !== 204) { error(el, 'Not able to upload file') } else { var fileUrl = data.url + '/' + data.fields.key; update(el, fileUrl); } }); } function getSignedUrl(e) { var el = e.target.parentElement, file = el.querySelector('.file-input').files[0], form = new FormData(), headers = {'X-CSRFToken': getCookie('csrftoken')}, url = '/s3/signed-url/'; var key = file.name; if (el.getAttribute('data-upload-to')) { key = el.getAttribute('data-upload-to') + '/' + key; } form.append('key', key); request('POST', url, form, headers, el, function(status, response) { if (status !== 200) { error(el, 'Not able to upload file') } else { uploadFile(e, JSON.parse(response)); } }); } function checkType(e) { var el = e.target.parentElement, file = el.querySelector('.file-input').files[0], accepted = el.getAttribute('data-accepted-types').split(','); disableSubmit(el, true); if (accepted.indexOf(file.type) !== -1) { getSignedUrl(e); } else { error(el, 'File type not allowed.') } } function removeFile(e) { e.preventDefault(); var el = e.target.parentElement.parentElement; el.querySelector('.file-url').value = ''; el.querySelector('.file-input').value = ''; el.classList.remove('uploaded'); } function addEventHandlers(el) { var input = el.querySelector('.file-input'), remove = el.querySelector('.file-remove'); input.addEventListener('change', checkType, false); remove.addEventListener('click', removeFile, false); } document.addEventListener('DOMContentLoaded', function(e) { ;[].forEach.call(document.querySelectorAll('.s3-buckets'), addEventHandlers) }) document.addEventListener('DOMNodeInserted', function(e){ if(e.target.tagName) { var el = e.target.querySelector('.s3-buckets') if(el) addEventHandlers(el) } }) }());
JavaScript
0
@@ -4066,16 +4066,55 @@ lowed.') +;%0A disableSubmit(el, false); %0A
8f5c299e190bc301f8e29910a7414146e1923500
clear precache thread on destroy
client/js/modules/imaging/views/imagehistory.js
client/js/modules/imaging/views/imagehistory.js
define(['marionette', 'utils/xhrimage', 'tpl!templates/imaging/imagehistory.html', 'tpl!templates/imaging/imagehistorymin.html' ], function(Marionette, XHRImage, template, templatemin) { var ThumbView = Marionette.ItemView.extend({ tagName: 'figure', template: _.template('<a href="/containers/cid/<%=CONTAINERID%>/iid/<%=CONTAINERINSPECTIONID%>/sid/<%=BLSAMPLEID%>"><img /></a><figcaption>+<%=DELTA%>d</figcaption>'), events: { 'mouseover': 'hover', }, hover: function(e) { console.log('hover') this.model.set({isSelected: true}); this.model.collection.trigger('selected:change', this.model) }, initialize: function(options) { this.model.on('change:isSelected', this.onSelectedChanged.bind(this)) var self = this this.img = new XHRImage() this.img.onload = function() { self.$el.find('img').attr('src', self.img.src) } this.img.load(this.model.urlFor()) }, onSelectedChanged: function() { this.model.get('isSelected') ? this.$el.addClass('selected') : this.$el.removeClass('selected') }, onRender: function() { if (this.model.get('isSelected')) this.$el.addClass('selected') }, }) var ThumbsView = Marionette.CollectionView.extend({ childView: ThumbView, }) return Marionette.LayoutView.extend({ // template: template, getTemplate: function() { return this.getOption('embed') ? templatemin : template }, className: function() { return 'img_history' + (this.getOption('embed') ? ' embed' : '') }, regions: { thm: '.columns', }, // setSampleId: function(id) { // this.blsampleid = id // if (id) this.images.fetch() // }, // getSampleId: function() { // return this.blsampleid // }, initialize: function(options) { this.caching = true this.images = options.historyimages this.listenTo(this.images, 'sync', this.preCache.bind(this,1)) //this.images.fetch() }, onRender: function() { this.thm.show(new ThumbsView({ collection: this.images })) }, preCache: function(n) { clearTimeout(this.cachethread) var self = this var i = this.images.at(n) if (this.caching && i) { var xhr = new XHRImage() console.log('caching history', i.urlFor('hd')) xhr.load(i.urlFor('full'), function() { self.cachethread = setTimeout(function() { self.preCache(++n) }, 500) }) } }, onDestroy: function() { this.caching = false }, }) })
JavaScript
0
@@ -3148,32 +3148,75 @@ y: function() %7B%0A + clearTimeout(this.cachethread)%0A this
434402dfe84617e8334cf16ba0dda9b723b37b32
remove todo that was completed in a previous refactor
public/app/components/home/home-controller.js
public/app/components/home/home-controller.js
angular.module('app.home', []) .controller('HomeController', function($scope, $rootScope, $window, $location, $state, $http, $timeout, Utilities, Posts) { 'use strict'; // get recent posts to display on home page // TODO: change when this fires so it only happens on home page (controller reorg?) Posts.getRecent() .success(function(data) { $scope.posts = data; }) .error(function(err) { console.error(err); }); $scope.scrollDown = function() { Utilities.scrollTo(document.body, document.getElementById('main').offsetTop, 800); }; // some static data for home page $scope.contact = { "email": "ianlamb32@gmail.com", "phone": "+1 519-902-6533", "location": { "name": "London, ON", "latLng": [42.9837, -81.2497] } }; $scope.projects = [ { name: 'GoodLife Fitness Sales', url: 'http://www.goodlifefitness.com/training-programs/team-training/camps/ontario/london', repo: '', image: 'glf-sales-opt.png', desc: 'Sales engine for selling GoodLife team training contracts online' }, { name: 'Store Finder', url: 'http://apps.ianlamb.com/storefinder/', repo: 'https://github.com/ianlamb/storefinder', image: 'store-finder-opt.png', desc: 'Component for selecting stores from a large network' }, { name: 'Tempus Notes', url: 'http://notes.ianlamb.com/', repo: 'https://github.com/ianlamb/notes', image: 'tempus-notes-opt.png', desc: 'A very simple note-taker, great for remembering what you did for daily scrum' }, { name: 'Dark Souls Challenge Runs', url: 'http://darksouls.ianlamb.com/challenges', repo: 'https://github.com/ianlamb/darksouls-challenges', image: 'dscrgen-opt.png', desc: 'A fun little randomizer for Dark Souls challenge runs' }, { name: 'Z-Code', url: 'http://zcode.ianlamb.com/', repo: 'https://github.com/ianlamb/zcode', image: 'zcode-opt.png', desc: 'HTML5 game that my buddy and I made in college' }, { name: 'Creekside Landscaping', url: 'http://www.creeksidelandscaping.ca/', repo: '', image: 'creekside-landscaping-opt.png', desc: 'WordPress redesign for my neighbour\'s landscaping business' } ]; });
JavaScript
0
@@ -243,100 +243,8 @@ age%0A - // TODO: change when this fires so it only happens on home page (controller reorg?)%0A
d62f015d188313b416631cf015604f27b7313b19
fix summary not clickable on dashboards
layouts/dashboards/selectors.js
layouts/dashboards/selectors.js
import { createSelector, createStructuredSelector } from 'reselect'; import upperFirst from 'lodash/upperFirst'; import { encodeQueryParams } from 'utils/url'; import { filterWidgetsByLocation, getWidgetCategories, getActiveCategory, } from 'components/widgets/selectors'; import { getActiveArea } from 'providers/areas-provider/selectors'; import CATEGORIES from 'data/categories.json'; // get list data const selectShowMap = (state) => state.widgets?.showMap; const selectLocation = (state) => state.location; const selectLocationType = (state) => state.location && state.location.payload && state.location.payload.type; const selectCategory = (state) => (state.location && state.location.query && state.location.query.category) || 'summary'; export const selectQuery = (state) => state.location && state.location.query; export const getEmbed = createSelector( [selectLocation], (location) => location && location.pathname.includes('/embed') ); export const getWidgetAnchor = createSelector( [selectQuery, filterWidgetsByLocation], (query, widgets) => { const { scrollTo } = query || {}; const hasWidget = widgets && widgets.length && widgets.find((w) => w.widget === scrollTo); return hasWidget ? document.getElementById(scrollTo) : null; } ); export const getNoWidgetsMessage = createSelector( [selectCategory], (category) => `${upperFirst(category)} data for {location} coming soon` ); export const getLinks = createSelector( [getWidgetCategories, getActiveCategory, selectLocation], (widgetCats, activeCategory, location) => { const serializePayload = Object.values(location.payload).filter( (p) => p && p.length ); function formatQuery(category) { const encodedQueryString = encodeQueryParams({ ...location.query, ...(category.value !== 'summary' && { category: category.value, }), }); return encodedQueryString.length > 0 ? `?${encodedQueryString}` : ''; } if (!widgetCats || widgetCats?.length === 0) { return CATEGORIES.map((category) => ({ label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, })); } return CATEGORIES.filter((c) => widgetCats.includes(c.value)).map( (category) => { return { label: category.label, category: category.value, href: location.pathname, shallow: true, as: `${location.pathname.replace( '[[...location]]', serializePayload.join('/') )}${formatQuery(category)}`, active: activeCategory === category.value, }; } ); } ); export const getDashboardsProps = createStructuredSelector({ showMapMobile: selectShowMap, category: getActiveCategory, links: getLinks, widgetAnchor: getWidgetAnchor, noWidgetsMessage: getNoWidgetsMessage, locationType: selectLocationType, activeArea: getActiveArea, widgets: filterWidgetsByLocation, });
JavaScript
0.000003
@@ -1898,16 +1898,105 @@ %7D),%0A + ...(category.value === 'summary' && %7B%0A category: undefined,%0A %7D),%0A %7D)
e0d37a79655947ca31eb869e3d52fbedf8d018a1
Fix deployedUrl.
upload.js
upload.js
import archiver from 'archiver' import fs from 'mz/fs' import path from 'path' import {run} from 'yacol' import http from 'http' import https from 'https' import e from './env.js' import parseArgs from 'minimist' import fetch from 'node-fetch' const {bool, env, getErrors} = e() const request = (bool('HTTPS') ? https : http).request function* ignore(folder) { const ignoreFile = path.join(folder, '.docsignore') const parse = (f) => f.split('\n') .map((s) => s.trim()) .filter((s) => !s.match(/^#/) && s !== '') return yield run(function*() { return parse(yield fs.readFile(ignoreFile, 'utf-8')) }).catch((e) => { if (e.code === 'ENOENT') return [] else throw e }) } function response() { let resolve, reject return { promise: new Promise((res, rej) => { resolve = res reject = rej }), callback: (res) => { const data = [] res.on('data', (d) => data.push(d)) res.on('error', (e) => reject(e)) res.on('end', () => resolve({...res, body: data.join('')})) } } } function baseUrl() { const protocol = bool('HTTPS') ? 'https:' : 'http:' const defaultPorts = {'http:': '80', 'https:': '443'} const portPart = env('PORT') !== defaultPorts[protocol] ? `:${env('PORT')}` : '' return `${protocol}//${env('HOST')}${portPart}` } const deployedUrl = (docId, isDraft) => `${baseUrl()}/${isDraft ? 'drafts' : 'docs'}/${docId}/` function* upload(folder) { const archive = archiver('zip') const {promise, callback} = response() const uploadReq = request({ host: env('HOST'), port: env('PORT'), path: '/$upload', method: 'POST', headers: { 'Authorization': env('API_KEY'), }, }, callback) getErrors() uploadReq.on('close', () => uploadReq.end()) archive.pipe(uploadReq) archive.glob('**/*', { dot: false, cwd: folder, ignore: yield run(ignore, folder) }) archive.finalize() const result = yield promise if (result.statusCode !== 200) { throw new Error(`Server returned: HTTP ${result.statusCode} -- ${result.body}`) } else{ console.log(`Deploy successful on ${deployedUrl(result.body, true)}`) return result.body } } function* link(folder, docId) { const configFile = path.join(folder, 'docs.json') const config = JSON.parse(yield fs.readFile(configFile, 'utf-8')) if (!config.alias) throw new Error(`Alias not defined in ${configFile}`) const url = `${baseUrl()}/$alias/${docId}/${config.alias}` const result = yield fetch(url, { method: 'PUT', headers: {'Authorization': env('API_KEY')} }) if (result.status !== 200) { const body = yield result.text() throw new Error(`Server returned: HTTP ${result.status} -- ${body}`) } else{ console.log(`Deploy successful on ${deployedUrl(config.alias, false)}`) return result.body } } const args = parseArgs(process.argv.slice(2), { alias: {'alias': 'a'}, 'boolean': ['alias'], }) const folder = args['_'][0] if (!folder) { console.log(`usage: yarn run upload -- [-a] folder`) process.exit(0) } run(function* () { const docId = yield run(upload, folder) if (args.alias) { yield run(link, folder, docId) } })
JavaScript
0
@@ -1373,17 +1373,16 @@ seUrl()%7D -/ $%7BisDraf @@ -1386,16 +1386,18 @@ raft ? ' +/$ drafts' @@ -1399,20 +1399,16 @@ fts' : ' -docs '%7D/$%7Bdoc
c57c4b4b6a0aaa4478c9cc241eb9d780de8496eb
Update list_metadata_parser.js
test/core/list_metadata_parser.js
test/core/list_metadata_parser.js
require('../initialize-globals').load(); var listMetadataParser = require('../../lib/core/list_metadata_parser'); describe('# list_metadata_parser', function() { describe("##createListMetadatasOptions", function() { it('GET', function() { var meta = { top: 10, skip: 23, sortFieldName: "colA", sortDesc: true }; var ajaxOptions = listMetadataParser.load({ criteria: { name: "pierre", age: 27 }, metadata: meta }, { url: "http://test.com" }); console.log("ajaxOptions", ajaxOptions); ajaxOptions.url.should.be.a.string; for (var m in meta) { ajaxOptions.url.indexOf(m).should.not.be.equal(-1); } }); }); });
JavaScript
0.000002
@@ -217,16 +217,21 @@ %7B%0A it +.skip ('GET', @@ -764,8 +764,9 @@ %7D);%0A%7D); +%0A
748cbd48a2c0558a6f653aa92773493dc146fcec
fix typo
client/app/pods/media/route.js
client/app/pods/media/route.js
/* Single Ember.js Route that will work for all media types */ import Ember from 'ember'; import DataRotueErrorMixin from 'client/mixins/data-route-error'; const { Route, get } = Ember; // TODO: Figure out if different media types should just use different // templates, or if they should not share any code at all. export default Route.extend(DataRotueErrorMixin, { model(params) { return this.store.findRecord('user', params.mediaSlug); }, serialize(model) { return { mediaType: model.constructor.modelName, mediaSlug: get(model, 'slug') }; } });
JavaScript
0.001084
@@ -94,26 +94,26 @@ mport DataRo -t u +t eErrorMixin @@ -351,18 +351,18 @@ d(DataRo -t u +t eErrorMi
98710a45424dafe5164d212207c5102044ac3e74
fix `unflatten` for sequenced/defaulted args
runtime-js/functions2.js
runtime-js/functions2.js
var exports=null;//IGNORE function String$(a,b){}//IGNORE function StringBuilder(){}//IGNORE function string(/*Iterable<Character>*/chars) { if (chars === undefined) return String$('',0); var s = StringBuilder(); var iter = chars.iterator(); var c; while ((c = iter.next()) !== getFinished()) { s.appendCharacter(c); } return s.string; } function internalSort(comp, elems, $$$mptypes) { if (elems===undefined) {return getEmpty();} var arr = []; var it = elems.iterator(); var e; while ((e=it.next()) !== getFinished()) {arr.push(e);} if (arr.length === 0) {return getEmpty();} arr.sort(function(a, b) { var cmp = comp(a,b); return (cmp===larger) ? 1 : ((cmp===smaller) ? -1 : 0); }); return ArraySequence(arr, $$$mptypes); } exports.string=string; function flatten(tf, $$$mptypes) { var rf = function() { var t = getEmpty(); var e = null; var argc = arguments.length; var last = argc>0 ? arguments[argc-1] : undefined; if (typeof(last) === 'object' && typeof(last.Args) === 'object' && typeof(last.Args.t) === 'function') { argc--; } for (var i=0; i < argc; i++) { var c = arguments[i]===null ? Null : arguments[i] === undefined ? Empty : arguments[i].getT$all ? arguments[i].getT$all() : Anything; if (e === null) { e = c; } else if (e.t === 'u' && e.l.length > 0) { var l = [c]; for (var j=0; j < e.l.length; j++) { l[j+1] = e.l[j]; } } else { e = {t:'u', l:[e, c]}; } var rest; if (t === getEmpty()) { rest={t:Empty}; } else { rest={t:Tuple, a:t.$$$targs$$$}; } t = Tuple(arguments[i], t, {First:c, Element:e, Rest:rest}); } return tf(t, t.$$targs$$); }; rf.$$targs$$=$$$mptypes; return rf; } function unflatten(ff, $$$mptypes) { if (ff.$$metamodel$$ && ff.$$metamodel$$['$ps']) { var ru = function ru(seq) { if (seq===undefined || seq.size === 0) { return ff(); } var pmeta = ff.$$metamodel$$['$ps']; var a = []; for (var i = 0; i < pmeta.length; i++) { if (pmeta[i]['seq'] == 1) { a[i] = seq.skipping(i).sequence; } else { a[i] = seq.get(i); } } a[i]=ru.$$targs$$; return ff.apply(ru, a); } } else { var ru = function ru(seq) { if (seq===undefined || seq.size === 0) { return ff(); } var a = []; for (var i = 0; i < seq.size; i++) { a[i] = seq.get(i); } a[i]=ru.$$targs$$; return ff.apply(ru, a); } } ru.$$targs$$=$$$mptypes; return ru; } exports.flatten=flatten; exports.unflatten=unflatten; //internal function toTuple(iterable) { var seq = iterable.sequence; return Tuple(seq.first, seq.rest.sequence, {First:seq.$$targs$$.Element, Element:seq.$$targs$$.Element, Rest:{t:Sequential, a:seq.$$targs$$}}); } exports.toTuple=toTuple; function integerRangeByIterable(range, step, $$$mptypes) { return Comprehension(function(){ var a = range.first; var b = range.last; if (a>b) { a += step; return function() { a -= step; return a<b ? getFinished() : a; } } a-=step; return function() { a += step; return a>b ? getFinished() : a; } }, {Element:range.$$targs$$.Element, Absent:range.$$targs$$.Absent}); } exports.integerRangeByIterable=integerRangeByIterable;
JavaScript
0.000002
@@ -2510,32 +2510,50 @@ %7D else + if (seq.size %3E i) %7B%0A @@ -2570,32 +2570,95 @@ %5D = seq.get(i);%0A + %7D else %7B%0A a%5Bi%5D = undefined;%0A
b6f23172ccb9da4549d7e1c691d07e8973f1e430
Fix podcast publisher not showing in podcast detail view
public/app/js/cbus-server-get-podcast-info.js
public/app/js/cbus-server-get-podcast-info.js
if (!cbus.hasOwnProperty("server")) { cbus.server = {} } (function() { cbus.server.getPodcastInfo = function(podcastUrl, callback) { var podcastData = {}; xhr({ url: podcastUrl, // headers: cbus.const.REQUEST_HEADERS }, function(err, result, body) { if (err) { callback(null) } else { let parser = new DOMParser(); let doc = parser.parseFromString(body, "application/xml"); if (doc.documentElement.nodeName === "parsererror") { console.log("error parsing xml", err); callback(null) } else { let channel = doc.querySelector("rss channel"); // title let titleElem = channel.getElementsByTagName("title")[0]; if (titleElem) { podcastData.title = titleElem.textContent.trim(); } // publisher let authorElem = channel.getElementsByTagName("author")[0]; if (authorElem && authorElem.tagName === "itunes:author") { podcastData.publisher = authorElem.textContent; } // description let descriptionElem = channel.getElementsByTagName("description")[0]; if (descriptionElem) { podcastData.description = descriptionElem.textContent; } // image let imageElems = doc.querySelectorAll("rss channel > image"); for (let i = 0, l = imageElems.length; i < l; i++) { let imageElem = imageElems[i]; if (imageElem.tagName === "image" && imageElem.getElementsByTagName("url")[0]) { podcastData.image = imageElem.getElementsByTagName("url")[0].textContent; } else if (imageElem.tagName === "itunes:image") { podcastData.image = imageElem.getAttribute("href"); } } callback(podcastData); } } }); } }());
JavaScript
0
@@ -940,16 +940,23 @@ agName(%22 +itunes: author%22) @@ -989,50 +989,8 @@ Elem - && authorElem.tagName === %22itunes:author%22 ) %7B%0D
b7e97954668783e49d80f717d0ae7343ca3a54e2
make modal donation text dynamic (#38462)
client/src/components/Donation/DonationModal.js
client/src/components/Donation/DonationModal.js
/* eslint-disable max-len */ import React from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { Modal, Button, Col, Row } from '@freecodecamp/react-bootstrap'; import { Spacer } from '../helpers'; import { blockNameify } from '../../../utils/blockNameify'; import Heart from '../../assets/icons/Heart'; import Cup from '../../assets/icons/Cup'; import MinimalDonateForm from './MinimalDonateForm'; import { closeDonationModal, isDonationModalOpenSelector, isBlockDonationModalSelector, executeGA } from '../../redux'; import { challengeMetaSelector } from '../../templates/Challenges/redux'; import './Donation.css'; const mapStateToProps = createSelector( isDonationModalOpenSelector, challengeMetaSelector, isBlockDonationModalSelector, (show, { block }, isBlockDonation) => ({ show, block, isBlockDonation }) ); const mapDispatchToProps = dispatch => bindActionCreators( { closeDonationModal, executeGA }, dispatch ); const propTypes = { activeDonors: PropTypes.number, block: PropTypes.string, closeDonationModal: PropTypes.func.isRequired, executeGA: PropTypes.func, isBlockDonation: PropTypes.bool, show: PropTypes.bool }; function DonateModal({ show, block, isBlockDonation, closeDonationModal, executeGA }) { const [closeLabel, setCloseLabel] = React.useState(false); const handleProcessing = ( duration, amount, action = 'stripe form submission' ) => { executeGA({ type: 'event', data: { category: 'donation', action: `Modal ${action}`, label: duration, value: amount } }); setCloseLabel(true); }; if (show) { executeGA({ type: 'modal', data: '/donation-modal' }); executeGA({ type: 'event', data: { category: 'Donation', action: `Displayed ${ isBlockDonation ? 'block' : 'progress' } donation modal`, nonInteraction: true } }); } const donationText = <b>Become an annual supporter of our nonprofit.</b>; const blockDonationText = ( <div className='block-modal-text'> <div className='donation-icon-container'> <Cup className='donation-icon' /> </div> <Row> {!closeLabel && ( <Col sm={10} smOffset={1} xs={12}> <b>Nicely done. You just completed {blockNameify(block)}. </b> <br /> {donationText} </Col> )} </Row> </div> ); const progressDonationText = ( <div className='text-center progress-modal-text'> <div className='donation-icon-container'> <Heart className='donation-icon' /> </div> <Row> {!closeLabel && ( <Col sm={10} smOffset={1} xs={12}> {donationText} </Col> )} </Row> </div> ); return ( <Modal bsSize='lg' className='donation-modal' show={show}> <Modal.Body> {isBlockDonation ? blockDonationText : progressDonationText} <Spacer /> <MinimalDonateForm handleProcessing={handleProcessing} /> <Spacer /> <Row> <Col sm={4} smOffset={4} xs={8} xsOffset={2}> <Button block={true} bsSize='sm' bsStyle='primary' className='btn-link' onClick={closeDonationModal} tabIndex='0' > {closeLabel ? 'Close' : 'Ask me later'} </Button> </Col> </Row> </Modal.Body> </Modal> ); } DonateModal.displayName = 'DonateModal'; DonateModal.propTypes = propTypes; export default connect( mapStateToProps, mapDispatchToProps )(DonateModal);
JavaScript
0
@@ -521,16 +521,96 @@ teForm'; +%0Aimport %7B modalDefaultStateConfig %7D from '../../../../config/donation-settings'; %0A%0Aimport @@ -2204,41 +2204,374 @@ st d -onationText = %3Cb%3EBecome an annual +urationToText = donationDuration =%3E %7B%0A if (donationDuration === 'onetime') return 'a one-time';%0A else if (donationDuration === 'month') return 'a monthly';%0A else if (donationDuration === 'year') return 'an annual';%0A else return 'a';%0A %7D;%0A%0A const donationText = (%0A %3Cb%3E%0A Become %7BdurationToText(modalDefaultStateConfig.donationDuration)%7D%7B' '%7D%0A sup @@ -2594,20 +2594,29 @@ nprofit. -%3C/b%3E +%0A %3C/b%3E%0A ) ;%0A cons
5fdd6483d7346751b297b6f6ec16cf591507de8d
remove rate persent
src/js/components/Transaction/ExchangeForm.js
src/js/components/Transaction/ExchangeForm.js
import React from "react" import { roundingNumber } from "../../utils/converter" const ExchangeForm = (props) => { var errorToken = props.errors.selectSameToken + props.errors.selectTokenToken var tokenRate = props.isSelectToken ? <img src="/assets/img/waiting.svg" /> : props.exchangeRate.rate var render = ( <div> <div class="frame"> <div class="row"> <div class="column small-11 medium-10 large-8 small-centered"> <h1 class="title">Exchange</h1> <form action="#" method="get"> <div class="row"> <div class="column medium-6"> <label style={{marginBottom: 0}}>Exchange From <div className={errorToken === "" && props.errors.sourceAmount === "" ? "token-input" : "token-input error"}> <input type={props.input.sourceAmount.type} className="source-input" value={props.input.sourceAmount.value} onFocus={() => props.input.sourceAmount.onFocus()} onChange={(e) => props.input.sourceAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {props.tokenSource} </div> {errorToken !== "" && <span class="error-text">{errorToken}</span> } {props.errors.sourceAmount !== "" && <span class="error-text">{props.errors.sourceAmount}</span> } </label> <div class="address-balance" style={{marginBottom: 40}}> <span class="note">Address Balance</span> <a className="value" onClick={props.setAmount} title={props.balance.value}> {props.balance.roundingValue} {props.sourceTokenSymbol} </a> </div> </div> <div class="column medium-6"> <label>Exchange To <div class="token-input"> <input type={props.input.destAmount.type} value={props.input.destAmount.value} onFocus={() => props.input.destAmount.onFocus()} onChange={(e) => props.input.destAmount.onChange(e)} min="0" step="0.000001" placeholder="0" /> {/* <div class="info" data-open="exchange-to-token-modal"><img src="/assets/img/omg.svg"/><span class="name">OMG</span></div> */} {props.tokenDest} </div> </label> </div> </div> <div class="row"> <div class="column"> <p class="token-compare" title={tokenRate}> 1 {props.exchangeRate.sourceToken} = {roundingNumber(tokenRate)} {props.exchangeRate.destToken} <span class="up">{props.exchangeRate.percent}%</span> </p> </div> </div> {props.step === 2 && <div class="row hide-on-choose-token-pair"> <div class="column"> <div class="clearfix"> <div class="advanced-switch base-line float-right"> <div class="switch accent"> <input class="switch-input" id="advanced" type="checkbox" /> <label class="switch-paddle" for="advanced"><span class="show-for-sr">Advanced Mode</span></label> </div> <label class="switch-caption" for="advanced">Advanced</label> </div> </div> <div class="advanced-content" disabled> {props.gasConfig} </div> </div> </div> } </form> </div> </div> </div> {props.exchangeButton} {props.selectTokenModal} </div> ) return ( <div className={props.step === 1 ? "choose-token-pair" : ""} id="exchange"> {props.step !== 3 ? render : ''} <div class="page-3"> {props.step == 3 ? props.trasactionLoadingScreen : ''} </div> </div> ) } export default ExchangeForm
JavaScript
0.000005
@@ -2784,32 +2784,36 @@ + %7B/* %3Cspan class=%22up @@ -2846,24 +2846,28 @@ ent%7D%25%3C/span%3E + */%7D %0A
e903aa8710d1558c79049f2e6305026065759132
support company tag; bugfix: hide locked problem after sort
leetcode-ext/leetcode-hidden.js
leetcode-ext/leetcode-hidden.js
/** * Created by binarylu on 3/21/16. */ $(function(){ var path = window.location.pathname; chrome.storage.sync.get({ ac_difficulty: 'show', hide_locked: 0 }, function(items) { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); } if (path.match(new RegExp('^\/tag'))) { tag_add_check(); $("#hide_locked").prop("checked", items.hide_locked === 0 ? false : true); tag_hide_locked(); } if (items.ac_difficulty == "hide") { if (path.match(new RegExp('^\/problemset'))) { page_problemset(); } else if (path.match(new RegExp('^\/tag'))) { $("#question_list thead a.btn-link").click(function() { setTimeout(page_tag, 1000); }); page_tag(); } else if (path.match(new RegExp('^\/problems'))) { page_problem(); $("#result-state").bind("DOMSubtreeModified", function() { var state = $("#result-state").html().replace(/(^\s*)|(\s*$)/g, "").toLocaleLowerCase(); if (state == "accepted") { $("#total-submit-ac").show(); } else { $("#total-submit-ac").hide(); } }); } } }); }); function page_problemset() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#problemList tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:last"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_tag() { var oncl = '$(this).parent().html($(this).parent().attr("ori_data"));return false;'; $("#question_list tbody tr").each(function() { var $ac = $(this).children("td:eq(3)"); $ac.attr("ori_data", $ac.html()); $ac.html("<a href='#' onclick='" + oncl + "'>Show</a>"); var $difficulty = $(this).children("td:eq(4)"); $difficulty.attr("ori_data", $difficulty.html()); $difficulty.html("<a href='#' onclick='" + oncl + "'>Show</a>"); }); } function page_problem() { $("#result h4:first").after($("<h4 id='total-submit-ac'></h4>").html($(".total-submit,.total-ac")).hide()); } function tag_add_check() { var $check = '<div style="display:inline;margin-left:10px">' + '<input type="checkbox" id="hide_locked">&nbsp;' + '<label for="hide_locked">Hide locked problems</label>' + '</div>'; $("label[for='tagCheck']").after($check); $("#hide_locked").click(tag_hide_locked); } function tag_hide_locked() { var hide_locked = $("#hide_locked").prop("checked") === true ? 1 : 0; chrome.storage.sync.set({ hide_locked: hide_locked }, function() { if(chrome.runtime.lastError) { console.log(chrome.runtime.lastError.message); return; } $("#question_list tbody tr").each(function() { var locked = $(this).children("td:eq(2)").children("i").length === 0 ? 0 : 1; if (hide_locked === 1 && locked === 1) { $(this).hide(); return true; } $(this).show(); }); }); }
JavaScript
0
@@ -345,32 +345,72 @@ egExp('%5E%5C/tag')) + %7C%7C path.match(new RegExp('%5E%5C/company')) ) %7B%0A @@ -749,16 +749,56 @@ %5C/tag')) + %7C%7C path.match(new RegExp('%5E%5C/company')) ) %7B%0A @@ -913,16 +913,71 @@ 1000);%0A + setTimeout(tag_hide_locked, 1000);%0A
dc6cacb775d1970fdc2371191f436c43eaac2828
Update console2winston.js
console2winston.js
console2winston.js
var util = require("util"); var winston = require("winston"); var stackTrace = require("stack-trace"); var _ = require("underscore"); var g_logger = winston; exports.logger = g_logger; exports.init= function(log) { g_logger = log; exports.logger = exports.winston = g_logger; return g_logger; } exports.enable_console = false; exports.enable_extra_info = true; var my_console = {}; for (var i in console) { my_console[i] = console[i]; } exports.console= my_console; function log(sl, level, args) { var out = ""; if (exports.enable_extra_info) { var trace = stackTrace.parse(new Error()); var filename = trace[sl].fileName; var funcname = trace[sl].functionName; if (funcname == null) funcname = trace[sl].methodName; var line = trace[sl].lineNumber; header = util.format("[%d][%s:%d][%s]\t", process.pid,filename, line, funcname); g_logger.log(level, header + args); } else { g_logger.log(level, out); } if (!!exports.enable_console) { switch(level) { case "info": my_console.info(out); break; case "debug": my_console.debug(out); break; case "error": my_console.error(out); break; case "warn": my_console.warn(out); break; default: my_console.log(out); } } } var g_time_labels={}; (function() { console.log = function(){ log(2, "info", util.format.apply(util.format, arguments)); }; _.each(["info", "debug", "error", "warn", "verbose", "silly"], function(m) { console[m] = function(){log(2, m, util.format.apply(util.format, arguments));}; }); console.trace = function(lable) { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Trace: "+lable +"\n" + st; log(2, "error", st); }; console.dir = function(a) { var out = util.inspect(a); log(2, "info", out); }; console.assert = function(a) { if (!a) { var st = new Error().stack; var msg = Array.prototype.slice.call(arguments, 1, arguments.length); st = st.replace(/^.*\n/, ""); st = st.replace(/^.*\n/, "AssertionError: " + util.format.apply(util.format, msg)+"\n"); log(2, "error", st); } } console.time = function(label) { g_time_labels[label] = new Date().getTime(); } console.timeEnd = function(label) { var begin= g_time_labels[label]; g_time_labels[label]=undefined; var now = new Date().getTime(); if (typeof(begin) != 'undefined') { log(2, "info", label+": "+ (now - begin)); } else { var st = new Error().stack; st = st.replace(/^.*\n/, ""); st = "Error: No such label: "+label +"\n"+ st; log(2, "error", st); } } })();
JavaScript
0.000001
@@ -1140,24 +1140,26 @@ %0A +/* case %22debug%22 @@ -1212,32 +1212,77 @@ break;%0A + */ // no console.debug function%0A case
f6089cb812b2504fe90942d1d8180172f8194cc6
Add x-api-locale to http header
src/app/common/services/i18n-service.js
src/app/common/services/i18n-service.js
/** * @ngdoc service * @name just.service.service:i18nService * @description * # i18nService * Service to handle language settings. */ angular.module('just.service') .service('i18nService', [ '$translate', 'tmhDynamicLocale', 'settings', 'localStorageService', 'justFlowService', 'justRoutes', '$q', 'datastoreService', function($translate, tmhDynamicLocale, settings, storage, flow, routes, $q, datastoreService) { this.listeners = []; var that = this; this.getDefaultLang = function (langs) { var defLang = langs.filter(function (lang) { return lang['lang-code'] === 'sv'; }); if (defLang.length === 0) { return langs[0]; } return defLang[0]; }; this.allLanguages = $q(function (resolve, reject) { datastoreService.fetch('languages?filter[system_language]=true') .then(function (data) { resolve(data.store.findAll('languages')); }, reject); }); this.langResolve = function () { return $q(function (resolve, reject) { that.allLanguages.then(function (langs) { var lang = that.getDefaultLang(langs); that.updateLanguage(lang); resolve(lang); }, reject); }); }; /** * @ngdoc function * @name just.service:i18nService#getLanguage * @methodOf just.service.service:i18nService * * @description * Get the language setting. The language will be defaulted to 'sv' initially. * The used language will be stored in the localStorageService with key 'language'. * * @example * i18nService.getLanguage(); * @returns {Promise} resolve with current json-api language object, or fails with error description. */ this.getLanguage = function () { var language = storage.get("language"); if (angular.isObject(language)) { if (angular.isUndefined(that.current_language)) { that.useLanguage(language); } var deferd = $q.defer(); deferd.resolve(language); return deferd.promise; } return that.langResolve(); }; /** * @ngdoc function * @name just.service:i18nService#useLanguage * @methodOf just.service.service:i18nService * * @description * Returns an array of all supported languages. * The array will be populated once the xhr requests is completed. * * @param {object} lang A language json-api object. * @returns {void} will redirect to routes.global.start.url. */ this.useLanguage = function (lang) { that.updateLanguage(lang); }; this.useLanguageById = function(id) { var idStr = id; if (angular.isNumber(id)) { idStr = id.toString(); } that.allLanguages.then(function (langs) { var filteredLang = langs.filter(function (lang) { return lang.id === idStr; }); if (filteredLang.length === 1) { that.useLanguage(filteredLang[0]); } }); }; this.updateLanguage = function (lang) { $translate.use(lang['lang-code']); tmhDynamicLocale.set(lang['lang-code']); storage.set("language", lang); that.current_language = lang; that.notifyChange(lang); }; /** * @ngdoc function * @name just.service:i18nService#addLanguageChangeListener * @methodOf just.service.service:i18nService * * @description * Register a function to be called when the langauge changes. * Should only be used by controllers that are long-lived (like MainCtrl) * else this will generate a memory leak. * * @param {function} cb is called when language is changed. The language object will be passed as first argument. */ this.addLanguageChangeListener = function (cb) { this.listeners.push(cb); }; this.notifyChange = function (lang) { this.listeners.forEach(function (cb) { cb(lang); }); }; /** * @ngdoc function * @name just.service:i18nService#suppotedLanguage * @methodOf just.service.service:i18nService * * @description * Get all supported languages. The supported languages * has attribute system_language = true. * * @returns {promise} resolve with list of languages. */ this.supportedLanguages = function () { return that.allLanguages; }; }]);
JavaScript
0.000001
@@ -336,16 +336,24 @@ ervice', +'$http', functio @@ -437,16 +437,22 @@ eService +,$http ) %7B%0A @@ -3257,32 +3257,107 @@ nction (lang) %7B%0A + $http.defaults.headers.common%5B%22X-API-LOCALE%22%5D = lang%5B'lang-code'%5D;%0A $transla
036d3b4e1866b5f56e12a4019bca779b7d317969
change readme
src/js/components/navigation/KLSteps/index.js
src/js/components/navigation/KLSteps/index.js
/** * @file KLSteps 步骤条 * @author ziane(zianecui@gmail.com) */ const Component = require('../../../ui-base/component'); const template = require('./index.html'); const _ = require('../../../ui-base/_'); /** * @class KLSteps * @extend Component * @param {object} [options.data] = 绑定属性 * @param {object[]} [options.data.steps=null] <=> 数据源 * @param {number} [options.data.steps[].status] => 状态id * @param {string} [options.data.steps[].title] => 步骤标题 * @param {object[]} [options.data.steps[].description] => 步骤具体描述 * @param {number} [options.data.current=0] <=> 当前状态 * @param {string} [options.data.size] => 当前尺寸,sm */ const KLSteps = Component.extend({ name: 'kl-steps', template, config() { _.extend(this.data, { steps: [], current: 0, size: '', currentIndex: 0, }); this.supr(); }, init() { this.supr(); this.$watch('current', () => { this.juedgeFinishedItem(); }); }, juedgeFinishedItem() { const data = this.data; const current = data.current; const steps = data.steps; steps.forEach((item, index) => { if ((typeof item.status !== 'function' && item.status / 1 === current / 1) || (typeof item.status === 'function' && item.status(current))) { data.currentIndex = index; } }); }, }); module.exports = KLSteps;
JavaScript
0.000001
@@ -458,16 +458,50 @@ =%3E %E7%8A%B6%E6%80%81id +%EF%BC%8C%E6%94%AF%E6%8C%81%E6%96%B9%E6%B3%95%EF%BC%8C%E4%BC%A0%E5%85%A5%E5%BD%93%E5%89%8D current %E8%BF%94%E5%9B%9E true %E5%88%99%E5%B1%9E%E4%BA%8E%E5%BD%93%E5%89%8D%E7%8A%B6%E6%80%81 %0A * @par
440568e2a14be6bfb4ed4f6a83522f7c22790aa4
Fix linting errors
webpack.common.js
webpack.common.js
const webpack = require('webpack') const path = require('path') const CopyWebpackPlugin = require('copy-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { entry: { adhocracy4: [ './meinberlin/assets/scss/style.scss', './meinberlin/assets/extra_css/_slick-theme.css', 'shariff/dist/shariff.min.css', './meinberlin/assets/js/app.js' ], vendor: [ 'classnames', '@fortawesome/fontawesome-free/scss/fontawesome.scss', '@fortawesome/fontawesome-free/scss/brands.scss', '@fortawesome/fontawesome-free/scss/regular.scss', '@fortawesome/fontawesome-free/scss/solid.scss', 'js-cookie', 'react', 'immutability-helper', 'react-dom', 'react-flip-move', 'react-sticky-box', 'slick-carousel/slick/slick.min.js', 'slick-carousel/slick/slick.css' ], mb_plans_map: [ 'leaflet/dist/leaflet.css', 'mapbox-gl/dist/mapbox-gl.css', 'leaflet.markercluster/dist/MarkerCluster.css', 'react-bootstrap-typeahead/css/Typeahead.css', './meinberlin/apps/plans/assets/plans_map.jsx' ], a4maps_display_point: [ 'leaflet/dist/leaflet.css', 'mapbox-gl/dist/mapbox-gl.css', 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_point.js' ], a4maps_display_points: [ 'leaflet/dist/leaflet.css', 'mapbox-gl/dist/mapbox-gl.css', 'leaflet.markercluster/dist/MarkerCluster.css', 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_points.js' ], a4maps_choose_point: [ 'leaflet/dist/leaflet.css', 'mapbox-gl/dist/mapbox-gl.css', 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_choose_point.js' ], a4maps_choose_polygon: [ 'leaflet/dist/leaflet.css', 'mapbox-gl/dist/mapbox-gl.css', 'leaflet-draw/dist/leaflet.draw.css', './meinberlin/apps/maps/assets/map_choose_polygon_with_preset.js' ], datepicker: [ './meinberlin/assets/js/init-picker.js', 'datepicker/css/datepicker.min.css' ], embed: [ './meinberlin/assets/js/embed.js' ], 'popup-close': [ './meinberlin/assets/js/popup-close.js' ], select2: [ 'select2' ] }, output: { libraryTarget: 'this', library: '[name]', path: path.resolve('./meinberlin/static/'), publicPath: '/static/', filename: '[name].js' }, externals: { 'django': 'django' }, module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules\/(?!(adhocracy4|bootstrap)\/).*/, // exclude most dependencies loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'].map(require.resolve), plugins: ['@babel/plugin-transform-runtime', '@babel/plugin-transform-modules-commonjs'] } }, { test: /\.s?css$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader' }, { loader: 'postcss-loader', options: { ident: 'postcss', plugins: [ require('autoprefixer') ] } }, { loader: 'sass-loader' } ] }, { test: /fonts\/.*\.(svg|woff2?|ttf|eot)(\?.*)?$/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]' } }, { test: /\.svg$|\.png$/, loader: 'file-loader', options: { name: 'images/[name].[ext]' } } ] }, resolve: { extensions: ['*', '.js', '.jsx', '.scss', '.css'], alias: { 'jquery$': 'jquery/dist/jquery.min.js', 'shariff$': 'shariff/dist/shariff.min.js', 'shpjs$': 'shpjs/dist/shp.min.js', 'a4maps_common$': 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_common.js' }, // when using `npm link`, dependencies are resolved against the linked // folder by default. This may result in dependencies being included twice. // Setting `resolve.root` forces webpack to resolve all dependencies // against the local directory. modules: [path.resolve('./node_modules')] }, plugins: [ new webpack.ProvidePlugin({ timeago: 'timeago.js', $: 'jquery', jQuery: 'jquery', Promise: ['es6-promise', 'Promise'] }), new webpack.optimize.SplitChunksPlugin({ name: 'vendor', filename: 'vendor.js' }), new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[id].css' }), new CopyWebpackPlugin([ { from: './meinberlin/assets/images/**/*', to: 'images/', flatten: true }, { from: './meinberlin/assets/info', to: 'info/', flatten: false } ]) ] }
JavaScript
0.000002
@@ -2451,24 +2451,22 @@ : %7B%0A -' django -' : 'djang @@ -3768,17 +3768,15 @@ -' jquery$ -' : 'j @@ -3812,17 +3812,16 @@ -' shariff$ ': ' @@ -3816,17 +3816,16 @@ shariff$ -' : 'shari @@ -3859,16 +3859,14 @@ -' shpjs$ -' : 's @@ -3894,17 +3894,16 @@ ,%0A -' a4maps_c @@ -3908,17 +3908,16 @@ _common$ -' : 'adhoc
68db3627a88782e5127e83aaa4cc8f80c2626942
fix test configs
karma-espower-preprocessor/karma.conf.js
karma-espower-preprocessor/karma.conf.js
module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'expect'], files: [ { pattern: 'node_modules/requirejs/require.js', included: false }, { pattern: 'test/fixture/amd.html', watched: true, served: true, included: false }, { pattern: 'build/power-assert.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/assertion.es6.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/customization.js', watched: true, served: true, included: true }, { pattern: 'test/not_tobe_instrumented/not_instrumented.js', watched: true, served: true, included: true }, { pattern: 'test/tobe_instrumented/modules.js', watched: true, served: true, included: true } ], preprocessors: { 'test/*/*.js': ['espower'] }, espowerPreprocessor: { options: { emitActualCode: false } }, reporters: ['dots'], port: 9876, colors: true, browsers: ['Chrome', 'Firefox'], singleRun: true }); };
JavaScript
0
@@ -1012,16 +1012,21 @@ 'test/ +tobe_ */*.js':
221d49f83ebbb23a9ddffe76cb90c74c1e347dc7
Use separate property to shutdown workers
worker-manager.js
worker-manager.js
var Worker = require('./worker') /** * Tracks worker state across runs. */ function WorkerManager () { this._pollHandle = null this.workers = {} this.isPolling = false } WorkerManager.prototype.registerWorker = function registerWorker (workerData) { if (this.workers[workerData.id]) { this.unregisterWorker(this.workers[workerData.id]) } var worker = new Worker(workerData) worker.emit('status', worker.status) this.workers[workerData.id] = worker return worker } WorkerManager.prototype.unregisterWorker = function unregisterWorker (worker) { worker.emit('delete', worker) worker.removeAllListeners() delete this.workers[worker.id] return worker } WorkerManager.prototype.updateWorker = function updateWorker (workerData) { var workers = this.workers if (workers[workerData.id]) { var worker = workers[workerData.id] var prevStatus = worker.status Object.keys(workerData).forEach(function (k) { worker[k] = workerData[k] }) if (worker.status !== prevStatus) { worker.emit('status', worker.status) } } } WorkerManager.prototype.startPolling = function startPolling (client, pollingTimeout, callback) { if (this.isPolling) { return } var self = this this.isPolling = true client.getWorkers(function (err, updatedWorkers) { if (err) { self.isPolling = false return (callback ? callback(err) : null) } var activeWorkers = (updatedWorkers || []).reduce(function (o, worker) { o[worker.id] = worker return o }, {}) Object.keys(self.workers).forEach(function (workerId) { if (activeWorkers[workerId]) { // process updates self.updateWorker(activeWorkers[workerId]) } else { // process deletions self.unregisterWorker(self.workers[workerId]) } }) self._pollHandle = setTimeout(function () { self.isPolling = false self.startPolling(client, pollingTimeout, callback) }, pollingTimeout) }) } WorkerManager.prototype.stopPolling = function stopPolling () { if (this._pollHandle) { clearTimeout(this._pollHandle) this._pollHandle = null } this.isPolling = false } // expose a single, shared instance of WorkerManager module.exports = new WorkerManager()
JavaScript
0
@@ -170,16 +170,46 @@ = false%0A + this.shouldShutdown = false%0A %7D%0A%0AWorke @@ -1230,16 +1230,39 @@ sPolling + %7C%7C this.shouldShutdown ) %7B%0A @@ -2219,32 +2219,36 @@ %0A this. -isPolling = fals +shouldShutdown = tru e%0A%7D%0A%0A//
e44447153bddf2cfacddac0af533944fd329b883
enable source map.
webpack.config.js
webpack.config.js
var path = require('path'); var env = process.env.NODE_ENV || 'dev'; module.exports = { entry: './src/main.js', output: { path: './dist', publicPath: '/dist', filename: 'bundle.js' }, devServer: { inline: true, port: 3000, historyApiFallback: true }, resolve: { root: path.resolve(__dirname), // create tasks to choose prod/dev env // need to create an issue alias: { config: 'config/config.' + env + '.js' } }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] } };
JavaScript
0
@@ -279,16 +279,41 @@ ue%0A %7D,%0A + devtool: 'source-map',%0A resolv
a35c3e8052efc885284e6ac19433ee2442cfb6e5
remove unused variables
routes/docker/exec.js
routes/docker/exec.js
var express = require('express'), handler = require('../common/handler'), docker = require('../../config').docker; let router = express.Router(); router .param('id', (req, res, next, id) => { req.exec = docker.getExec(id); next(); }) .get('/:id/json', (req, res) => { req.exec.inspect(handler.sendTo(res)); }) .post('/:id/start', (req, res) => { console.log('start'); req.exec.start(req.body, handler.sendTo(res, data => { res.status(201); })); }) .post('/:id/resize', (req, res) => { req.exec.start(req.body, handler.sendTo(res, data => { res.status(201); })); }); module.exports = router;
JavaScript
0.000014
@@ -434,36 +434,34 @@ ler.sendTo(res, -data +() =%3E %7B%0A res. @@ -579,12 +579,10 @@ es, -data +() =%3E
c4662893e120cae90c65206a4cac43056269bc8a
Fix the order of array key when sortObjectKeys = true is given
src/object-inspector/ObjectInspector.js
src/object-inspector/ObjectInspector.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TreeView from '../tree-view/TreeView'; import ObjectRootLabel from './ObjectRootLabel'; import ObjectLabel from './ObjectLabel'; import ThemeProvider from '../styles/ThemeProvider'; const createIterator = (showNonenumerable, sortObjectKeys) => { const objectIterator = function*(data) { const shouldIterate = (typeof data === 'object' && data !== null) || typeof data === 'function'; if (!shouldIterate) return; // iterable objects (except arrays) if (!Array.isArray(data) && data[Symbol.iterator]) { let i = 0; for (let entry of data) { if (Array.isArray(entry) && entry.length === 2) { const [k, v] = entry; yield { name: k, data: v, }; } else { yield { name: i.toString(), data: entry, }; } i++; } } else { const keys = Object.getOwnPropertyNames(data); if (sortObjectKeys === true) { keys.sort(); } else if (typeof sortObjectKeys === 'function') { keys.sort(sortObjectKeys); } for (let propertyName of keys) { if (data.propertyIsEnumerable(propertyName)) { const propertyValue = data[propertyName]; yield { name: propertyName || `""`, data: propertyValue, }; } else if (showNonenumerable) { // To work around the error (happens some time when propertyName === 'caller' || propertyName === 'arguments') // 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context // http://stackoverflow.com/questions/31921189/caller-and-arguments-are-restricted-function-properties-and-cannot-be-access let propertyValue; try { propertyValue = data[propertyName]; } catch (e) { // console.warn(e) } if (propertyValue !== undefined) { yield { name: propertyName, data: propertyValue, isNonenumerable: true, }; } } } // [[Prototype]] of the object: `Object.getPrototypeOf(data)` // the property name is shown as "__proto__" if (showNonenumerable && data !== Object.prototype /* already added */) { yield { name: '__proto__', data: Object.getPrototypeOf(data), isNonenumerable: true, }; } } }; return objectIterator; }; const defaultNodeRenderer = ({ depth, name, data, isNonenumerable }) => depth === 0 ? <ObjectRootLabel name={name} data={data} /> : <ObjectLabel name={name} data={data} isNonenumerable={isNonenumerable} />; /** * Tree-view for objects */ class ObjectInspector extends Component { static defaultProps = { showNonenumerable: false, theme: 'chromeLight', }; static propTypes = { /** An integer specifying to which level the tree should be initially expanded. */ expandLevel: PropTypes.number, /** An array containing all the paths that should be expanded when the component is initialized, or a string of just one path */ expandPaths: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), name: PropTypes.string, /** Not required prop because we also allow undefined value */ data: PropTypes.any, /** A known theme or theme object */ theme: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), /** Show non-enumerable properties */ showNonenumerable: PropTypes.bool, /** Sort object keys with optional compare function. */ sortObjectKeys: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** Provide a custom nodeRenderer */ nodeRenderer: PropTypes.func, }; render() { const { showNonenumerable, sortObjectKeys, nodeRenderer, ...rest } = this.props; const dataIterator = createIterator(showNonenumerable, sortObjectKeys); const renderer = nodeRenderer ? nodeRenderer : defaultNodeRenderer; return ( <ThemeProvider theme={this.props.theme}> <TreeView nodeRenderer={renderer} dataIterator={dataIterator} {...rest} /> </ThemeProvider> ); } } export default ObjectInspector;
JavaScript
0.999997
@@ -504,16 +504,58 @@ eturn;%0A%0A + const isArray = Array.isArray(data);%0A%0A // i @@ -595,35 +595,23 @@ if (! -Array. isArray -(data) && data @@ -1078,19 +1078,96 @@ === true -) %7B + && !isArray) %7B%0A // Array keys should not be sorted in alphabetical order %0A
abfd69cba9797b46b82c40f64788ce6dbfa0408e
remove public path for prod
webpack.config.js
webpack.config.js
const webpack = require('webpack'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const UglifyJsPlugin = require("uglifyjs-webpack-plugin"); const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); module.exports = { mode: "production", devtool: '#source-map', node: { fs: 'empty', net: 'empty', module: 'empty' }, entry: './src/frontend/App.js', output: { path: path.resolve(__dirname + '/dist/'), publicPath: '/', filename: 'assets/bundle.js' }, optimization: { minimizer: [ new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: true // set to true if you want JS source maps }), new OptimizeCSSAssetsPlugin({}) ] }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets:['react']} }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, "css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]"], exclude: /node_modules/ }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, "css-loader", 'sass-loader'], exclude: /node_modules/ }, { test: /\.(png|jp(e*)g)$/, use: [{ loader: 'url-loader', options: { limit: 8000, // Convert images < 8kb to base64 strings name: 'assets/img/[hash]-[name].[ext]' } }] }, { test: /\.(eot|svg|ttf|woff|woff2)$/, use: [ { loader: 'file-loader', options: { name: 'assets/fonts/[name].[ext]' } } ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "assets/[name].css", chunkFilename: "assets/[id].css" }), new HtmlWebpackPlugin({ template: './src/index.template.html', inject: 'body', filename: 'index.html' }) ], resolve: { modules: ['node_modules'], alias: { "Components": path.resolve("./src/frontend/Components"), "Containers": path.resolve("./src/frontend/Containers"), "css": path.resolve("./src/frontend/css"), "Assets": path.resolve("./src/backend/assets"), "Routes": path.resolve("./src/backend/routes") }, extensions: ['.js', '.jsx', '.json', '.css', '.scss'] }, target: 'web' };
JavaScript
0
@@ -573,30 +573,8 @@ ),%0D%0A - publicPath: '/',%0D%0A
fa3c6204dce853e3b2d3653016b976745879965c
Update variable name to reflect change
clients/web/src/views/widgets/UploadWidget.js
clients/web/src/views/widgets/UploadWidget.js
/** * This widget is used to upload files to a folder. Pass a folder model * to its constructor as the parent folder that will be uploaded into. * Events: * itemComplete: Triggered each time an individual item is finished uploading. * finished: Triggered when the entire set of items is uploaded. */ girder.views.UploadWidget = girder.View.extend({ events: { 'submit #g-upload-form': 'startUpload', 'click .g-resume-upload': function () { this.$('.g-upload-error-message').html(''); this.currentFile.resumeUpload(); }, 'change #g-files': function (e) { var files = this.$('#g-files')[0].files; if (files.length) { this.files = files; this.filesChanged(); } }, 'click .g-drop-zone': function (e) { this.$('#g-files').click(); }, 'dragenter .g-drop-zone': function (e) { e.stopPropagation(); e.preventDefault(); e.originalEvent.dataTransfer.dropEffect = 'copy'; this.$('.g-drop-zone') .addClass('g-dropzone-show') .html('<i class="icon-bullseye"/> Drop files here'); }, 'dragleave .g-drop-zone': function (e) { e.stopPropagation(); e.preventDefault(); this.$('.g-drop-zone') .removeClass('g-dropzone-show') .html('<i class="icon-docs"/> Browse or drop files'); }, 'dragover .g-drop-zone': function (e) { e.preventDefault(); }, 'drop .g-drop-zone': 'filesDropped' }, initialize: function (settings) { this.parent = settings.parent || settings.folder; this.parentType = settings.parentType || 'folder'; this.title = settings.title || 'Upload files'; this.files = []; this.totalSize = 0; }, render: function () { this.$el.html(jade.templates.uploadWidget({ parent: this.parent, parentType: this.parentType, title: this.title })).girderModal(this).on('hidden.bs.modal', function () { girder.dialogs.handleClose('upload'); }); girder.dialogs.handleOpen('upload'); return this; }, filesDropped: function (e) { e.stopPropagation(); e.preventDefault(); this.$('.g-drop-zone') .removeClass('g-dropzone-show') .html('<i class="icon-docs"/> Browse or drop files'); this.files = e.originalEvent.dataTransfer.files; this.filesChanged(); }, filesChanged: function () { if (this.files.length === 0) { this.$('.g-overall-progress-message').text('No files selected'); this.$('.g-start-upload').addClass('disabled'); } else { this.totalSize = 0; _.each(this.files, function (file) { this.totalSize += file.size; }, this); var msg; if (this.files.length > 1) { msg = 'Selected ' + this.files.length + ' files'; } else { msg = 'Selected <b>' + this.files[0].name + '</b>'; } this.$('.g-overall-progress-message').html('<i class="icon-ok"/> ' + msg + ' (' + girder.formatSize(this.totalSize) + ') -- Press start button'); this.$('.g-start-upload').removeClass('disabled'); this.$('.g-progress-overall,.g-progress-current').addClass('hide'); this.$('.g-current-progress-message').html(''); this.$('.g-upload-error-message').html(''); } }, startUpload: function (e) { e.preventDefault(); this.$('.g-drop-zone').addClass('hide'); this.$('.g-start-upload').addClass('disabled'); this.$('.g-progress-overall,.g-progress-current').removeClass('hide'); this.$('.g-upload-error-message').html(''); this.currentIndex = 0; this.overallProgress = 0; this._uploadNextFile(); }, /** * Initializes the upload of a file by requesting the upload token * from the server. If successful, this will call _uploadChunk to send the * actual bytes from the file if it is of non-zero length. */ _uploadNextFile: function () { if (this.currentIndex >= this.files.length) { // All files have finished this.$el.modal('hide'); this.trigger('g:uploadFinished'); return; } this.currentFile = this.parentType === 'file' ? this.parent : new girder.models.FileModel(); this.currentFile.on('g:upload.complete', function () { this.currentIndex += 1; this._uploadNextFile(); }, this).on('g:upload.chunkSent', function (info) { this.overallProgress += info.bytes; }, this).on('g:upload.progress', function (info) { var currentProgress = info.startByte + info.loaded; this.$('.g-progress-current>.progress-bar').css('width', Math.ceil(100 * currentProgress / info.total) + '%'); this.$('.g-progress-overall>.progress-bar').css('width', Math.ceil(100 * (this.overallProgress + info.loaded) / this.totalSize) + '%'); this.$('.g-current-progress-message').html( '<i class="icon-doc-text"/>' + (this.currentIndex + 1) + ' of ' + this.files.length + ' - <b>' + info.file.name + '</b>: ' + girder.formatSize(currentProgress) + ' / ' + girder.formatSize(info.total)); this.$('.g-overall-progress-message').html('Overall progress: ' + girder.formatSize(this.overallProgress + info.loaded) + ' / ' + girder.formatSize(this.totalSize)); }, this).on('g:upload.error', function (info) { var text = info.message + ' <a class="g-resume-upload">' + 'Click to resume upload</a>'; $('.g-upload-error-message').html(text); }, this); if (this.parentType === 'file') { this.currentFile.updateContents(this.files[this.currentIndex]); } else { this.currentFile.upload(this.folder, this.files[this.currentIndex]); } } });
JavaScript
0
@@ -6372,22 +6372,22 @@ ad(this. -folder +parent , this.f
dde0443f3b37c3eda25a02bd4ff56162eb9ba33e
Remove console.log call used for debugging
bin/main.js
bin/main.js
// Steam Multi-user Multi-game hourboost by MetalRuller // Dont edit below. const utils = require("../bin/util.js"); const SteamUser = require("steam-user"); const config = require("../cfg/settings.js"); const configChecker = require("../bin/configChecker.js"); const SteamTotp = require("steam-totp"); const testConfig = configChecker.checkConfig(config); if(testConfig !== "fine") { utils.print("error", "Got configuration errors:" + testConfig); return; } var actionTodo = {}; var users = new Array(); function ResetTodoList() { actionTodo = {}; for(var key in config.Accounts) { if({}.hasOwnProperty.call(config.Accounts, key)) { actionTodo[key] = config.Accounts[key]; } } } function GetGameId(gamename) { for(var key in config.GameDefs) { if(key.toLowerCase() === gamename.toLowerCase()) { return config.GameDefs[key]; } } return 0; } function doNext(step, obj) { if(Object.keys(actionTodo).length > 0) { var _username, _password; for(var key in actionTodo) { if(typeof(_username) === "undefined" && typeof(_password) === "undefined") { _username = key; _password = actionTodo[key]; } } if(typeof(step) === "undefined") { doUserLogin(_username, _password); } else { if(typeof(obj) !== "undefined") { if(step === "startGame") { if(typeof(obj.publicIP) !== "undefined" && typeof(obj.cellID) !== "undefined") { var usersGame = config.Games[_username]; if(typeof(usersGame) !== "string" && typeof(usersGame) !== "object" && utils.isArray(usersGame) !== true) { utils.print("error", "No game defined for user " + _username); return; } obj.setPersona(SteamUser.EPersonaState.Offline); var _rapps = new Array(); if(typeof(usersGame) === "string") { if(usersGame === "tons") { var _all = obj.getOwnedPackages(); console.log(_all.length); for(var i = 0; i < 30; i++) { var _i = _all[utils.getRandomInt(0, _all.length)]; while (_rapps.contains(_i)) { _i = _all[utils.getRandomInt(0, _all.length)]; } _rapps.push(_i); } } } if(typeof(usersGame) === "object" && utils.isArray(usersGame) === true) { var ids = new Array(); usersGame.forEach(function(gamen) { ids.push(GetGameId(gamen)); }); obj.gamesPlayed(ids); } else { if(usersGame !== "tons") { obj.gamesPlayed(GetGameId(usersGame)); } else { obj.gamesPlayed(_rapps); } } delete actionTodo[_username]; if(typeof(usersGame) === "string") { if(usersGame !== "tons") { utils.print("success", "Account <" + _username + "> is now playing " + usersGame); } else { utils.print("success", "Account <" + _username + "> is now playing " + _rapps.length + " games!"); } } else { var _gamespl = ""; for(var i = 0; i < usersGame.length; i++) { _gamespl = _gamespl + usersGame[i]; if(i !== usersGame.length-1) { _gamespl = _gamespl + ", "; } } utils.print("success", "Account <" + _username + "> is now playing : " + _gamespl); } setTimeout(function() { doNext(); }, 60000); } } } } } } function doUserLogin(username, password) { utils.print("info", "Logging into steam as " + username); var _c = { "accountName": username, "password": password, "machineName": "HourBooster Bot(MetalRuller)", }; var client = new SteamUser(); client.options.autoRelogin = true; if(typeof(config.Games[username]) === "string") { if(config.Games[username] === "tons") { client.options.enablePicsCache = true; } } if(typeof(config.TwofacSecrets[username]) === "string") { client.options.promptSteamGuardCode = false; client.on('steamGuard', function(domain, callback, lastCodeWrong) { if(lastCodeWrong == true) { utils.print("error", "Failed to generate steamguard code for " + username + ", skipping"); setTimeout(function() { delete actionTodo[username]; client.logOff(); delete client; doNext(); }, 120000); return; } var code = SteamTotp.generateAuthCode(config.TwofacSecrets[username]); callback(code); }); } client.on('loggedOn', function(details) { users.push(client); utils.print("success", "Logged into Steam as " + username); client.setPersona(SteamUser.EPersonaState.Online); setTimeout(function() { if(typeof(actionTodo[username]) !== "string") { actionTodo[username] = password; } doNext("startGame", client); }, 2500); }); client.on("playingState", function(blocked) { if(blocked === true) { utils.print("warn", "Stopped botting on " + username + ", started game elsewhere, skipping in 5m"); client.setPersona(SteamUser.EPersonaState.Online); client.logOff(); delete client; delete actionTodo[username]; setTimeout(function() { actionTodo[username] = password; doNext(); }, 1000*60*5); } }); client.on("error", function(e) { utils.print("error", String(e)); // Some error occurred during logon if(String(e).toLowerCase() === "Error: RateLimitExceeded".toLowerCase()) { utils.print("warn", "Rate limit exceeded... waiting 45mins"); utils.pause(2700000); utils.print("warn", "exiting"); process.exit(); } else if(String(e).toLowerCase() === "Error: LoggedInElsewhere".toLowerCase() || String(e).toLowerCase() === "Error: LogonSessionReplaced".toLowerCase()) { utils.print("warn", "Logged in elsewhere... trying to login again in 2m"); client.logOff(); delete client; delete actionTodo[username]; setTimeout(function() { client.logOff(); actionTodo[username] = password; doNext(); }, 120000); } }); client.logOn(_c); } utils.print("success", "Started!"); utils.print("Resetting action list"); ResetTodoList(); utils.pause(10000); utils.print("Starting bot"); doNext();
JavaScript
0.000002
@@ -1923,43 +1923,8 @@ );%0D%0A -%09%09%09%09%09%09%09%09console.log(_all.length);%0D%0A %09%09%09%09
97c41cd9710edf4e5bd9b4afcc2ef945450d8581
remove appiumVersion
test/endtoend/wdio.remote.conf.js
test/endtoend/wdio.remote.conf.js
const base = require('./wdio.base.conf') const { CompanionService } = require('./utils') function createCapability (capability) { return { 'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER, build: process.env.TRAVIS_BUILD_NUMBER, extendedDebugging: true, ...capability } } exports.config = Object.assign(base.config, { capabilities: [ { browserName: 'firefox', version: '40.0', platform: 'Linux' }, { browserName: 'firefox', version: '61.0', platform: 'Windows 10' }, { browserName: 'internet explorer', version: '10.0', platform: 'Windows 8' }, { browserName: 'internet explorer', version: '11.0', platform: 'Windows 10' }, { browserName: 'chrome', version: '70.0', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '14', platform: 'Windows 10' }, { browserName: 'MicrosoftEdge', version: '17', platform: 'Windows 10' }, // { browserName: 'safari', version: '11.0', platform: 'macOS 10.12' }, // { browserName: 'safari', version: '10.0', platformName: 'iOS', platformVersion: '10.0', deviceOrientation: 'portrait', deviceName: 'iPhone 6 Simulator', appiumVersion: '1.7.1' }, { browserName: 'chrome', platformName: 'Android', platformVersion: '6.0', deviceOrientation: 'portrait', deviceName: 'Android Emulator', appiumVersion: '1.7.1' } ].map(createCapability), // If you only want to run your tests until a specific amount of tests have failed use // bail (default is 0 - don't bail, run all tests). bail: 3, // Set a base URL in order to shorten url command calls. If your url parameter starts // with "/", then the base url gets prepended. baseUrl: 'http://localhost', // Test runner services // Services take over a specific job you don't want to take care of. They enhance // your test setup with almost no effort. Unlike plugins, they don't add new // commands. Instead, they hook themselves up into the test process. services: ['static-server', 'sauce', new CompanionService()], user: process.env.SAUCE_USERNAME, key: process.env.SAUCE_ACCESS_KEY })
JavaScript
0.000003
@@ -1290,32 +1290,8 @@ tor' -, appiumVersion: '1.7.1' %7D%0A
44febbe5a4664defe498690f1652ced63d0063bd
update upload
routes/upload-font.js
routes/upload-font.js
'use strict'; var fs = require('fs'); var path = require('path'); var express = require('express'); var router = express.Router(); var Fontmin = require('fontmin'); var intoStream = require('into-stream'); var rename = require('gulp-rename'); var uuid = require('node-uuid'); var EasyZip = require('easy-zip').EasyZip; router.post('/', function (req, res, next) { var originalname = req.files[0].originalname; var output = path.join(process.cwd(), 'public', 'uploads', originalname); var rs = intoStream(req.files[0].buffer); var ws = fs.createWriteStream(output); rs.pipe(ws); rs.on('end', function () { handleFont(req, res); }); rs.on('error', function (err) { console.log(err); throw err; }); }); module.exports = router; // /////////////////////////////////////////////////////////////// // private method // /////////////////////////////////////////////////////////////// function handleFont(req, res) { var styleData; var fontmin; var originalname = req.files[0].originalname; var output = path.join(process.cwd(), 'public', 'uploads', originalname); var fontFamily = originalname.replace(/\.ttf/, ''); var id = uuid.v1(); var dest = path.join(process.cwd(), 'public', 'fontmin', id); var fontPath = '/fontmin/' + id + '/'; var cssPath = path.join(process.cwd(), 'public', 'fontmin', id, originalname.replace(/\.ttf/, '.css')); var reg = /url\("\/fontmin\/([^/]+)\//g; var outputName = path.join(process.cwd(), 'public', 'fontmin', id + '.zip'); if (req.body.text.length > 0) { fontmin = new Fontmin() .src(output) .use(rename(originalname)) .use(Fontmin.glyph({ // 字型提取插件 text: req.body.text // 所需文字 })) .use(Fontmin.ttf2eot()) // eot 转换插件 .use(Fontmin.ttf2woff()) // woff 转换插件 .use(Fontmin.ttf2svg()) // svg 转换插件 .use(Fontmin.css({ fontPath: fontPath, asFileName: true })) // css 生成插件 .dest(dest); } else { fontmin = new Fontmin() .src(output) .use(rename(originalname)) .use(Fontmin.ttf2eot()) // eot 转换插件 .use(Fontmin.ttf2woff()) // woff 转换插件 .use(Fontmin.ttf2svg()) // svg 转换插件 .use(Fontmin.css({ fontPath: fontPath, asFileName: true })) // css 生成插件 .dest(dest); } runFontmin(fontmin) .then(function () { return readFile(cssPath); }) .then(function (data) { styleData = data; data = data.replace(reg, 'url("/fonts/'); return writeFile(cssPath, data); }) .then(function () { return zipFonts(dest, outputName); }) .then(function () { res.json({ style: styleData, fontFamily: fontFamily, zipUrl: '/fontmin/' + id + '.zip' }); }) .catch(function (err) { throw new Error(err); }); } function runFontmin(fontmin) { return new Promise(function (resolve, reject) { fontmin.run(function (err) { if (err) { return reject(err); } resolve(); }); }); } function readFile(path) { return new Promise(function (resolve, reject) { fs.readFile(path, 'utf-8', function (err, data) { if (err) { return reject(err); } resolve(data); }); }); } function writeFile(path, data) { return new Promise(function (resolve, reject) { fs.writeFile(path, data, function (err) { if (err) { return reject(err); } resolve(); }); }); } function zipFonts(input, output) { var zip = new EasyZip(); return new Promise(function (resolve, reject) { zip.zipFolder(input, function (err) { if (err) { return reject(err); } zip.writeToFile(output); resolve(); }); }); }
JavaScript
0
@@ -2011,32 +2011,60 @@ (originalname))%0A + .use(Fontmin.glyph())%0A .use(Fontm
7d474e8169f45a6622760a29450436be42489213
Fix null body issue
client/src/components/Issue.js
client/src/components/Issue.js
import React from 'react'; import Avatar from './Avatar'; import Assignee from './Assignee'; import Labels from './Labels'; import Moment from 'react-moment'; import PropTypes from 'prop-types'; const Issue = ({ issue: { user: { avatar_url }, html_url, title, assignee, created_at, updated_at, labels, body } }) => { return ( <div className='issue'> <h2> <a href={html_url}>{title}</a> </h2> <Avatar url={avatar_url} user_url={getUserUrlFromIssueUrl(html_url)} /> <div> <a href={getRepoUrlFromIssueUrl(html_url)}> {getRepoNameFromIssueUrl(html_url)} </a> {assignee && <Assignee user={assignee} />} <div className='times'> <div className='timeAgo'> Created: <Moment fromNow parse='YYYY-MM-DDTHH:mm:ssZ'> {created_at} </Moment> </div> <div className='timeAgo'> Updated: <Moment fromNow parse='YYYY-MM-DDTHH:mm:ssZ'> {updated_at} </Moment> </div> </div> </div> <Labels labels={labels} /> <p className='issue-body'> {body.length < maxBodyLength ? body : body.substr(0, maxBodyLength) + '...'} </p> </div> ); }; const maxBodyLength = 500; function getRepoUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\/[^/]+\//; let matches = html_url.match(pattern); let repoUrl = ''; if (matches && matches.length > 0) { repoUrl = matches[0]; } return repoUrl; } function getUserUrlFromIssueUrl(html_url) { let pattern = /^https:\/\/github.com\/[^/]+\//; let matches = html_url.match(pattern); let userUrl = ''; if (matches && matches.length > 0) { userUrl = matches[0]; } return userUrl; } function getRepoNameFromIssueUrl(html_url) { let pattern = /https:\/\/github.com\/([^/]+)\/([^/]+)\//; let matches = html_url.match(pattern); let repoName = ''; if (matches && matches.length > 2) { repoName = matches[1] + '/' + matches[2]; } return repoName; } Issue.propTypes = { issue: PropTypes.shape({ html_url: PropTypes.string.isRequired, user: PropTypes.shape({ avatar_url: PropTypes.string.isRequired }).isRequired, title: PropTypes.string.isRequired, assignee: PropTypes.shape({ html_url: PropTypes.string.isRequired, avatar_url: PropTypes.string.isRequired }), created_at: PropTypes.string.isRequired, updated_at: PropTypes.string.isRequired, labels: PropTypes.array.isRequired, body: PropTypes.string.isRequired }).isRequired }; export default Issue;
JavaScript
0.000001
@@ -381,15 +381,15 @@ ame= -' +%22 issue -' +%22 %3E%0A @@ -727,15 +727,15 @@ ame= -' +%22 times -' +%22 %3E%0A @@ -753,33 +753,33 @@ v className= -' +%22 timeAgo -' +%22 %3E%0A @@ -784,24 +784,30 @@ Created: +&nbsp; %0A @@ -821,33 +821,33 @@ t fromNow parse= -' +%22 YYYY-MM-DDTHH:mm @@ -842,33 +842,33 @@ -MM-DDTHH:mm:ssZ -' +%22 %3E%0A @@ -948,17 +948,17 @@ ame= -' +%22 timeAgo -' +%22 %3E%0A @@ -975,16 +975,22 @@ Updated: +&nbsp; %0A @@ -1016,17 +1016,17 @@ w parse= -' +%22 YYYY-MM- @@ -1037,17 +1037,17 @@ H:mm:ssZ -' +%22 %3E%0A @@ -1186,17 +1186,17 @@ assName= -' +%22 issue-bo @@ -1197,17 +1197,17 @@ sue-body -' +%22 %3E%0A @@ -1213,16 +1213,33 @@ %7Bbody +%0A ? body .length @@ -1268,15 +1268,19 @@ + + ? body%0A + @@ -1324,16 +1324,31 @@ + '...' +%0A : '' %7D%0A @@ -2685,27 +2685,16 @@ s.string -.isRequired %0A %7D).is
b4d77fa1968a8faa79dfeceaee13bd3fecf630aa
Update building config
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: path.join(__dirname, 'src'), output: { library: 'RsuiteDatepicker', libraryTarget: 'umd', path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015', 'react'] } }, { test: /\.less$/, loader: 'style!css!less' } ] }, devtool: 'source-map', externals: { 'react': 'React', 'react-dom': 'ReactDOM', 'moment': 'moment' } };
JavaScript
0.000001
@@ -164,16 +164,46 @@ 'umd',%0A + umdNamedDefine: true,%0A @@ -261,14 +261,25 @@ e: ' -bundle +rsuite-datepicker .js' @@ -449,101 +449,8 @@ der' -,%0A query: %7B%0A presets: %5B'es2015', 'react'%5D%0A %7D %0A @@ -588,35 +588,8 @@ -devtool: 'source-map',%0A exte @@ -616,17 +616,136 @@ act' +: %7B%0A root: 'React',%0A commonjs2: 'react',%0A commonjs: 'react',%0A amd : ' -R +r eact' +%0A %7D ,%0A @@ -762,16 +762,36 @@ ct-dom': + %7B%0A root: 'ReactD @@ -807,26 +807,109 @@ + -'moment': 'moment' + commonjs2: 'react-dom',%0A commonjs: 'react-dom',%0A amd: 'react-dom'%0A %7D %0A
13361865c78fa6be9828ab4c6bf53169f7bf52fc
made action verbs uppercase. #16
src/actionTypes.js
src/actionTypes.js
export const BLUR = 'redux-form/blur'; export const CHANGE = 'redux-form/change'; export const INITIALIZE = 'redux-form/initialize'; export const RESET = 'redux-form/reset'; export const TOUCH = 'redux-form/touch'; export const TOUCH_ALL = 'redux-form/touch-all'; export const UNTOUCH = 'redux-form/untouch'; export const UNTOUCH_ALL = 'redux-form/untouch-all';
JavaScript
0.999173
@@ -29,12 +29,12 @@ orm/ -blur +BLUR ';%0Ae @@ -70,14 +70,14 @@ orm/ -change +CHANGE ';%0Ae @@ -117,18 +117,18 @@ orm/ -initialize +INITIALIZE ';%0Ae @@ -163,13 +163,13 @@ orm/ -reset +RESET ';%0Ae @@ -200,21 +200,21 @@ ux-form/ -touch +TOUCH ';%0Aexpor @@ -245,25 +245,25 @@ ux-form/ -touch-all +TOUCH_ALL ';%0Aexpor @@ -292,23 +292,23 @@ ux-form/ -untouch +UNTOUCH ';%0Aexpor @@ -345,18 +345,18 @@ orm/ -untouch-all +UNTOUCH_ALL ';%0A
92f6d5545818b338a0642e79103e5e284662cb38
Add failing test
test/fixtures/hard/indentation.js
test/fixtures/hard/indentation.js
import styled, { keyframes } from 'styled-components' // None of the below should throw indentation errors const Comp = () => { const Button = styled.button` color: blue; ` return Button } const Comp2 = () => { const InnerComp = () => { const Button = styled.button` color: blue; ` return Button } return InnerComp() } const Button = styled.button`color: blue;` const animations = { spinnerCircle: keyframes` 0% { opacity: 0; } 100% { opacity: 1; } ` }
JavaScript
0.000138
@@ -19,16 +19,21 @@ eyframes +, css %7D from @@ -525,8 +525,164 @@ %7D%0A %60%0A%7D%0A +%0Aconst helper = condition =%3E %7B%0A if (condition) %7B%0A return css%60%0A color: red;%0A%0A &:hover %7B%0A color: blue;%0A %7D%0A %60%0A %7D%0A return null%0A%7D%0A
6703cf195a87cb3758015379cf2302d6ebe32366
Make bin/rnws.js executable
bin/rnws.js
bin/rnws.js
#!/usr/bin/env node const path = require('path'); const fs = require('fs'); const program = require('commander'); const package = require('../package.json'); const fetch = require('../lib/fetch'); const Server = require('../lib/Server'); /** * Create a server instance using the provided options. * @param {Object} opts react-native-webpack-server options * @return {Server} react-native-webpack-server server */ function createServer(opts) { opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath); if (fs.existsSync(opts.webpackConfigPath)) { opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath)); } else { throw new Error('Must specify webpackConfigPath or create ./webpack.config.js'); } delete opts.webpackConfigPath; const server = new Server(opts); return server; } function commonOptions(program) { return program .option( '-H, --hostname [hostname]', 'Hostname on which the server will listen. [localhost]', 'localhost' ) .option( '-P, --port [port]', 'Port on which the server will listen. [8080]', 8080 ) .option( '-p, --packagerPort [port]', 'Port on which the react-native packager will listen. [8081]', 8081 ) .option( '-w, --webpackPort [port]', 'Port on which the webpack dev server will listen. [8082]', 8082 ) .option( '-c, --webpackConfigPath [path]', 'Path to the webpack configuration file. [webpack.config.js]', 'webpack.config.js' ) .option( '-e, --entry [name]', 'Webpack entry module. [index.ios]', 'index.ios' ); } program.version(package.version); commonOptions(program.command('start')) .description('Start the webpack server.') .option('-r, --hot', 'Enable hot module replacement. [false]', false) .action(function(options) { const opts = options.opts(); const server = createServer(opts); server.start(); }); commonOptions(program.command('bundle')) .description('Bundle the app for distribution.') .option( '-b, --bundlePath [path]', 'Path where the bundle should be written. [./iOS/main.jsbundle]', './iOS/main.jsbundle' ) .action(function(options) { const opts = options.opts(); const server = createServer(opts); const url = 'http://localhost:' + opts.port + '/index.ios.bundle'; const targetPath = path.resolve(opts.bundlePath); server.start(); fetch(url).then(function(content) { fs.writeFileSync(targetPath, content); server.stop(); // XXX: Hack something is keeping the process alive but we can still // safely kill here without leaving processes hanging around... process.exit(0); }).catch(function(err) { console.log('Error creating bundle...', err.stack); server.stop(); }); }); program.parse(process.argv);
JavaScript
0.000015
8d101319df5fdec771fd87478cf3b8f2773f1549
Fix duplicated styles generated from emotion (#23809)
docs/pages/_document.js
docs/pages/_document.js
import React from 'react'; import { ServerStyleSheets } from '@material-ui/styles'; import { ServerStyleSheet } from 'styled-components'; import createEmotionServer from '@emotion/server/create-instance'; import Document, { Html, Head, Main, NextScript } from 'next/document'; import { LANGUAGES_SSR } from 'docs/src/modules/constants'; import { pathnameToLanguage } from 'docs/src/modules/utils/helpers'; import { themeColor } from 'docs/src/modules/components/ThemeContext'; import { cacheLtr } from 'docs/pages/_app'; const { extractCritical } = createEmotionServer(cacheLtr); // You can find a benchmark of the available CSS minifiers under // https://github.com/GoalSmashers/css-minification-benchmark // We have found that clean-css is faster than cssnano but the output is larger. // Waiting for https://github.com/cssinjs/jss/issues/279 // 4% slower but 12% smaller output than doing it in a single step. // // It's using .browserslistrc let prefixer; let cleanCSS; if (process.env.NODE_ENV === 'production') { /* eslint-disable global-require */ const postcss = require('postcss'); const autoprefixer = require('autoprefixer'); const CleanCSS = require('clean-css'); /* eslint-enable global-require */ prefixer = postcss([autoprefixer]); cleanCSS = new CleanCSS(); } const GOOGLE_ID = process.env.NODE_ENV === 'production' ? 'UA-106598593-2' : 'UA-106598593-3'; export default class MyDocument extends Document { render() { const { canonical, userLanguage } = this.props; return ( <Html lang={userLanguage}> <Head> {/* manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ */} <link rel="manifest" href="/static/manifest.json" /> {/* PWA primary color */} <meta name="theme-color" content={themeColor} /> <link rel="shortcut icon" href="/static/favicon.ico" /> {/* iOS Icon */} <link rel="apple-touch-icon" sizes="180x180" href="/static/icons/180x180.png" /> {/* SEO */} <link rel="canonical" href={`https://material-ui.com${ userLanguage === 'en' ? '' : `/${userLanguage}` }${canonical}`} /> <link rel="alternate" href={`https://material-ui.com${canonical}`} hrefLang="x-default" /> {LANGUAGES_SSR.map((userLanguage2) => ( <link key={userLanguage2} rel="alternate" href={`https://material-ui.com${ userLanguage2 === 'en' ? '' : `/${userLanguage2}` }${canonical}`} hrefLang={userLanguage2} /> ))} {/* Preconnect allows the browser to setup early connections before an HTTP request is actually sent to the server. This includes DNS lookups, TLS negotiations, TCP handshakes. */} <link href="https://fonts.gstatic.com" rel="preconnect" crossOrigin="anonymous" /> <style id="material-icon-font" /> <style id="font-awesome-css" /> <style id="app-search" /> <style id="prismjs" /> <style id="insertion-point-jss" /> </Head> <body> <Main /> <script // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: ` window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; window.ga('create','${GOOGLE_ID}','auto'); `, }} /> <NextScript /> </body> </Html> ); } } // `getInitialProps` belongs to `_document` (instead of `_app`), // it's compatible with static-site generation (SSG). MyDocument.getInitialProps = async (ctx) => { // Resolution order // // On the server: // 1. app.getInitialProps // 2. page.getInitialProps // 3. document.getInitialProps // 4. app.render // 5. page.render // 6. document.render // // On the server with error: // 1. document.getInitialProps // 2. app.render // 3. page.render // 4. document.render // // On the client // 1. app.getInitialProps // 2. page.getInitialProps // 3. app.render // 4. page.render // Render app and page and get the context of the page with collected side effects. const materialSheets = new ServerStyleSheets(); const styledComponentsSheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />)), }); const initialProps = await Document.getInitialProps(ctx); const emotionStyles = extractCritical(initialProps.html); let css = materialSheets.toString(); // It might be undefined, e.g. after an error. if (css && process.env.NODE_ENV === 'production') { const result1 = await prefixer.process(css, { from: undefined }); css = result1.css; css = cleanCSS.minify(css).styles; } // All the URLs should have a leading /. // This is missing in the Next.js static export. let url = ctx.req.url; if (url[url.length - 1] !== '/') { url += '/'; } return { ...initialProps, canonical: pathnameToLanguage(url).canonical, userLanguage: ctx.query.userLanguage || 'en', // Styles fragment is rendered after the app and page rendering finish. styles: [ ...React.Children.toArray(initialProps.styles), <style id="jss-server-side" key="jss-server-side" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: css }} />, <style id="emotion-server-side" key="emotion-server-side" data-emotion-css={emotionStyles.ids.join(' ')} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: emotionStyles.css }} />, styledComponentsSheet.getStyleElement(), ], }; } finally { styledComponentsSheet.seal(); } };
JavaScript
0
@@ -6046,13 +6046,16 @@ tion --css= +=%7B%60css $ %7Bemo @@ -6079,16 +6079,18 @@ in(' ')%7D +%60%7D %0A
3135fb1373abcedb2f001d12a59509151cbad113
update babel-loder config
webpack.config.js
webpack.config.js
module.exports = webpackConfig => { webpackConfig.babel.plugins.push('antd'); webpackConfig.module.loaders.unshift( { test: /src(\\|\/).+\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: [ 'es2015', 'react', 'stage-0' ] } } ); return webpackConfig; };
JavaScript
0
@@ -138,27 +138,14 @@ t: / -src(%5C%5C%7C%5C/).+ %5C.jsx? -$ /,%0A
127a05ae0dffa44e70906e11d1b66be9bb8d6442
Fix test case mistakes
client/test/changeset_tests.js
client/test/changeset_tests.js
/** * Copyright 2010 PolicyPad * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * These test deal with generating changesets based in user * insertions in the editor. */ module("Insertion Changeset Generation"); /** * Old: foobar * New: foobarbaz * * Expected: Z:6>3=6+3$baz */ test('simple single line append', function() { equals(generateChangeset('foobar', 'foobarbaz'), 'Z:6>3=6+3$baz'); }); /** * Old: fo * New: foo * * Expected: Z:2>1=2+1$o */ test('single character append', function() { equals(generateChangeset('fo', 'foo'), 'Z:2>1=2+1$o'); }); /** * Old: foobaz * New: foobarbaz * * Expected: Z:6>3=3+3$bar */ test('simple single line insert', function() { equals(generateChangeset('foobaz', 'foobarbaz'), 'Z:6>3=3+3$bar'); }); /** * Old: foo\n * New: foo\nbar * * Expected: Z:4>3|1=4+3$bar */ test('simple multi line append', function() { equals(generateChangeset('foo\n', 'foo\nbar'), 'Z:4>3|1=4+3$bar'); }); /** * Old: foo\nbar * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4=3+4$\nbaz */ test('simple multi line append without original newline', function() { equals(generateChangeset('foo\nbar', 'foo\nbar\nbaz'), 'Z:7>4|1=4=3+4$\nbaz'); }); /** * Old: foo\nbaz * New: foo\nbar\nbaz * * Expected: Z:7>4|1=4+4$bar\n */ test('simple multi line insert', function() { equals(generateChangeset('foo\nbaz', 'foo\nbar\nbaz'), 'Z:7>4|1=4+4$bar\n'); }); /** * These tests deal with generating changesets based on deletions * from within the editor. */ module('Deletion Changeset Generation'); /** * Old: fooo * New: foo * * Expected: Z:4<1=3-1 */ test('simple single character delete', function() { equals(generateChangeset('fooo', 'foo'), 'Z:4<1=3-1'); }); /** * Old: foobarbaz * New: foobaz * * Expected: Z:6<3=3-3 */ test('simple single line characters delete', function() { equals(generateChangeset('foobarbaz', 'foobaz'), 'Z:6<3=3-3'); });
JavaScript
0.999995
@@ -1154,23 +1154,25 @@ : Z:6%3E3= -3+3$ +5+3=1$r ba -r %0A */%0Ates @@ -1279,15 +1279,17 @@ 6%3E3= -3+3$ +5+3=1$r ba -r ');%0A @@ -1555,26 +1555,30 @@ Z:7%3E4%7C1=4=3 -+4 +%7C1+1+3 $%5Cnbaz%0A */%0At @@ -1718,18 +1718,22 @@ %3E4%7C1=4=3 -+4 +%7C1+1+3 $%5Cnbaz') @@ -1936,24 +1936,32 @@ :7%3E4%7C1=4 -+4$ba +=2%7C1+2+2=1$ r%5Cn +ba ');%0A%7D);%0A @@ -2336,23 +2336,25 @@ cted: Z: -6%3C3=3 +9%3C3=5 -3 +=1 %0A */%0Ates @@ -2468,15 +2468,17 @@ 'Z: -6%3C3=3 +9%3C3=5 -3 +=1 ');%0A
d8949e04d04bbd01a2bee3c3e7f278c33076fae8
Remove type annotation from protein input
packages/example-studio/components/ProteinInput/ProteinInput.js
packages/example-studio/components/ProteinInput/ProteinInput.js
import PropTypes from 'prop-types' import React from 'react' import Fieldset from 'part:@sanity/components/fieldsets/default' import {PatchEvent, unset, set, setIfMissing} from 'part:@sanity/form-builder/patch-event' import {io, Viewer} from 'bio-pv' import Select from 'part:@sanity/components/selects/default' import TextField from 'part:@sanity/components/textfields/default' import Button from 'part:@sanity/components/buttons/default' import Spinner from 'part:@sanity/components/loading/spinner' import ActivateOnFocus from 'part:@sanity/components/utilities/activate-on-focus' import PDBS from './PDBS' const VIEWER_OPTIONS = { width: 'auto', height: '500', antialias: true, fog: true, outline: true, quality: 'high', style: 'phong', selectionColor: 'white', transparency: 'screendoor', background: '#fff', animateTime: 500, doubleClick: null } const DEFAULT_PDB = PDBS[0].id const getAttr = (value, propName) => value && value[propName] export default class ProteinInput extends React.Component { static propTypes = { type: PropTypes.shape({ title: PropTypes.string }).isRequired, value: PropTypes.shape({ _type: PropTypes.string, pdb: PropTypes.string, camera: PropTypes.shape({ rotation: PropTypes.arrayOf(PropTypes.number), center: PropTypes.arrayOf(PropTypes.number), zoom: PropTypes.number }) }), level: PropTypes.number, onChange: PropTypes.func.isRequired } state = { isLoading: true } componentDidMount() { const {value} = this.props this.viewer = new Viewer(this._viewerElement, VIEWER_OPTIONS) this._viewerElement.addEventListener('mousemove', this.handleMouseMove) this._viewerElement.addEventListener('mousewheel', this.handleMouseWheel) this.loadPdb((value && value.pdb) || DEFAULT_PDB) } componentWillUnmount() { this._viewerElement.removeEventListener('mousemove', this.handleMouseMove) this._viewerElement.removeEventListener('mousewheel', this.handleMouseWheel) this.viewer.destroy() } componentDidUpdate(prevProps) { const camera = getAttr(this.props.value, 'camera') const prevPdb = getAttr(prevProps.value, 'pdb') const pdb = getAttr(this.props.value, 'pdb') if (prevPdb !== pdb) { this.loadPdb(pdb) return } if (camera) { this.updateViewerCamera(camera) } else { this.resetViewerCamera() } } loadPdb(id) { this.setState({ isLoading: true }) this.viewer.clear() io.fetchPdb(`//www.rcsb.org/pdb/files/${id}.pdb`, structure => { const ligand = structure.select({rnames: ['SAH', 'RVP']}) this.viewer.spheres('structure.ligand', ligand, {}) this.viewer.cartoon('structure.protein', structure, {boundingSpheres: false}) this.setState({ isLoading: false }) }) } updateViewerCamera = camera => { this.viewer.setCamera(camera.rotation, camera.center, camera.zoom) } resetViewerCamera = () => { this.viewer.autoZoom() } handleMouseMove = () => { if (this.viewer._redrawRequested) { this.saveCamera() } } handleMouseWheel = () => { if (this.viewer._redrawRequested) { this.saveCamera() } } saveCamera = () => { const {onChange, type} = this.props const {_rotation, _center, _zoom} = this.viewer._cam onChange( PatchEvent.from([ setIfMissing({_type: type.name, pdb: DEFAULT_PDB}), set( { rotation: Array.from(_rotation), center: Array.from(_center), zoom: _zoom }, ['camera'] ) ]) ) } handleSelectChange = item => { this.setPdb(item.id) } handlePdbStringChange = event => { const pdbId = event.target.value if (pdbId && pdbId.length === 4) { this.setPdb(pdbId) } } handleResetCamera = () => { this.props.onChange(PatchEvent.from([unset(['camera'])])) } setPdb(pdbId: string) { const {onChange, type} = this.props onChange(PatchEvent.from([set({_type: type.name, pdb: pdbId})])) } getPdbById = id => { return PDBS.find(item => item.id === id) } setViewerElement = element => { this._viewerElement = element } render() { const {value, type, level} = this.props const pdbId = (value && value.pdb) || DEFAULT_PDB const {isLoading} = this.state return ( <Fieldset legend={type.title} level={level} description={type.description}> <Select label="Choose existing…" items={PDBS} onChange={this.handleSelectChange} value={this.getPdbById(pdbId)} /> <TextField label="PDB" value={pdbId} onChange={this.handlePdbStringChange} /> <div style={{height: '500px', width: '100%', position: 'relative', overflow: 'hidden'}}> {isLoading && ( <div style={{ zIndex: 100, backgroundColor: 'rgba(255,255,255,0.8)', width: '100%', height: '100%' }} > <Spinner center /> </div> )} <ActivateOnFocus> <div ref={this.setViewerElement} /> </ActivateOnFocus> </div> <Button onClick={this.handleResetCamera}>Reset camera</Button> </Fieldset> ) } }
JavaScript
0
@@ -3995,16 +3995,8 @@ dbId -: string ) %7B%0A
932c97d216606859ac8b0049c3a615e23681ef21
Fix dz can use new components
packages/strapi-plugin-content-type-builder/utils/attributes.js
packages/strapi-plugin-content-type-builder/utils/attributes.js
'use strict'; const _ = require('lodash'); const toUID = (name, plugin) => { const modelUID = Object.keys(strapi.contentTypes).find(key => { const ct = strapi.contentTypes[key]; if (ct.modelName === name && ct.plugin === plugin) return true; }); return modelUID; }; const fromUID = uid => { const contentType = strapi.contentTypes[uid]; const { modelName, plugin } = contentType; return { modelName, plugin }; }; const hasComponent = model => { const compoKeys = Object.keys(model.attributes || {}).filter(key => { return model.attributes[key].type === 'component'; }); return compoKeys.length > 0; }; const isRelation = attribute => _.has(attribute, 'target') || _.has(attribute, 'model') || _.has(attribute, 'collection'); /** * Formats a component's attributes * @param {Object} attributes - the attributes map * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttributes = model => { return Object.keys(model.attributes).reduce((acc, key) => { acc[key] = formatAttribute(key, model.attributes[key], { model }); return acc; }, {}); }; /** * Fromats a component attribute * @param {string} key - the attribute key * @param {Object} attribute - the attribute * @param {Object} context - function context * @param {Object} context.component - the associated component */ const formatAttribute = (key, attribute, { model }) => { if (_.has(attribute, 'type')) return attribute; // format relations const relation = (model.associations || []).find( assoc => assoc.alias === key ); const { plugin } = attribute; let targetEntity = attribute.model || attribute.collection; if (plugin === 'upload' && targetEntity === 'file') { return { type: 'media', multiple: attribute.collection ? true : false, required: attribute.required ? true : false, }; } else { return { nature: relation.nature, target: targetEntity === '*' ? targetEntity : toUID(targetEntity, plugin), plugin: plugin || undefined, dominant: attribute.dominant ? true : false, targetAttribute: attribute.via || undefined, columnName: attribute.columnName || undefined, targetColumnName: _.get( strapi.getModel(targetEntity, plugin), ['attributes', attribute.via, 'columnName'], undefined ), unique: attribute.unique ? true : false, }; } }; const replaceTemporaryUIDs = uidMap => schema => { return { ...schema, attributes: Object.keys(schema.attributes).reduce((acc, key) => { const attr = schema.attributes[key]; if (attr.type === 'component') { if (_.has(uidMap, attr.component)) { acc[key] = { ...attr, component: uidMap[attr.component], }; return acc; } if (!_.has(strapi.components, attr.component)) { throw new Error('component.notFound'); } } if ( attr.type === 'dynamiczone' && _.intersection(attr.components, Object.keys(uidMap)).length > 0 ) { acc[key] = { ...attr, components: attr.components.map(value => { if (_.has(uidMap, value)) return uidMap[value]; if (!_.has(strapi.components, attr.component)) { throw new Error('component.notFound'); } return value; }), }; return acc; } acc[key] = attr; return acc; }, {}), }; }; module.exports = { fromUID, toUID, hasComponent, isRelation, replaceTemporaryUIDs, formatAttributes, formatAttribute, };
JavaScript
0
@@ -2464,24 +2464,56 @@ %7D;%0A %7D%0A%7D;%0A%0A +// TODO: move to schema builder%0A const replac @@ -3361,38 +3361,29 @@ components, -attr.component +value )) %7B%0A
b408e57be9dc9fa642141b62674e508fd39f10ed
use @ syntax for import
agir/events/components/eventPage/EventDescriptionCard.js
agir/events/components/eventPage/EventDescriptionCard.js
import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; import { DateTime } from "luxon"; import Button from "@agir/front/genericComponents/Button"; import Collapsible from "@agir/front/genericComponents/Collapsible.js"; import Card from "../../../front/components/genericComponents/Card"; import Spacer from "../../../front/components/genericComponents/Spacer"; import style from "@agir/front/genericComponents/_variables.scss"; const DescriptionSection = styled.div` margin: 0; &:empty { margin: 0; } & + & { margin-top: 1rem; } & > * { margin-top: 0; margin-bottom: 1rem; &:empty, &:last-child { margin-bottom: 0; } } img { margin: 10px 0px; } `; const StyledButton = styled(Button)` height: 48px; font-size: 16px; font-weight: 500; border-radius: ${style.borderRadius}; margin: 0 16px; `; const StyledActionButtons = styled.div` display: inline-grid; grid-gap: 0.5rem; grid-template-columns: auto auto; padding: 0.5rem 0; @media (max-width: ${style.collapse}px) { display: grid; grid-template-columns: repeat(auto-fill, minmax(275px, 1fr)); } ${Button} { margin: 0; justify-content: center; && *, && *::before { flex: 0 0 auto; } } ${Button} + ${Button} { margin-left: 0; } `; const EventDescription = ({ illustration, description, isOrganizer, endTime, routes, }) => { return ( <> {description ? ( <Card> <DescriptionSection> <b>L'événement</b> {illustration?.banner && ( <DescriptionSection> <img src={illustration.banner} alt="Image d'illustration de l'événement postée par l'utilisateur" style={{ maxWidth: "100%", height: "auto", maxHeight: "500px", borderRadius: "8px", }} /> </DescriptionSection> )} <Collapsible dangerouslySetInnerHTML={{ __html: description }} fadingOverflow /> <Spacer /> <StyledActionButtons> <StyledButton as="a" href={routes.edit}> Modifier la description </StyledButton> <StyledButton as="a" href={routes.edit}> Ajouter une image d'illustration </StyledButton> </StyledActionButtons> </DescriptionSection> </Card> ) : null} {!description && isOrganizer && endTime > DateTime.local() && ( <Card> <DescriptionSection> <h2>Ajoutez une description !</h2> <p> Donner tous les informations nécessaires aux participants de votre événement. Comment accéder au lieu, quel est le programme, les liens pour être tenu au courant... Et ajoutez une image ! </p> <div> <StyledButton as="a" href={routes.edit}> Ajouter une description </StyledButton> {!illustration?.banner && ( <StyledButton as="a" href={routes.edit}> Ajouter une image d'illustration </StyledButton> )} </div> </DescriptionSection> </Card> )} </> ); }; EventDescription.propTypes = { compteRendu: PropTypes.string, compteRenduPhotos: PropTypes.arrayOf( PropTypes.shape({ image: PropTypes.string, thumbnail: PropTypes.string, }) ), illustration: PropTypes.shape({ banner: PropTypes.string, thumbnail: PropTypes.string, }), description: PropTypes.string, isOrganizer: PropTypes.bool, endTime: PropTypes.instanceOf(DateTime), routes: PropTypes.object, rsvp: PropTypes.string, }; export default EventDescription;
JavaScript
0
@@ -277,32 +277,29 @@ Card from %22 -../../.. +@agir /front/compo @@ -353,16 +353,13 @@ om %22 -../../.. +@agir /fro
e68462264402c61ab3802657a6dce054e40d9ec0
Add xls & ppt support
contentscript.js
contentscript.js
// Avoid recursive frame insertion... var extensionOrigin = 'chrome-extension://' + chrome.runtime.id; if (!location.ancestorOrigins.contains(extensionOrigin)) { var links = document.getElementsByTagName('a'); var pdfLinks = []; Object.keys(links).forEach(function (id) { var link = links[id]; if (link.href.indexOf('.pdf') > -1 || link.href.indexOf('.doc') > -1) { pdfLinks.push(link); } }); pdfLinks.forEach(function (link) { var iframe = document.createElement('iframe'); // Must be declared at web_accessible_resources in manifest.json iframe.src = chrome.runtime.getURL('frame.html') + '?url=' + link.href; // Basic Style iframe.style.cssText = 'display:block;height:600px;width:664px;z-index:99999;border:none;margin-top:10px;margin-bottom:10px;'; // Insert after Link to include in Google doc viewer link.parentNode.insertBefore(iframe, link.nextSibling) }); }
JavaScript
0
@@ -155,16 +155,95 @@ gin)) %7B%0A + // Supported File Types%0A var fileTypes = %5B'.pdf', '.doc', '.xls', '.ppt'%5D;%0A%0A var li @@ -385,46 +385,50 @@ -if (link.href.indexOf('.pdf') %3E -1 %7C%7C +fileTypes.some(function (ext) %7B%0A if ( link @@ -441,22 +441,19 @@ indexOf( -'.doc' +ext ) %3E -1) @@ -460,16 +460,18 @@ %7B%0A + + pdfLinks @@ -487,17 +487,48 @@ k);%0A -%7D + return true;%0A %7D%0A %7D); %0A %7D);%0A%0A
c339e575c51ce62e409b33c05a7de4173d13126b
Fix toJSON call
model/base.js
model/base.js
// db.Base extensions. Currently purely about base methods needed for JSON snapshots 'use strict'; var memoize = require('memoizee/plain') , ensureDb = require('dbjs/valid-dbjs'); module.exports = memoize(function (db) { ensureDb(db).Base.prototype.__descriptorPrototype__.setProperties({ // Field (label: value) JSON serializer fieldToJSON: function (ignore) { var value = this.object.get(this.key), result; if (value.forEach && !this.nested && this.multiple) { result = []; value.forEach(function (value) { result.push(this.type.valueToJSON(value, this)); }, this); value = result; } else { value = this.type.valueToJSON(value, this); } return { label: this.dynamicLabelKey ? this.object.get(this.dynamicLabelKey) : this.label, value: value }; } }); db.Base.prototype.defineProperties({ // Whether value should be considered as empty isEmpty: { type: db.Function }, toJSON: { type: db.Function } }); return db.Base.defineProperties({ // Whether provided value should be considered empty isValueEmpty: { type: db.Function, value: function (value) { if (value == null) return true; if (typeof value.isEmpty !== 'function') return false; return value.isEmpty(); } }, // Returns JSON representation of provided value (in many cases it's same as value) valueToJSON: { type: db.Function, value: function (value, descriptor) { if (value == null) return value; if (this.database.isObjectType(this)) { if (typeof value.toJSON === 'function') return value.toJSON(this); return value.toString(descriptor); } return (new this(value)).toString(descriptor); } } }); }, { normalizer: require('memoizee/normalizers/get-1')() });
JavaScript
0.000648
@@ -1544,20 +1544,26 @@ .toJSON( -this +descriptor );%0A%09%09%09%09r
f7ffc12c320883bb591e8e0a8099ed2e262c6365
Fix buffer size
bin/tcap.js
bin/tcap.js
#!/usr/bin/env node 'use strict'; var commander = require('commander'); var TChannelTracker = require('../tchannel-tracker.js'); var ansi = require('../ansi.js'); if (require.main === module) { main(); } function main(arg) { commander.version(require('../package.json').version) .option('-i --interface [interface', 'network interface name for capture (defaults to first with an address)', '') .option('-f --filter [filter]', 'packet filter in pcap-filter(7) syntax (default: all TCP packets on port 4040)') .option('-b --buffer-size [mb]', 'size in MiB to buffer between libpcap and app (default: 10)') .option('--no-color', 'disables colors (default: not attached to a tty)') .parse(process.argv); var color = commander.color && !!process.stdout.isTTY; ansi.no_color = !color; var bufferSizeMb = commander.bufferSize || 10; checkUid(); var tracker = new TChannelTracker({ interface: commander.interface, filter: commander.filter, bufferSize: bufferSizeMb }); tracker.listen(); } function checkUid() { if (process.getuid() !== 0) { console.log(ansi.red(ansi.bold("Warning: not running with root privs, which are usually required for raw packet capture."))); console.log(ansi.red("Trying to open anyway...")); } }
JavaScript
0.000009
@@ -1049,16 +1049,30 @@ erSizeMb + * 1024 * 1024 %0A %7D);
6a7dc4f4e3e1e0ac0bd3922f022ce08b12ffd535
Add Chapter 09, exercise 2
eloquent_js_exercises/chapter09/chapter09_ex02.js
eloquent_js_exercises/chapter09/chapter09_ex02.js
var text = "'I'm the cook,' he said, 'it's my job.'"; console.log( text.replace(/([a-z])'([a-z])/gi, "$1~~$2") .replace(/'/g, "\"") .replace(/~~/g, "'"));
JavaScript
0
@@ -1,7 +1,7 @@ -var +let tex @@ -47,16 +47,36 @@ job.'%22;%0A +// Change this call. %0Aconsole @@ -80,25 +80,16 @@ ole.log( -%0A text.rep @@ -99,93 +99,78 @@ e(/( -%5Ba-z%5D)'(%5Ba-z%5D +%5CW%7C%5E)'%7C'(%5CW%7C$ )/g -i , -%22$1~~$2%22)%0A .replace(/'/g, %22%5C%22%22)%0A .replace(/~~/g, %22'%22)); +'$1%22$2'));%0A// %E2%86%92 %22I'm the cook,%22 he said, %22it's my job.%22 %0A
4fc97327ea6f5d2750e55ee99e030690ba3f0023
Move Equalizer project to top of file
data/projects.js
data/projects.js
// When you add a new project, please add it to the top of the array! export default [ { name: 'Bornycentre', description: 'An app to get your Bornycentre built with Cycle.js', repository: 'https://github.com/teawaterwire/bornycentre', homepage: 'http://bornycent.re/', screenshot: 'data/images/bornycentre.png' }, { name: 'TAMS Tools', description: 'A set of tools for teaching and learning computer science built with Cycle.js', repository: 'https://github.com/laszlokorte/tams-tools', homepage: 'https://thesis.laszlokorte.de/', screenshot: 'data/images/tams-tools.png' }, { name: 'Cycle Conway', description: 'Conway\'s Game of Life built with Cycle.js', repository: 'https://github.com/raquelxmoss/cycle-conway', homepage: 'http://raquelxmoss.github.io/cycle-conway', screenshot: 'data/images/cycle-conway.png' }, { name: 'Hangman', description: 'Hangman game built with Cycle.js', repository: 'https://github.com/class-ideas/cyclejs-hangman', homepage: 'http://class-ideas.github.io/cyclejs-hangman/', screenshot: 'data/images/hangman.png' }, { name: 'Concentration', description: 'A card game about memory and concentration', repository: 'https://github.com/class-ideas/cyclejs-concentration', homepage: 'http://class-ideas.github.io/cyclejs-concentration/', screenshot: 'data/images/concentration.png' }, { name: 'TodoMVC', description: 'TodoMVC example implemented in Cycle.js', repository: 'https://github.com/cyclejs/todomvc-cycle', homepage: 'http://cycle.js.org/todomvc-cycle/', screenshot: 'data/images/todomvc.png' }, { name: 'Cycle Music Sequencer', description: 'An easy way to make melodies in your browser, powered by Cycle.js and Tone.js', repository: 'https://github.com/widdershin/cycle-music-sequencer/', homepage: 'http://widdersh.in/cycle-music-sequencer/', screenshot: 'data/images/cycle-music-sequencer.png' }, { name: 'Tricycle', description: 'Try Cycle.js in your browser, no setup required', repository: 'https://github.com/widdershin/tricycle/', homepage: 'http://widdersh.in/tricycle', screenshot: 'data/images/tricycle.png' }, { name: 'Ghostwriter', description: 'Autocompleting rap/rhyme editor', repository: 'https://github.com/widdershin/ghostwriter', homepage: 'http://widdersh.in/ghostwriter', screenshot: 'data/images/ghostwriter.png' }, { name: 'Powerpeople', description: 'An app used internally at Powershop to help staff learn the names of their coworkers. Shown here with Pokemon as an example.', repository: 'https://github.com/Widdershin/powerpeople', homepage: 'https://github.com/Widdershin/powerpeople', screenshot: 'data/images/powerpeople.png' }, { name: 'RxMarbles', description: 'Interactive diagrams of Rx Observables', repository: 'https://github.com/staltz/rxmarbles', homepage: 'http://rxmarbles.com/', screenshot: 'data/images/rxmarbles.png' }, { name: 'Equalizer', description: 'Web audio player with equalizer', repository: 'https://github.com/Bloomca/equalizer', homepage: 'http://bloomca.github.io/equalizer/', screenshot: 'data/images/equalizer.png' } ];
JavaScript
0
@@ -81,16 +81,254 @@ fault %5B%0A + %7B%0A name: 'Equalizer',%0A description: 'Web audio player with equalizer',%0A repository: 'https://github.com/Bloomca/equalizer',%0A homepage: 'http://bloomca.github.io/equalizer/',%0A screenshot: 'data/images/equalizer.png'%0A %7D,%0A%0A %7B%0A @@ -3308,246 +3308,79 @@ %0A %7D -,%0A%0A %7B%0A name: 'Equalizer',%0A description: 'Web audio player with equalizer',%0A repository: 'https://github.com/Bloomca/equalizer',%0A homepage: 'http://bloomca.github.io/equalizer/',%0A screenshot: 'data/images/equalizer.png'%0A %7D%0A%5D; +%0A%5D;%0A%0A// When you add a new project, please add it to the top of the array! %0A
96258a4d3e3b592d11de3a2edfceb874129be270
Add correlationId to message options
Response.js
Response.js
'use strict' class Response { constructor(messenger, msg) { this.messenger = messenger this.queue = msg.properties.replyTo this.corr = msg.properties.corr } send (msg) { if(this.queue){ this.messenger.publish( this.queue, msg, {correlationId: this.corr} ) } } ok (payload) { this.send({status: 'ok', content: payload}) } error (payload) { this.send({status: 'ok', content: payload}) } } module.exports = Response
JavaScript
0.000001
@@ -271,43 +271,8 @@ sg,%0A - %7BcorrelationId: this.corr%7D%0A @@ -323,32 +323,58 @@ d(%7Bstatus: 'ok', + correlationId: this.corr, content: payloa @@ -430,16 +430,42 @@ s: 'ok', + correlationId: this.corr, content
0e3e5a0b7fdbc002cf304ac1026249e56dab342c
Allow fine acceleration on mobile
controller/game.js
controller/game.js
var Player = require('../model/player'); var Integrator = require('../model/integrator'); var Team = require('../model/team'); var Obstacle = require('../model/obstacle'); var Projectile = require('../model/projectile'); var Physics = require('physicsjs'); // Constructor function Game() { // Physics this.bounds = {x: 800, y: 450}; this.world = Physics(); this.extensions(); this.behaviors(); this.integrators(); this.subscribers(); // Empty state this.players = {}; this.teams = []; this.obstacles = []; this.projectiles = []; // Setup game this.addObstacles(1); this.addTeams(['red', 'blue']); } // Instance methods Game.prototype.extensions = function() { Player.extension(); Projectile.extension(); Integrator.extension(); Obstacle.extension(); }; Game.prototype.behaviors = function() { this.world.add([ Physics.behavior('body-impulse-response', { check: 'collisions:desired' }), Physics.behavior('body-collision-detection'), Physics.behavior('sweep-prune'), Physics.behavior('edge-collision-detection', { aabb: Physics.aabb(0, 0, 800, 450), restitution: 0.6, cof: 0.2 }) ]); }; Game.prototype.integrators = function() { this.world.add(Physics.integrator('verlet-custom')); } Game.prototype.subscribers = function() { this.world.on('collisions:detected', function(data){ for(var i=0; i<data.collisions.length; i++){ var collision = data.collisions[i]; if(collision.bodyA.name === 'projectile' && collision.bodyB.name === 'player' || collision.bodyA.name === 'player' && collision.bodyB.name === 'projectile'){ var player = (collision.bodyA.name === 'player') ? collision.bodyA : collision.bodyB; var projectile = (collision.bodyA.name === 'projectile') ? collision.bodyA : collision.bodyB; if(projectile.active){ if(!projectile.newborn || projectile.owner.shooter !== player.owner) this.playerHit(player.owner, projectile.owner); }else if(player.owner.ammo < player.owner.maxAmmo){ data.collisions.splice(i, 1); // Do not record collision if(player.state.pos.dist(projectile.state.pos) < player.radius) this.ammoPickup(player.owner, projectile.owner); } } } this.world.emit('collisions:desired', data); }.bind(this)); } Game.prototype.addPlayer = function(id) { if(this.teams.length < 1) return; var smallestTeam = this.teams.sort(function(a, b) {return (a.length > b.length) ? 1 : -1;})[0]; var player = new Player(id, smallestTeam, 100, 100); this.players[id] = player; this.world.add(player.body); }; Game.prototype.removePlayer = function(id) { var player = this.players[id]; player.delete(); delete this.players[id]; }; Game.prototype.playerHit = function(player, projectile) { player.alive = false; console.log('kill'); } Game.prototype.ammoPickup = function(player, projectile) { player.ammo++; projectile.delete(); this.projectiles.splice(this.projectiles.indexOf(projectile), 1); } Game.prototype.addTeams = function(names) { for(var index=0; index<names.length; index++){ this.teams.push(new Team(names[index])); } } Game.prototype.addObstacles = function(count) { for(var index=0; index<count; index++){ var obstacle = new Obstacle(400, 225); this.obstacles.push(obstacle); this.world.add(obstacle.body); } } Game.prototype.reset = function() { this.forEachPlayer(function(player) {this.removePlayer(player.id);}.bind(this)); }; Game.prototype.state = function(callback) { var players = []; this.forEachPlayer(function(player) { players.push(player.toState()); }); return { 'players': players, 'obstacles': this.obstacles.map(function(obstacle) {return obstacle.toState();}), 'projectiles': this.projectiles.map(function(projectile) {return projectile.toState();}) }; }; Game.prototype.forEachPlayer = function(callback) { for(var id in this.players) { callback(this.players[id]); } }; Game.prototype.tick = function() { this.world.step(); }; Game.prototype.acceleratePlayer = function(id, x, y) { var player = this.players[id]; if(player != undefined && player.alive){ player.body.accelerate(Physics.vector(x, y).normalize().mult(player.body.acceleration)); player.body.sleep(false); } }; Game.prototype.addProjectile = function(id, x, y) { var player = this.players[id]; if(player != undefined && player.alive && player.ammo>0){ player.ammo--; var projectile = new Projectile(this.players[id]); projectile.accelerate(x, y); this.world.add(projectile.body); this.projectiles.push(projectile); } } // Export class module.exports = Game;
JavaScript
0.000001
@@ -4248,18 +4248,58 @@ y). -normalize( +clamp(Physics.vector(-1, -1), Physics.vector(1, 1) ).mu
5fe1c4b383943b31f0edae8ba40f6dad4d977fcd
Fix empty post message.
controller/room.js
controller/room.js
var Config = require('../config'); var Common = require('./common'); var Rooms = require('../data/rooms'); var rooms = new Rooms(); var addClientToRoom = function (request, roomId, clientId, isLoopback, callback) { var key = Common.getCacheKeyForRoom(request.headers.host, roomId); rooms.createIfNotExist(key, function (error, room) { var error = null; var isInitiator = false; var messages = []; var occupancy = room.getOccupancy(); if (occupancy >= 5) { error = Config.constant.RESPONSE_ROOM_FULL; callback(error, { messages: messages, room_state: room.toString() }); return; } else if (room.hasClient(clientId)) { error = Config.constant.RESPONSE_DUPLICATE_CLIENT; callback(error, { messages: messages, room_state: room.toString() }); return; } else { room.join(clientId, function (error, client, otherClient) { if (error) { callback(error, { messages: messages, room_state: null }); return; } if (client.isInitiator && isLoopback) { room.join(Config.constant.LOOPBACK_CLIENT_ID); } var messages = otherClient ? otherClient.messages : messages; if (otherClient) otherClient.clearMessages(); console.log('Added client ' + clientId + ' in room ' + roomId); callback(null, { is_initiator: client.isInitiator, messages: messages, room_state: room.toString() }); }); } }); }; var saveMessageFromClient = function (host, roomId, clientId, message, callback) { var text = message; var key = Common.getCacheKeyForRoom(host, roomId); rooms.get(key, function (error, room) { if (!room) { console.warn('Unknown room: ' + roomId); callback({ error: Config.constant.RESPONSE_UNKNOWN_ROOM }); return; } else if (!room.hasClient(clientId)) { console.warn('Unknown client: ' + clientId); callback({ error: Config.constant.RESPONSE_UNKNOWN_CLIENT }); return; } else if (room.getOccupancy() > 5) { callback(null, false); } else { var client = room.getClient(clientId); client.addMessage(text); console.log('Saved message for client ' + clientId + ':' + client.toString() + ' in room ' + roomId); callback(null, true); return; } }); }; var sendMessageToCollider = function (request, roomId, clientId, message, callback) { console.log('Forwarding message to collider from room ' + roomId + ' client ' + clientId); var wssParams = Common.getWSSParameters(request); var wssHost = Url.parse(wssParams.wssPostUrl); var postOptions = { host: wssHost.hostname, port: wssHost.port, path: '/' + roomId + '/' + clientId, method: 'POST' }; var postRequest = https.request(postOptions, function (result) { if (result.statusCode == 200) { callback(null, { result: 'SUCCESS' }); return; } else { console.error('Failed to send message to collider: ' + result.statusCode); callback(result.statusCode); return; } }); postRequest.write(message); postRequest.end(); }; var removeClientFromRoom = function (host, roomId, clientId, callback) { var key = Common.getCacheKeyForRoom(host, roomId); rooms.get(key, function (error, room) { if (!room) { console.warn('remove_client_from_room: Unknown room: ' + roomId); callback(Config.constant.RESPONSE_UNKNOWN_ROOM, { room_state: null }); return; } else if (!room.hasClient(clientId)) { console.warn('remove_client_from_room: Unknown client: ' + clientId); callback(Config.constant.RESPONSE_UNKNOWN_CLIENT, { room_state: null }); return; } else { room.removeClient(clientId, function (error, isRemoved, otherClient) { if (room.hasClient(Config.constant.LOOPBACK_CLIENT_ID)) { room.removeClient(Config.constant.LOOPBACK_CLIENT_ID, function (error, isRemoved) { return; }); } else { if (otherClient) { otherClient.isInitiator = true; } } callback(null, { room_state: room.toString() }); }); } }); }; exports.main = { handler: function (request, reply) { var roomId = request.params.roomId; var key = Common.getCacheKeyForRoom(request.headers['host'], roomId); rooms.get(key, function (error, room) { if (room) { console.log('Room ' + roomId + ' has state ' + room.toString()); if (room.getOccupancy() >= 5) { console.log('Room ' + roomId + ' is full'); reply.view('full_template', {}); return; } } var params = Common.getRoomParameters(request, roomId, null, null); reply.view('index_template', params); }); } }; exports.join = { handler: function (request, reply) { var roomId = request.params.roomId; var clientId = Common.generateRandom(8); var isLoopback = request.params.debug == 'loopback'; addClientToRoom(request, roomId, clientId, isLoopback, function(error, result) { if (error) { console.error('Error adding client to room: ' + error + ', room_state=' + result.room_state); reply({ result: error, params: result }); return; } var params = Common.getRoomParameters(request, roomId, clientId, result.is_initiator); params.messages = result.messages; reply({ result: 'SUCCESS', params: params }); console.log('User ' + clientId + ' joined room ' + roomId); console.log('Room ' + roomId + ' has state ' + result.room_state); }); } }; exports.message = { handler: function (request, reply) { var roomId = request.params.roomId; var clientId = request.params.clientId; var message = request.body; saveMessageFromClient(request.headers['host'], roomId, clientId, message, function (error, result) { if (error) { reply({ result: error }); return; } if (result) { reply({ result: 'SUCCESS' }); } else { sendMessageToCollider(request, roomId, clientId, message, function (error, result) { if (error) { reply('').code(500); } if (result) { reply(result); } }); } }); } }; exports.leave = { handler: function (request, reply) { var roomId = request.params.roomId; var clientId = request.params.clientId; removeClientFromRoom(request.headers['host'], roomId, clientId, function (error, result) { if (error) { console.log('Room ' + roomId + ' has state ' + result.room_state); } reply(''); }); } };
JavaScript
0.000468
@@ -6016,12 +6016,15 @@ est. -body +payload ;%0A%0A
ba30c5cea4baa2ff57061c3146a7ee2f96e01528
Fix error page.
errors/browser/admin/views/errors-page.js
errors/browser/admin/views/errors-page.js
var ErrorsCollection = require('../collections/errors'); var ErrorView = require('./error'); module.exports = require('ridge/views/page').extend({ events: { 'click button[data-command="removeAll"]': 'removeAll', 'click button[data-command="removeFiltered"]': 'removeFiltered', 'click button[data-command="removePage"]': 'removePage' }, removeAll: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors', success: function() { _view.fetch(null, this.state.get('query')); } }); }, removeFiltered: function() { var _view = this; $.ajax({ method: 'DELETE', url: '/api/errors?' + this.state.get('query'), success: function() { _view.fetch(null, this.state.get('query')); } }); }, removePage: function() { var _view = this; _.invokeMap(this.modelViews, 'delete'); this.modelViews = []; this.fetch(null, this.state.get('query')); }, elements: { container: '.collection.container' }, subviews: { paginations: [ '.pagination', require('ridge/views/pagination'), { template: 'admin/pagination', multi: true } ], search: [ '.search', require('ridge/views/search') ] }, initialize: function(options) { this.collection = new ErrorsCollection(); this.listenTo(this.collection, 'reset', this.reset); this.listenTo(this.state, 'change:query', this.fetch); }, fetch: function(state, query) { this.collection.fetch({ reset: true, data: query }); }, attach: function() { this.collection.reset({ totalCount: this.state.get('totalCount'), errors: this.state.get('errors') }, { parse: true }); }, reset: function (models, options) { _.invokeMap(this.modelViews, 'remove'); this.modelViews = []; models.each(this.renderModel.bind(this)); }, renderModel: function(model) { this.modelViews.push(new ErrorView({ model: model, data: this.data, }).enter(this.elements.container)); }, });
JavaScript
0
@@ -478,36 +478,37 @@ iew.fetch(null, -this +_view .state.get('quer @@ -636,20 +636,21 @@ ors?' + -this +_view .state.g @@ -701,36 +701,37 @@ iew.fetch(null, -this +_view .state.get('quer
cf479bafab4275c456ecbaf6143f0e42003f2ed0
convert form field FieldValue to lower case string
red/ubicall/plist/nodes/view/zendesk-ticket.js
red/ubicall/plist/nodes/view/zendesk-ticket.js
var plistUtils = require("../utils.js"); var log = require("../../../../log"); // form object element as keys will be mapped to plist element as values var PlistMapper = { type: "ScreenType", name: "ScreenTitle", help: "FormTitle", fields: "FormFields" }; // form field object element as keys will be mapped to plist FormField element as values var FieldPlistMapper = { id: "FieldValue", title_in_portal: "FieldLabel", type: "FieldType", required_in_portal: "required", editable_in_portal: "editable", description: "Placeholder", system_field_options: "select_field_options" }; // static fields in zendesk, it not custom field var zendeskSystemFields = [ "subject", "description", "status", "tickettype", "priority", "group", "assignee" ]; // zendesk field type as keys will be value of FieldPlistMapper[type] var FieldTypePlistMapper = { subject: "Text Area", description: "Text Area", textarea: "Text Area", text: "Text Field", date: "Date", integer: "Integer", decimal: "Decimal", tickettype: "Selector", priority: "Selector", status: "Selector", checkbox: "Check Box" }; var TYPE = "ZendeskForm"; /** @param node ```javascript { name : "submit an issue", help : "fill next form to submit an issue", id: "ckbf465.68kjvg", type: "view-zendesk-ticket-form", wires: [["98hg3cg4.knh897"]], x: 455, y: 442, z: "17032888.e8fcd7", } ``` @return ```xml <key>ckbf465.68kjvg</key> <dict> <key>ScreenType</key> <string>ZendeskForm</string> <key>ScreenTitle</key> <string>submit an issue</string> <key>FormTitle</key> <string>fill next form to submit an issue</string> <key>__next</key> <dict> <key>id</key> <string>98hg3cg4.knh897</string> </dict> <key>FormFields</key> <array> <dict> <key>FieldLabel</key> <string>Name</string> <key>FieldValue</key> <string>Name</string> <key>FieldType</key> <string>Text Field</string> <key>required</key> <true/> <key>Placeholder</key> <string>John Smith</string> </dict> <dict> <key>FieldLabel</key> <string>Email</string> <key>FieldValue</key> <string>27251078</string> <key>FieldType</key> <string>Text Field</string> <key>required</key> <true/> <key>Placeholder</key> <string>JohnSmith@exmaple.com</string> </dict> <dict> <key>FieldLabel</key> <string>Birth Date</string> <key>FieldValue</key> <string>27251088</string> <key>FieldType</key> <string>Date</string> <key>required</key> <true/> <key>Placeholder</key> <string>31/12/1990</string> </dict> <dict> <key>FieldLabel</key> <string>Type</string> <key>FieldValue</key> <string>Type</string> <key>FieldType</key> <string>Selector</string> <key>required</key> <false/> <key>Placeholder</key> <string>Request type</string> <key>select_field_options</key> <array> <dict> <key>value</key> <string>question</string> <key>name</key> <string>Question</string> </dict> <dict> <key>value</key> <string>incident</string> <key>name</key> <string>Incident</string> </dict> <dict> <key>value</key> <string>problem</string> <key>name</key> <string>Problem</string> </dict> <dict> <key>value</key> <string>task</string> <key>name</key> <string>Task</string> </dict> </array> </dict> </array> </dict> ``` **/ function createZendeskForm(node) { // TODO for all nodes types - assert node has id , type // TODO for info node - assert node has name, wires `nextWires[0][0]`, fields `with at least one Field` // help is optional // custom plist node type node.type = TYPE || node.type; var _form = {}; for (var key in PlistMapper) { if (PlistMapper.hasOwnProperty(key)) { _form[PlistMapper[key]] = node[key]; } } _form[PlistMapper.fields] = createFormFields(node.fields); // generate __next key var nextWires = node.wires; if (nextWires.length > 0 && nextWires[0][0]) { // create __next node if nextWires is not empty // note only first next wire is used _form.__next = {}; _form.__next.id = nextWires[0][0]; } log.info("form " + JSON.stringify(_form)); return _form; } /** <array> <dict> <key>FieldLabel</key> <string>Name</string> <key>FieldValue</key> <string>Name</string> <key>FieldType</key> <string>Text Field</string> <key>required</key> <true/> <key>Placeholder</key> <string>John Smith</string> </dict> </array> **/ function createFormFields(fields) { var _items = []; if (!fields) { // TODO should throw error return _items; } for (var i = 0; i < fields.length; i++) { var field = fields[i]; // https://developer.zendesk.com/rest_api/docs/core/ticket_fields#list-ticket-fields if (!field["visible_in_portal"] || !field["active"] ) continue; //Whether this field is available to end users or active var item = {}; for (var key in FieldPlistMapper) { if (FieldPlistMapper.hasOwnProperty(key) && (field[key] !== null && field[key] !== undefined)) { item[FieldPlistMapper[key]] = field[key]; } } // if field["type"] is one of zendesk system fields @variable zendeskSystemFields => FieldValue will be same as field["title"] if(zendeskSystemFields.indexOf(field["type"]) > -1){ item["FieldValue"] = field["title"].toLowerCase(); } // zendesk field type as keys will be value of FieldPlistMapper[type] var __fieldType = FieldTypePlistMapper[field["type"]]; item[FieldPlistMapper["type"]] = __fieldType; // ignore this field if we not support mapping of this element type yet if (!__fieldType) { log.info("not support field " + field["type"] + "!!!") } else { _items.push(item); } } return _items; } module.exports = { createZendeskForm: createZendeskForm }
JavaScript
0.999997
@@ -5695,16 +5695,78 @@ %22title%22%5D +;%0A %7D%0A item%5B%22FieldValue%22%5D = item%5B%22FieldValue%22%5D.toString() .toLower @@ -5773,22 +5773,16 @@ Case();%0A - %7D%0A %0A
c2bd377e1fb3c780bb4bea59038b2cadf8ef5624
Fix broken link in docs (#1399)
docs/src/pages/index.js
docs/src/pages/index.js
import React from 'react'; import classnames from 'classnames'; import Layout from '@theme/Layout'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import useBaseUrl from '@docusaurus/useBaseUrl'; import styles from './styles.module.css'; const heroImageUrl = 'img/pinch-reworked.svg'; const sectionImageUrl = 'img/swm-react-native-reanimated-illu-kon-06.svg'; const screenshotUrl = 'gifs/sampleswipeable.gif'; const boxes = [ { title: <>Use platform native gesture recognizers👍</>, description: ( <> With Gesture Handler touch stream handling happens on the UI thread and uses APIs native to each platform. </> ), }, { title: <>Works with Animated API</>, description: ( <> Pass and process gesture specific data to React Native's Animated library and build smooth gesture based experiences with useNativeDriver flag. </> ), }, { title: <>Use cross platform components built with Gesture Handler</>, description: ( <> Gesture Handler library ships with a set of components that aims to provide best possible interations such as SwipeableRow or Drawer. More components to come! </> ), }, { title: <>Available in Expo.io</>, description: ( <> Gesture Handler is available for you to use with{' '} <a href="https://expo.io/">Expo</a> and to play with on{' '} <a href="https://snack.expo.io/">Snack</a>. </> ), }, ]; const bannerTitle = 'React Native Gesture Handler provides native-driven gesture management APIs for building best possible touch-based experiences in React Native.'; const bannerDescription = 'eact Native Reanimated provides a more comprehensive, low level abstraction for the Animated library API to be built on top of and hence allow for much greater flexibility especially when it comes to gesture based interactions.'; const blogUrl = 'https://blog.swmansion.com/introducing-reanimated-2-752b913af8b3'; const exampleUrl = 'https://github.com/software-mansion/react-native-reanimated/tree/master/Example'; const playgroundUrl = 'https://github.com/software-mansion-labs/reanimated-2-playground'; const tryItOutDecription = 'Check out the documentation and learn how to quickly get up and running with Gesture Handler. Take a look at our API guides to get familiarize with it.'; function InfoBox({ title, description }) { return ( <div className="col col--6 info-box"> <h3>{title}</h3> <p>{description}</p> </div> ); } function Hero() { const context = useDocusaurusContext(); const { siteConfig = {} } = context; return ( <header className={classnames('hero hero--secondary', styles.heroBanner)}> <div className="container"> <div className="row row-hero"> <div className="col col--5 hero-content"> <h1 className="hero__title">{siteConfig.title}</h1> <p className="hero__p">{siteConfig.tagline}</p> <div className={classnames('hero-buttons', styles.buttons)}> <Link className={classnames( 'button button--primary button--lg', styles.getStarted )} to={useBaseUrl('docs/')}> View Docs </Link> <Link className={classnames( 'button button--primary button--lg', styles.getStarted )} to="https://snack.expo.io/@adamgrzybowski/react-native-gesture-handler-demo"> Try demo app on Expo </Link> </div> </div> <div className="col col--7 hero-image" style={{ backgroundImage: `url(${heroImageUrl})`, }} /> </div> </div> </header> ); } function SectionImage() { return ( <div className="col col--4 section-image" style={{ backgroundImage: `url(${sectionImageUrl})`, backgroundSize: 'contain', backgroundPosition: 'center center', backgroundRepeat: 'no-repeat', }} /> ); } function SectionBoxes() { return ( <div className="col col--12 section-boxes"> {boxes && boxes.length > 0 && ( <div className="row box-container"> {boxes.map((props, idx) => ( <InfoBox key={idx} {...props} /> ))} </div> )} </div> ); } function BannerSection() { return ( <section> <div className="container"> <div className="row"> <div className="col col--4 section-image" style={{ backgroundImage: `url(${sectionImageUrl})`, backgroundSize: 'contain', backgroundPosition: 'center center', backgroundRepeat: 'no-repeat', }} /> <div className="col col--8"> <h1>{bannerTitle}</h1> <p className="hero__p">{bannerDescription}</p> <div className={classnames('hero-buttons', styles.buttons)}> <Link className={classnames( 'button button--primary button--lg', styles.getStarted )} to={useBaseUrl('docs/installation')}> Getting Started Guide </Link> </div> </div> </div> </div> </section> ); } function Home() { const context = useDocusaurusContext(); const { siteConfig = {} } = context; return ( <Layout title={`Hello from ${siteConfig.title}`} description="Description will go into a meta tag in <head />"> <Hero /> <main> <section> <div className="container"> <div className="row row--box-section"> <SectionBoxes /> </div> </div> </section> {/* <BannerSection /> */} <section> <div className="container container--center"> <div className="row row--center"> <div className="col col--7 text--center col--bottom-section"> <h2>Try it out</h2> <p>{tryItOutDecription}</p> <p> Try our showcase app or{' '} <a href="https://snack.expo.io/@adamgrzybowski/react-native-gesture-handler-demo"> get it here using Expo </a> . Or just <a href="/docs/example">go to this page</a> to see how you can run it locally with React Native on both Android and iOS. </p> <div className="item screenshot-container"> <img src={screenshotUrl} alt="Gesture handler screenshot" /> </div> </div> </div> </div> </section> </main> </Layout> ); } export default Home;
JavaScript
0
@@ -6614,19 +6614,54 @@ just - %3Ca href=%22/ +%7B' '%7D%0A %3CLink to=%7BuseBaseUrl(' docs @@ -6668,17 +6668,20 @@ /example -%22 +/')%7D %3Ego to t @@ -6694,17 +6694,18 @@ ge%3C/ -a%3E to see +Link%3E%7B' '%7D %0A @@ -6719,16 +6719,23 @@ +to see how you @@ -6782,16 +6782,8 @@ both - Android %0A @@ -6797,16 +6797,24 @@ +Android and iOS.
b5d7847f3a817140f24f07c1165269f38e0e24c6
Update version string to 2.6.0-pre.4.dev
version.js
version.js
if (enyo && enyo.version) { enyo.version["enyo-cordova"] = "2.6.0-pre.4"; }
JavaScript
0
@@ -65,13 +65,17 @@ .0-pre.4 +.dev %22;%0A%7D%0A
a04cf25a556f0e10a1399a3c37570bc25e2f1d4f
Fix name of the SJ ssid
modules/SJ.js
modules/SJ.js
'use strict'; // Example response /* data({ "version":"1.6", "ip":"10.101.5.100", "mac":"00:05:69:4B:74:59", "online":"0", "timeleft":"0", "authenticated":"1", "userclass":"2", "expires":"Never", "timeused":"175", "data_download_used":"131427344", "data_upload_used":"745893", "data_total_used":"132173237", "data_download_limit":"0", "data_upload_limit":"0", "data_total_limit":"209715200", "bandwidth_download_limit":"0", "bandwidth_upload_limit":"0" }); */ var request = require( 'request' ); module.exports = { name: 'SJ', percentageLimit: 95, shouldRefresh: function( callback ){ var percentage, _this = this; request( 'http://www.ombord.info/api/jsonp/user/?callback=data&_' + Date.now(), function( error, response, data ){ if( error ){ // We should probably do something here // exports.log doesn't seem to work for some reason, it's not really needed anyway // module.parent.exports.log( 'Unable to load quota' ); return false; } // Make sure there is no newlines or spaces or anything data.trim(); // Strip the JSONP stuff, we really don't need it data = data.substr( 5 ); // Strip "data(" data = data.substr( 0, data.length - 2 ); // Strip the final ");" // Should be raw JSON now data = JSON.parse( data ); // Get the percentage used percentage = Math.round( data.data_total_used / data.data_total_limit * 100 ); if( percentage >= _this.percentageLimit ){ callback( true, percentage ); } else { callback( false, percentage ); } }); } };
JavaScript
0.999988
@@ -587,12 +587,12 @@ -name +ssid : 'S
554cf9a8bad27f0b5701ed236290f581587e1531
add isFeature function
meteor/imports/helpers.js
meteor/imports/helpers.js
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2014 Mozilla Corporation */ import { _ } from 'meteor/underscore'; // helper functions getSetting=function (settingKey){ // prefer Meteor.settings.public.mozdef // then the subscribed collection if ( _.has(Meteor.settings.public.mozdef,settingKey) ){ return Meteor.settings.public.mozdef[settingKey]; }else{ if ( mozdefsettings.findOne({ key : settingKey }) ){ return mozdefsettings.findOne({ key : settingKey }).value; }else{ return ''; } } };
JavaScript
0.000124
@@ -728,8 +728,199 @@ %7D%0A%7D;%0A%0A +isFeature = function(featureName)%7B%0A if ( features.findOne(%7B'name':featureName%7D) )%7B%0A return features.findOne(%7B'name':featureName%7D).enabled;%0A %7Delse%7B%0A return true;%0A %7D%0A%7D;%0A%0A
04c10207973f28827d1914f233511f3f1cc3de2f
Fix bs modal closing when datepicker hide event is triggered
app/admin/formwidgets/datepicker/assets/js/datepicker.js
app/admin/formwidgets/datepicker/assets/js/datepicker.js
/* * Color Picker plugin * * Data attributes: * - data-control="datePicker" - enables the plugin on an element */ +function ($) { "use strict"; // FIELD DATEPICKER CLASS DEFINITION // ============================ var DatePicker = function (element, options) { this.options = options this.$el = $(element) this.picker = null this.$dataLocker = null this.bindPicker() } DatePicker.DEFAULTS = { autoclose: true, mode: 'date', format: 'dd-mm-yyyy', todayHighlight: true, templates: { leftArrow: '<i class="fa fa-long-arrow-left"></i>', rightArrow: '<i class="fa fa-long-arrow-right"></i>' }, language: 'en', } DatePicker.prototype.bindPicker = function () { this.$dataLocker = this.$el.parent('div').find('[data-datepicker-value]') if (this.options.mode === 'datetime') { this.$el.datetimepicker({ format: this.options.format, icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-arrow-up", down: "fa fa-arrow-down" } }); this.$el.on('change.datetimepicker', $.proxy(this.onSelectDateTimePicker, this)) } else { this.options.language = this.options.language.replace('_', '-').split('-').shift(); this.picker = this.$el.datepicker(this.options); this.parsePickerValue() this.$el.on('changeDate', $.proxy(this.onSelectDatePicker, this)) } } DatePicker.prototype.parsePickerValue = function () { var value = this.$el.val() if (value === '30-11--0001') this.$el.val('') } DatePicker.prototype.onSelectDatePicker = function(event) { var pickerDate = moment(event.date.toDateString()) var lockerValue = pickerDate.format('YYYY-MM-DD') this.$dataLocker.val(lockerValue) } DatePicker.prototype.onSelectDateTimePicker = function(event) { var lockerValue = event.date.format('YYYY-MM-DD HH:mm:ss') this.$dataLocker.val(lockerValue) this.$el.datetimepicker('hide') } // // FIELD DatePicker PLUGIN DEFINITION // ============================ var old = $.fn.datePicker $.fn.datePicker = function (option) { var args = Array.prototype.slice.call(arguments, 1), result this.each(function () { var $this = $(this) var data = $this.data('ti.datePicker') var options = $.extend({}, DatePicker.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('ti.datePicker', (data = new DatePicker(this, options))) if (typeof option == 'string') result = data[option].apply(data, args) if (typeof result != 'undefined') return false }) return result ? result : this } $.fn.datePicker.Constructor = DatePicker // FIELD DatePicker NO CONFLICT // ================= $.fn.datePicker.noConflict = function () { $.fn.datePicker = old return this } // FIELD DatePicker DATA-API // =============== $(document).render(function () { $('[data-control="datepicker"]').datePicker() }); }(window.jQuery);
JavaScript
0
@@ -1631,32 +1631,383 @@ ePicker, this))%0A + // Stops bootstrap modal from closing when datepicker hide event is triggered%0A // https://github.com/uxsolutions/bootstrap-datepicker/issues/50#issuecomment-90855951%0A .on('hide', function(event) %7B%0A event.preventDefault();%0A event.stopPropagation();%0A %7D)%0A %7D%0A %7D%0A
93db5063c7ec27f2b92de8dc13618862e698014d
Remove debugger
vendor/jasmine-jquery.js
vendor/jasmine-jquery.js
(function() { jasmine.JQuery = function() {}; jasmine.JQuery.browserTagCaseIndependentHtml = function(html) { var div = document.createElement('div'); div.innerHTML = html return div.innerHTML }; jasmine.JQuery.elementToString = function(element) { if (element instanceof HTMLElement) { return element.outerHTML } else { return element.html() } }; jasmine.JQuery.matchersClass = {}; (function(){ var jQueryMatchers = { toHaveClass: function(className) { debugger if (this.actual instanceof HTMLElement) { return this.actual.classList.contains(className) } else { return this.actual.hasClass(className); } }, toBeVisible: function() { return this.actual.is(':visible'); }, toBeHidden: function() { return this.actual.is(':hidden'); }, toBeSelected: function() { return this.actual.is(':selected'); }, toBeChecked: function() { return this.actual.is(':checked'); }, toBeEmpty: function() { return this.actual.is(':empty'); }, toExist: function() { if (this.actual instanceof HTMLElement) { return true } else { return this.actual.size() > 0; } }, toHaveAttr: function(attributeName, expectedAttributeValue) { var actualAttributeValue; if (this.actual instanceof HTMLElement) { actualAttributeValue = this.actual.getAttribute(attributeName) } else { actualAttributeValue = this.actual.attr(attributeName) } return hasProperty(actualAttributeValue, expectedAttributeValue); }, toHaveId: function(id) { if (this.actual instanceof HTMLElement) { return this.actual.getAttribute('id') == id } else { return this.actual.attr('id') == id; } }, toHaveHtml: function(html) { var actualHTML; if (this.actual instanceof HTMLElement) { actualHTML = this.actual.outerHTML } else { actualHTML = this.actual.html() } return actualHTML == jasmine.JQuery.browserTagCaseIndependentHtml(html); }, toHaveText: function(text) { var actualText; if (this.actual instanceof HTMLElement) { actualText = this.actual.textContent } else { actualText = this.actual.text() } if (text && typeof text.test === 'function') { return text.test(actualText); } else { return actualText == text; } }, toHaveValue: function(value) { return this.actual.val() == value; }, toHaveData: function(key, expectedValue) { return hasProperty(this.actual.data(key), expectedValue); }, toMatchSelector: function(selector) { return this.actual.is(selector); }, toContain: function(selector) { return this.actual.find(selector).size() > 0; }, toBeDisabled: function(selector){ return this.actual.is(':disabled'); }, // tests the existence of a specific event binding toHandle: function(eventName) { var events = this.actual.data("events"); return events && events[eventName].length > 0; }, // tests the existence of a specific event binding + handler toHandleWith: function(eventName, eventHandler) { var stack = this.actual.data("events")[eventName]; var i; for (i = 0; i < stack.length; i++) { if (stack[i].handler == eventHandler) { return true; } } return false; } }; jQueryMatchers.toExist.supportsBareElements = true jQueryMatchers.toHaveClass.supportsBareElements = true jQueryMatchers.toHaveText.supportsBareElements = true jQueryMatchers.toHaveId.supportsBareElements = true jQueryMatchers.toHaveAttr.supportsBareElements = true jQueryMatchers.toHaveHtml.supportsBareElements = true var hasProperty = function(actualValue, expectedValue) { if (expectedValue === undefined) { return actualValue !== undefined; } return actualValue == expectedValue; }; var bindMatcher = function(methodName) { var builtInMatcher = jasmine.Matchers.prototype[methodName]; jasmine.JQuery.matchersClass[methodName] = function() { if (this.actual && this.actual.jquery || this.actual instanceof HTMLElement && jQueryMatchers[methodName].supportsBareElements) { var result = jQueryMatchers[methodName].apply(this, arguments); this.actual = jasmine.JQuery.elementToString(this.actual); return result; } if (builtInMatcher) { return builtInMatcher.apply(this, arguments); } return false; }; }; for(var methodName in jQueryMatchers) { bindMatcher(methodName); } })(); beforeEach(function() { this.addMatchers(jasmine.JQuery.matchersClass); }); })();
JavaScript
0.00001
@@ -482,23 +482,8 @@ ) %7B%0A - debugger%0A
7bc80c5a84e277cef288fe2a5d35b1d1347fc10b
Improve comment of byte alignment computation.
examples/jsm/renderers/webgpu/WebGPUAttributes.js
examples/jsm/renderers/webgpu/WebGPUAttributes.js
class WebGPUAttributes { constructor( device ) { this.buffers = new WeakMap(); this.device = device; } get( attribute ) { return this.buffers.get( attribute ); } remove( attribute ) { const data = this.buffers.get( attribute ); if ( data ) { data.buffer.destroy(); this.buffers.delete( attribute ); } } update( attribute, isIndex = false, usage = null ) { let data = this.buffers.get( attribute ); if ( data === undefined ) { if ( usage === null ) { usage = ( isIndex === true ) ? GPUBufferUsage.INDEX : GPUBufferUsage.VERTEX; } data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( usage && usage !== data.usage ) { data.buffer.destroy(); data = this._createBuffer( attribute, usage ); this.buffers.set( attribute, data ); } else if ( data.version < attribute.version ) { this._writeBuffer( data.buffer, attribute ); data.version = attribute.version; } } _createBuffer( attribute, usage ) { const array = attribute.array; const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment const buffer = this.device.createBuffer( { size: size, usage: usage | GPUBufferUsage.COPY_DST, mappedAtCreation: true, } ); new array.constructor( buffer.getMappedRange() ).set( array ); buffer.unmap(); attribute.onUploadCallback(); return { version: attribute.version, buffer: buffer, usage: usage }; } _writeBuffer( buffer, attribute ) { const array = attribute.array; const updateRange = attribute.updateRange; if ( updateRange.count === - 1 ) { // Not using update ranges this.device.defaultQueue.writeBuffer( buffer, 0, array, 0 ); } else { this.device.defaultQueue.writeBuffer( buffer, 0, array, updateRange.offset * array.BYTES_PER_ELEMENT, updateRange.count * array.BYTES_PER_ELEMENT ); updateRange.count = - 1; // reset range } } } export default WebGPUAttributes;
JavaScript
0
@@ -1162,16 +1162,28 @@ lignment +, see #20441 %0A%0A%09%09cons
ecbbde5d78bccc0fb56b0cacbe0a0c4413a0f0c8
add functions to set slide-* CSS rules
app/assets/javascripts/app/controllers/FormController.js
app/assets/javascripts/app/controllers/FormController.js
function FormController($window, $filter, FormDataService, WordService, GenreService, BandNameService, ShareBandNameService) { var ctrl = this; ctrl.formData = FormDataService.formData; ctrl.genres = []; ctrl.bandWords = []; ctrl.bandName = ShareBandNameService; ctrl.getGenreNames = function() { GenreService.getGenres() .then(function(response) { ctrl.genres.push(response.data.genres); }); } ctrl.getBeginningWords = function() { WordService.getWords() .then(function(response) { var beginningWords = $filter('removeBeginningWordsFilter')(response.data.words, true); ctrl.beginningWords = $filter('editBeginningWordsFilter')(beginningWords, ['The', 'By', 'Of', 'That', 'This', 'In']); }); } ctrl.setBeginningWords = function() { if (ctrl.formData.beginsWith != undefined && ctrl.formData.beginsWith != '') { ctrl.bandWords.push(ctrl.formData.beginsWith); } } ctrl.getRandomInt = function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } ctrl.setBandWords = function(numOfWords) { WordService.getWords() .then(function(response) { var words = $filter('removeBeginningWordsFilter')(response.data.words, false); var i = 0 while (i++ < numOfWords) { var randomWordIndex = ctrl.getRandomInt(0, words.length-1); ctrl.bandWords.push(words[randomWordIndex].string); } ctrl.bandName.name = ctrl.bandWords.join(' '); ctrl.saveBandName(); ctrl.bandWords = []; }); } ctrl.setBandGenre = function() { ctrl.bandName.genre_id = ctrl.formData.genre_id; } ctrl.saveBandName = function() { var data = { band_name: { name: ctrl.bandName.name, genre_id: parseInt(ctrl.bandName.genre_id) }, }; BandNameService.postBandName(data); } ctrl.getBandName = function(numOfWords) { ctrl.setBandGenre(); ctrl.setBeginningWords(); ctrl.setBandWords(numOfWords); $window.location.href = '/#/band-name'; } ctrl.getGenreNames(); ctrl.getBeginningWords(); } angular .module('app') .controller('FormController', FormController);
JavaScript
0
@@ -266,16 +266,33 @@ Service; +%0A ctrl.slideDir; %0A%0A ctrl @@ -2115,24 +2115,166 @@ '; %0A %7D%0A%0A + ctrl.slideViewLeft = () =%3E %7B%0A ctrl.slideDir = 'slide-left';%0A %7D%0A%0A ctrl.slideViewRight = () =%3E %7B%0A ctrl.slideDir = 'slide-right';%0A %7D%0A%0A ctrl.getGe
fbb8cdcd2d6957cea85f21431c59aedff3bdaf12
Return 204 status code for DELETE and PUT requests
controllers/api.js
controllers/api.js
'use strict'; /** * GET /api/challenges * List of challenges. */ exports.getChallenges = function get(req, res) { res.json({ challenges: [] }); }; /** * POST /api/challenges/ * Create a new challenge. */ exports.postChallenge = function post(req, res) { res.status(201).send("Created new challenge"); } /** * PUT /api/challenges/:challengeId * Updated a new challenge. */ exports.putChallenge = function put(req, res) { res.status(201).send("Update challenge"); } /** * DELETE /api/challenges/:challengeId * Delete a challenge. */ exports.deleteChallenge = function deleteChallenge(req, res) { res.status(204).send("Delete challenge"); } /** * GET /api/teams * List of teams. */ exports.getTeams = function get(req, res) { res.json({ teams: [] }); }; /** * POST /api/teams * Create a new team. */ exports.postTeam = function post(req, res) { res.status(201).send("Created new team"); } /** * POST /api/teams/:teamId * Update a team by id. */ exports.putTeam = function put(req, res) { res.status(201).send("Updated a team"); } /** * POST /api/teams/:teamId * Delete a team by id. */ exports.deleteTeam = function deleteTeam(req, res) { res.status(204).send("Deleted a team"); }
JavaScript
0.000001
@@ -433,33 +433,33 @@ res.status(20 -1 +4 ).send(%22Update c @@ -1018,33 +1018,33 @@ res.status(20 -1 +4 ).send(%22Updated
8c3c73f4e3abed7535c513adc5fc607fdde0dd88
fix demo
example/react-native-iOS/push_activity.js
example/react-native-iOS/push_activity.js
'use strict'; import React, { Component } from 'react'; import ReactNative from 'react-native'; const { Text, View, TextInput, TouchableHighlight, PropTypes, requireNativeComponent, NativeModules, ScrollView, DeviceEventEmitter, NativeAppEventEmitter, StyleSheet, Alert, } = ReactNative; import JPushModule from 'jpush-react-native'; export default class PushActivity extends Component { constructor(props) { super(props); this.state = { bg: '#ffffff', regid: '', connectStatus: '', package: 'PackageName', deviceId: 'DeviceId', }; this.onInitPress = this.onInitPress.bind(this) } jumpSetActivity() { this.props.navigation.navigate('Setting') } onInitPress() { console.log('on click init push '); JPushModule.getRegistrationID((registrationid) => { console.log(registrationid); this.setState({regid: registrationid}); }); } onSetuplocalNotificationPress() { this.props.navigator.push({ name:'LocalPushActivity' }); } componentWillMount() { JPushModule.setupPush() // if you add register notification in Appdelegate.m 有 don't need call this function JPushModule.getBadge((badge) => {Alert.alert("badge", badge)}) JPushModule.addnetworkDidLoginListener(() => { console.log('连接已登录') JPushModule.addTags(['dasffas'], (result)=> { Alert.alert('addTags success:' + JSON.stringify(result)) }) }) JPushModule.addOpenNotificationLaunchAppListener((result) => { Alert.alert('addOpenNotificationLaunchAppListener', 'the notification is :' + JSON.stringify(result)) }) JPushModule.addReceiveOpenNotificationListener((result) => { Alert.alert('addReceiveOpenNotificationListener',JSON.stringify(result)) }) JPushModule.addReceiveNotificationListener((result) => { Alert.alert('addReceiveNotificationListener',JSON.stringify(result)) }) JPushModule.addConnectionChangeListener((result) => { if (result) { console.log('网络已连接') } else { console.log('网络已断开') } }) // JPushModule.addReceiveNotificationListener((notification) => { // Alert.alert(JSON.stringify(notification)) // }) } componentDidMount() { } componentWillUnmount() { DeviceEventEmitter.removeAllListeners(); NativeAppEventEmitter.removeAllListeners(); } render() { return ( <ScrollView style = { styles.parent }> <Text style = { styles.textStyle }> RegistrationID: { this.state.regid } </Text> <Text style = { styles.textStyle }> 链接状态: { this.state.connectStatus } </Text> <Text style = { styles.textStyle }> { this.state.package } </Text> <Text style = { styles.textStyle }> { this.state.deviceId } </Text> <TouchableHighlight underlayColor = '#0866d9' activeOpacity = { 0.5 } style = { styles.btnStyle } onPress = { () => { this.props.navigation.navigate("Setting")} }> <Text style = { styles.btnTextStyle }> 设置 </Text> </TouchableHighlight> <TouchableHighlight underlayColor = '#0866d9' activeOpacity = { 0.5 } style = { styles.btnStyle } onPress = { this.onInitPress }> <Text style = { styles.btnTextStyle }> INITPUSH </Text> </TouchableHighlight> <TouchableHighlight underlayColor = '#e4083f' activeOpacity = { 0.5 } style = { styles.btnStyle } onPress = { () => {this.props.navigation.navigate("LocalPush")} }> <Text style = { styles.btnTextStyle }> local notification </Text> </TouchableHighlight> </ScrollView> ) } }; var styles = StyleSheet.create({ parent: { padding: 15, backgroundColor: '#f0f1f3' }, textStyle: { marginTop: 10, textAlign: 'center', fontSize: 20, color: '#808080' }, btnStyle: { marginTop: 10, borderWidth: 1, borderColor: '#3e83d7', borderRadius: 8, backgroundColor: '#3e83d7' }, btnTextStyle: { textAlign: 'center', fontSize: 25, color: '#ffffff' }, inputStyle: { borderColor: '#48bbec', borderWidth: 1, } }); module.exports = PushActivity
JavaScript
0.000001
@@ -1213,79 +1213,8 @@ ion%0A - JPushModule.getBadge((badge) =%3E %7BAlert.alert(%22badge%22, badge)%7D)%0A
c35381b80da7dfdd6cb984226a7d61b85297b122
remove console.log
src/components/component-helpers.js
src/components/component-helpers.js
// @flow export function getSource({ data, isFullscreen }) { let { source = data.src } = data; console.log(source) if (typeof source === 'string') return source; return isFullscreen ? source.fullscreen : source.regular; } export function getThumbnail({ data }) { const { source } = data; if (typeof source === 'string') return source; return source.thumbnail; }
JavaScript
0.000006
@@ -95,30 +95,8 @@ ta;%0A - console.log(source)%0A if
f64a66dcc482776b3970ca6645f7e64abc410ffb
change end point name
src/client/services/server-api/index.js
src/client/services/server-api/index.js
const io = require('socket.io-client'); const qs = require('querystring'); const _ = require('lodash'); const socket = io.connect('/'); const defaultFetchOpts = { method: 'GET', headers: { 'Content-type': 'application/json', 'Accept': 'application/json' } }; const ServerAPI = { getGraphAndLayout(uri, version) { return fetch(`/api/get-graph-and-layout?${qs.stringify({uri, version})}`, defaultFetchOpts).then(res => res.json()); }, pcQuery(method, params){ return fetch(`/pc-client/${method}?${qs.stringify(params)}`, defaultFetchOpts); }, datasources(){ return fetch('/pc-client/datasources', defaultFetchOpts).then(res => res.json()); }, querySearch(query){ return fetch(`/pc-client/querySearch?${qs.stringify(query)}`, defaultFetchOpts).then(res => res.json()); }, geneQuery(query){ query.genes=_.concat(['padding'],query.genes.split(' ')); return fetch('/enrichment/gene-query', { method:'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, body:qs.stringify(query) }).then(res => res.json()); }, getGeneInformation(ids,type){ return fetch(`https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmode=json&db=${type}&id=${ids.join(',')}`, {method: 'GET'}).then(res => res.json()); }, getNeighborhood(ids,kind){ const source=ids.map(id=>`source=${id}`).join('&'); const patterns = '&pattern=controls-phosphorylation-of&pattern=in-complex-with&pattern=controls-expression-of&pattern=interacts-with'; return fetch(`http://www.pathwaycommons.org/pc2/graph?${source}&kind=${kind}&format=TXT${patterns}`,defaultFetchOpts).then(res => res.text()); }, // Send a diff in a node to the backend. The backend will deal with merging these diffs into // a layout submitNodeChange(uri, version, nodeId, bbox) { socket.emit('submitDiff', { uri: uri, version: version.toString(), diff: { nodeID: nodeId, bbox: bbox } }); }, submitLayoutChange(uri, version, layout) { socket.emit('submitLayout', { uri: uri, version: version, layout: layout }); }, initReceiveLayoutChange(callback) { socket.on('layoutChange', layoutJSON => { callback(layoutJSON); }); }, initReceiveNodeChange(callback) { socket.on('nodeChange', nodeDiff => { callback(nodeDiff); }); }, }; module.exports = ServerAPI;
JavaScript
0.000195
@@ -930,18 +930,18 @@ ent/ -gene-query +validation ', %7B
aff6e3d5a50548e831c3d692f0b1d49e8f044586
add meta to persons
src/components/person-page/index.js
src/components/person-page/index.js
import React from 'react'; import st from './style.module.css'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import marked from 'marked'; import {defaultHelmetMeta} from '../../layouts/index'; import BackButton from '../back-button'; import TelegramIcon from '-!svg-react-loader?name=Icon!../../../static/telegram.svg'; import VkIcon from '-!svg-react-loader?name=Icon!../../../static/vk.svg'; import SlackIcon from '-!svg-react-loader?name=Icon!../../../static/slack.svg'; import TwitterIcon from '-!svg-react-loader?name=Icon!../../../static/twitter.svg'; const SocialIcon = ({user, link, children}) => { const icon = user ? ( <span className={st.social_icon}> <a target="_blank" href={link}> {children} </a> </span> ) : null; return icon; }; export default ({history, pathContext: {data}}) => { const { name, lastname, position, vk, telegram, twitter, slack, bio, company, podcasts, talks, photo, slug, } = data; const title = `${name} ${lastname}`; const description = bio ? bio.bio : `${name} ${lastname}`; const metaImage = `${photo.file.url}?w=450&h=315&q=100`; const twitterImage = `${photo.file.url}?w=300&h=157&q=100&4362984378`; return ( <div> <Helmet meta={[ {name: 'author', content: title}, {name: 'twitter:card', content: 'summary'}, {name: 'twitter:description', content: description}, {name: 'twitter:site', content: title}, {name: 'twitter:creator', content: 'spb_frontend'}, {name: 'twitter:title', content: title}, {name: 'twitter:image', content: twitterImage}, {name: 'twitter:image:src', content: twitterImage}, {name: 'twitter:image:width', content: '300'}, {name: 'twitter:image:height', content: '157'}, {property: 'og:title', content: title}, {property: 'og:site_name', content: title}, {property: 'og:type', content: 'website'}, { property: 'og:url', content: `https://spb-frontend.ru/persons/${slug}`, }, {property: 'og:description', content: description}, {property: 'og:image', content: metaImage}, {property: 'og:site_name', content: title}, {name: 'viewport', content: 'width=device-width, maximum-scale=1'}, ]} /> <div className={st.back_link}> <BackButton history={history} /> </div> <div className={st.person}> <div className={st.person_info}> <h2> {name} {lastname} <br /> {position && ( <small className={st.person_position}>{position}</small> )} </h2> <div className={st.company}>{company}</div> <div className={st.social}> <SocialIcon link={`https://vk.com/${vk}`} user={vk}> <VkIcon /> </SocialIcon> <SocialIcon link={`https://t.me/${telegram}`} user={telegram}> <TelegramIcon /> </SocialIcon> <SocialIcon link={`https://twitter.com/${twitter}`} user={twitter}> <TwitterIcon /> </SocialIcon> {slack ? ( <span className={st.slack_icon}> <SlackIcon /> <span className={st.slack_name}>{slack}</span> </span> ) : null} {bio && <div dangerouslySetInnerHTML={{__html: marked(bio.bio)}} />} </div> </div> <div className={st.person_image}> {photo ? ( <img src={`https:${photo.file.url}?fit=thumb&h=200&w=200`} /> ) : ( <img src="/Person-placeholder.jpg" /> )} </div> </div> {podcasts && ( <div> <h4>Подкасты:</h4> {podcasts .sort((prev, next) => { return parseInt(next.number) - parseInt(prev.number); }) .map(({title, number}) => { return ( <div className={st.podcast_item} key={number}> <Link to={`/podcast/${number}`}>{title}</Link> </div> ); })} </div> )} {talks && ( <div style={{marginTop: 50}}> <h4>Доклады:</h4> {talks .sort((prev, next) => { return next.path - prev.path; }) .map(({title, slug}, key) => { return ( <div className={st.podcast_item} key={key}> <Link to={`/talks/${slug}`}>{title}</Link> </div> ); })} </div> )} </div> ); };
JavaScript
0.000001
@@ -1504,37 +1504,47 @@ site', content: -title +'@spb_frontend' %7D,%0A %7Bna @@ -1576,16 +1576,17 @@ ntent: ' +@ spb_fron