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
89f7ef5f893f13fb294365f9a2c0a8a21540a41e
check hostname exists
src/event_worker.js
src/event_worker.js
// // Copyright (c) Telefonica I+D. All rights reserved. // // var http = require('http'); var https = require('https'); var MG = require('./my_globals').C; var url = require('url'); var config_global = require('./config_base.js'); var path = require('path'); var log = require('PDITCLogger'); var logger = log.newLogger(); logger.prefix = path.basename(module.filename,'.js'); function urlErrors(pUrl) { "use strict"; var parsedUrl; if (pUrl) { parsedUrl = url.parse(pUrl); if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') { return ('Invalid protocol ' + pUrl ); } } return null; } function createTask(simpleRequest, callback) { "use strict"; //Check required headers if (!simpleRequest.headers[MG.HEAD_RELAYER_HOST]) { callback ([MG.HEAD_RELAYER_HOST + ' is missing'], null); } else { var errorsHeaders = []; //check URLS errorsHeaders = [simpleRequest.headers[MG.HEAD_RELAYER_HTTPCALLBACK], simpleRequest.headers[MG.HEAD_RELAYER_HTTPCALLBACK_ERROR], simpleRequest.headers[MG.HEAD_RELAYER_HOST] ].map(urlErrors).filter(function(e) { return e!==null;}); //check Retry header var retryStr = simpleRequest.headers[MG.HEAD_RELAYER_RETRY]; if (retryStr) { var retrySplit = retryStr.split(','); if (!retrySplit.every(function(num){return isFinite(Number(num));})) { errorsHeaders.push('invalid retry value: '+ retryStr); } } //check Persistence Header var persistence = simpleRequest.headers[MG.HEAD_RELAYER_PERSISTENCE]; if(persistence){ if (persistence!=='BODY' && persistence !== 'STATUS' && persistence !== 'HEADER'){ errorsHeaders.push('invalid persistence type: '+persistence); } } if(errorsHeaders.length > 0) { callback(errorsHeaders, null); } else { callback(null, simpleRequest); } } } function doJob(task, callback) { 'use strict'; logger.debug('doJob(task, callback)', [task, callback]); var httpModule; var target_host = task.headers[MG.HEAD_RELAYER_HOST], req; if (!target_host) { logger.warning('doJob','No target host'); } else { var options = url.parse(target_host); task.headers.host = options.host; if(options.protocol === 'https:'){ httpModule = https; } else { // assume plain http httpModule = http; } options.headers = task.headers; options.method = task.method; req = httpModule.request(options, function (rly_res) { if (Math.floor(rly_res.statusCode / 100) !== 5) { //if no 5XX ERROR get_response(rly_res, task, function (task, resp_obj) { //PERSISTENCE if (callback) { callback(null, resp_obj); } }); } else { get_response(rly_res, task, function (task, resp_obj) { var e = {id:task.id, resultOk:false, statusCode:rly_res.statusCode, headers:rly_res.headers, body:resp_obj.body }; handle_request_error(task, e, callback); }); } }); req.on('error', function (e) { e.resultOk = false; logger.warning('doJob',e); handle_request_error(task, {id:task.id, resultOk: false, error:e.code+'('+ e.syscall+')'}, callback); }); if (options.method === 'POST' || options.method === 'PUT') { //write body req.write(task.body); } req.end(); //?? sure HERE? } } function handle_request_error(task, e, callback) { "use strict"; logger.debug('handle_request_error(task, e, callback)', [task, e, callback]); logger.warning('handle_request_error', e); do_retry(task, e, callback); } function get_response(resp, task, callback) { "use strict"; logger.debug('get_response(resp, task, callback)', [resp, task, callback]); var data = ""; resp.on('data', function (chunk) { data += chunk; }); resp.on('end', function (chunk) { if (chunk) { if (chunk) { data += chunk; } //avoid tail undefined } var resp_obj = {id: task.id, topic: task.headers[MG.HEAD_RELAYER_TOPIC], resultOk:true, statusCode:resp.statusCode, headers:resp.headers, body:data}; if (callback) { callback(task, resp_obj); } }); } function do_retry(task, error, callback) { "use strict"; logger.debug('do_retry(task, error, callback)',[task, error, callback]); var retry_list = task.headers[MG.HEAD_RELAYER_RETRY]; var time = -1; if (retry_list) { var retry_a = retry_list.split(","); if (retry_a.length > 0) { time = parseInt(retry_a.shift(), 10); if (retry_a.length > 0) { // there is retry times still task.headers[MG.HEAD_RELAYER_RETRY] = retry_a.join(","); } else { //Retry End with no success delete task.headers[MG.HEAD_RELAYER_RETRY]; } if (time > 0) { setTimeout(function () { doJob(task, callback); }, time); } } } else { if (callback) { callback(error, null); } } } exports.doJob = doJob; exports.createTask = createTask;
JavaScript
0.000007
@@ -656,24 +656,118 @@ %0A %7D%0D%0A + if (!parsedUrl.hostname)%7B%0D%0A return ('Hostname expected' + pUrl);%0D%0A %7D%0D%0A %7D%0D%0A%0D%0A
746b1cffa32713b5fc68642ebd6399ea0c06f9f2
Add missing `new` in State.setup_state() test
test/test_lib/test_states/test_state.js
test/test_lib/test_states/test_state.js
var assert = require("assert"); var vumigo = require("../../../lib"); var DummyIm = vumigo.test_utils.DummyIm; var State = vumigo.states.State; describe("State", function () { var im; beforeEach(function () { im = new DummyIm(); }); describe(".setup_state", function() { it("should link the interaction machine to the state", function() { var state = State('luke-the-state'); assert.strictEqual(state.im, null); state.setup_state(im); assert.strictEqual(state.im, im); }); it("should invoke the associated handler", function(done) { var state = new State('luke-the-state', { handlers: { setup_state: function() { assert.equal(this, state); done(); } } }); state.setup_state(im); }); }); describe(".on_enter", function() { it("should invoke the associated handler", function(done) { var state = new State('luke-the-state', { handlers: { on_enter: function() { assert.equal(this, state); done(); } } }); state.on_enter(); }); }); describe(".on_exit", function() { it("should invoke the associated handler", function(done) { var state = new State('luke-the-state', { handlers: { on_exit: function() { assert.equal(this, state); done(); } } }); state.on_exit(); }); }); describe(".save_response", function() { it("should store the given user response", function() { var state = new State('luke-the-state'); state.setup_state(im); assert.strictEqual(im.user.answers['luke-the-state'], undefined); state.save_response('foo'); assert.strictEqual(im.user.answers['luke-the-state'], 'foo'); }); }); });
JavaScript
0.000013
@@ -393,16 +393,20 @@ state = + new State('
05e0d56be7e43ec25877f981615b2d51e143657a
when game start winner is -1
test/unit/clinicatdd/mytestctrl.test.js
test/unit/clinicatdd/mytestctrl.test.js
describe('MyTestCtrl', function () { var $scope, controller; var $controller; beforeEach(module('clinicatdd.controllers')); describe("when there is no info", function () { beforeEach(inject(function (_$controller_) { $controller = _$controller_; })); beforeEach(function () { $scope = {}; controller = $controller('MyTestCtrl', {$scope: $scope}); }); it('test variable is defined', function () { expect($scope.test).toBeDefined(); }); it('when game start winner is -1', function () { expect($scope.winner()).toBe(-1); }); it('when game start winner is -1', function () { expect($scope.winner).toBeDefined(); expect($scope.winner()).toBe(-1); }); }); });
JavaScript
0.999324
@@ -595,152 +595,8 @@ %7D); -%0A it('when game start winner is -1', function () %7B%0A expect($scope.winner).toBeDefined();%0A expect($scope.winner()).toBe(-1);%0A %7D); %0A%0A
fa013103e2ed0a1376bee65e094cbcf55b2f8f5d
Enable skipOnVariables flag
app/js/translations.js
app/js/translations.js
const i18n = require('i18next') const fsBackend = require('i18next-fs-backend') const middleware = require('i18next-http-middleware') const path = require('path') module.exports = { setup(options = {}) { const subdomainLang = options.subdomainLang || {} const availableLngs = Object.values(subdomainLang).map(c => c.lngCode) i18n.use(fsBackend).init({ backend: { loadPath: path.join(__dirname, '../../locales/__lng__.json') }, // Load translation files synchronously: https://www.i18next.com/overview/configuration-options#initimmediate initImmediate: false, // We use the legacy v1 JSON format, so configure interpolator to use // underscores instead of curly braces interpolation: { prefix: '__', suffix: '__', unescapeSuffix: 'HTML', // Disable escaping of interpolated values for backwards compatibility. // We escape the value after it's translated in web, so there's no // security risk escapeValue: false }, preload: availableLngs, supportedLngs: availableLngs, fallbackLng: options.defaultLng || 'en' }) const langDetector = new middleware.LanguageDetector(i18n.services) function setLangBasedOnDomainMiddleware(req, res, next) { // Determine language from subdomain const { host } = req.headers if (host == null) { return next() } const [subdomain] = host.split(/[.-]/) const lang = subdomainLang[subdomain] ? subdomainLang[subdomain].lngCode : null // Unless setLng query param is set, use subdomain lang if (!req.originalUrl.includes('setLng') && lang != null) { req.i18n.changeLanguage(lang) } // If the set language is different from the language detection (based on // the Accept-Language header), then set flag which will show a banner // offering to switch to the appropriate library const detectedLanguage = langDetector.detect(req, res) if (req.language !== detectedLanguage) { req.showUserOtherLng = detectedLanguage } next() } const expressMiddleware = function(req, res, next) { middleware.handle(i18n)(req, res, (...args) => { // Decorate req.i18n with translate function alias for backwards // compatibility req.i18n.translate = req.i18n.t next(...args) }) } return { expressMiddleware, setLangBasedOnDomainMiddleware, i18n, // Backwards compatibility with long-standing typo expressMiddlewear: expressMiddleware, setLangBasedOnDomainMiddlewear: setLangBasedOnDomainMiddleware } } }
JavaScript
0
@@ -1028,16 +1028,166 @@ e: false +,%0A // Disable nesting in interpolated values, preventing user input%0A // injection via another nested value%0A skipOnVariables: true %0A %7D
3cbe4f8b779bfb07777cd58875fa10a3d7af9aea
fix compile unit test
test/unit/specs/compile/compile_spec.js
test/unit/specs/compile/compile_spec.js
var Vue = require('../../../../src/vue') var _ = require('../../../../src/util') var dirParser = require('../../../../src/parse/directive') var merge = require('../../../../src/util/merge-option') var compile = require('../../../../src/compile/compile') if (_.inBrowser) { describe('Compile', function () { var vm, el, data beforeEach(function () { // We mock vms here so we can assert what the generated // linker functions do. el = document.createElement('div') data = {} vm = { _bindDir: jasmine.createSpy(), $set: jasmine.createSpy(), $eval: function (value) { return data[value] }, $interpolate: function (value) { return data[value] } } spyOn(vm, '$eval').and.callThrough() spyOn(vm, '$interpolate').and.callThrough() spyOn(_, 'warn') }) it('normal directives', function () { el.setAttribute('v-a', 'b') el.innerHTML = '<p v-a="a" v-b="b">hello</p><div v-b="b"></div>' var defA = { priority: 1 } var defB = { priority: 2 } var descriptorA = dirParser.parse('a')[0] var descriptorB = dirParser.parse('b')[0] var options = merge(Vue.options, { directives: { a: defA, b: defB } }) var linker = compile(el, options) expect(typeof linker).toBe('function') // should remove attributes expect(el.attributes.length).toBe(0) expect(el.firstChild.attributes.length).toBe(0) expect(el.lastChild.attributes.length).toBe(0) linker(vm, el) expect(vm._bindDir.calls.count()).toBe(4) expect(vm._bindDir).toHaveBeenCalledWith('a', el, descriptorB, defA) expect(vm._bindDir).toHaveBeenCalledWith('a', el.firstChild, descriptorA, defA) expect(vm._bindDir).toHaveBeenCalledWith('b', el.firstChild, descriptorB, defB) expect(vm._bindDir).toHaveBeenCalledWith('b', el.lastChild, descriptorB, defB) // check the priority sorting // the "b" on the firstNode should be called first! expect(vm._bindDir.calls.argsFor(1)[0]).toBe('b') }) it('text interpolation', function () { data.b = 'yeah' el.innerHTML = '{{a}} and {{*b}}' var def = Vue.options.directives.text var linker = compile(el, Vue.options) linker(vm, el) // expect 1 call because one-time bindings do not generate a directive. expect(vm._bindDir.calls.count()).toBe(1) var args = vm._bindDir.calls.argsFor(0) expect(args[0]).toBe('text') // skip the node because it's generated in the linker fn via cloneNode expect(args[2]).toBe(dirParser.parse('a')[0]) expect(args[3]).toBe(def) // expect $eval to be called during onetime expect(vm.$eval).toHaveBeenCalledWith('b') // {{a}} is mocked so it's a space. // but we want to make sure {{*b}} worked. expect(el.innerHTML).toBe(' and yeah') }) it('inline html and partial', function () { data.html = 'yoyoyo' el.innerHTML = '{{{html}}} {{{*html}}} {{>partial}}' var htmlDef = Vue.options.directives.html var partialDef = Vue.options.directives.partial var htmlDesc = dirParser.parse('html')[0] var partialDesc = dirParser.parse('partial')[0] var linker = compile(el, Vue.options) linker(vm, el) expect(vm._bindDir.calls.count()).toBe(2) var htmlArgs = vm._bindDir.calls.argsFor(0) expect(htmlArgs[0]).toBe('html') expect(htmlArgs[2]).toBe(htmlDesc) expect(htmlArgs[3]).toBe(htmlDef) var partialArgs = vm._bindDir.calls.argsFor(1) expect(partialArgs[0]).toBe('partial') expect(partialArgs[2]).toBe(partialDesc) expect(partialArgs[3]).toBe(partialDef) expect(vm.$eval).toHaveBeenCalledWith('html') // with placeholder comments & interpolated one-time html expect(el.innerHTML).toBe('<!--v-html--> yoyoyo <!--v-partial-->') }) it('terminal directives', function () { el.innerHTML = '<div v-repeat="items"><p v-a="b"></p></div>' + // v-repeat '<div v-pre><p v-a="b"></p></div>' // v-pre var def = Vue.options.directives.repeat var descriptor = dirParser.parse('items')[0] var linker = compile(el, Vue.options) linker(vm, el) // expect 1 call because terminal should return early and let // the directive handle the rest. expect(vm._bindDir.calls.count()).toBe(1) expect(vm._bindDir).toHaveBeenCalledWith('repeat', el.firstChild, descriptor, def) }) it('custom element components', function () { var options = merge(Vue.options, { components: { 'my-component': {} } }) el.innerHTML = '<my-component><div v-a="b"></div></my-component>' var def = Vue.options.directives.component var descriptor = dirParser.parse('my-component')[0] var linker = compile(el, options) linker(vm, el) expect(vm._bindDir.calls.count()).toBe(1) expect(vm._bindDir).toHaveBeenCalledWith('component', el.firstChild, descriptor, def) expect(_.warn).not.toHaveBeenCalled() }) it('attribute interpolation', function () { data['{{*b}}'] = 'B' el.innerHTML = '<div a="{{a}}" b="{{*b}}"></div>' var def = Vue.options.directives.attr var descriptor = dirParser.parse('a:a')[0] var linker = compile(el, Vue.options) linker(vm, el) expect(vm._bindDir.calls.count()).toBe(1) expect(vm._bindDir).toHaveBeenCalledWith('attr', el.firstChild, descriptor, def) expect(el.firstChild.getAttribute('b')).toBe('B') }) it('param attributes', function () { var options = merge(Vue.options, { paramAttributes: ['a', 'b', 'c'] }) var def = Vue.options.directives['with'] el.setAttribute('a', '1') el.setAttribute('b', '{{a}}') el.setAttribute('c', 'a {{b}} c') // invalid var linker = compile(el, options) linker(vm, el) // should skip literal & invliad expect(vm._bindDir.calls.count()).toBe(1) var args = vm._bindDir.calls.argsFor(0) expect(args[0]).toBe('with') expect(args[1]).toBe(el) // skipping descriptor because it's ducked inline expect(args[3]).toBe(def) // invalid should've warn expect(_.warn).toHaveBeenCalled() // literal should've called vm.$set expect(vm.$set).toHaveBeenCalledWith('a', '1') }) it('DocumentFragment', function () { var frag = document.createDocumentFragment() frag.appendChild(el) var el2 = document.createElement('div') frag.appendChild(el2) el.innerHTML = '{{*a}}' el2.innerHTML = '{{*b}}' data.a = 'A' data.b = 'B' var linker = compile(frag, Vue.options) linker(vm, frag) expect(el.innerHTML).toBe('A') expect(el2.innerHTML).toBe('B') }) }) }
JavaScript
0.000001
@@ -5377,17 +5377,19 @@ arse('a: -a +(a) ')%5B0%5D%0A
184a0341b5b8303f1966fd6ef3cbedf8033a2d8b
Fix bug where heading was not always updated
app/routes/arrivals.js
app/routes/arrivals.js
import Ember from 'ember'; import request from 'ic-ajax'; import ENV from './../config/environment'; var run = Ember.run; const POLL_INTERVAL = 15 * 1000; export default Ember.Route.extend({ pendingRefresh: null, model: function(params) { // Eagerly load template request(`${ENV.APP.SERVER}/api/arrivals/${params.stop_id}`).then(run.bind(this, 'requestDidFinish')); }, setupController: function(controller) { controller.setProperties({ arrivals: [], stopId: this.paramsFor('arrivals')['stop_id'], isLoading: true }); }, requestDidFinish: function(response) { this.controller.setProperties({ arrivals: response.arrivals, isLoading: false }); // Enqueue a refresh this.set('pendingRefresh', run.later(this, this.refresh, POLL_INTERVAL)); }, actions: { willTransition: function() { run.cancel(this.get('pendingRefresh')); } } });
JavaScript
0
@@ -243,37 +243,8 @@ ) %7B%0A - // Eagerly load template%0A @@ -349,85 +349,20 @@ ));%0A +%0A -%7D,%0A%0A -setupController: function(controller) %7B%0A controller.setProperties( +return %7B%0A @@ -397,34 +397,14 @@ Id: -this. params -For('arrivals') %5B'st @@ -439,16 +439,107 @@ ue%0A %7D +;%0A %7D,%0A%0A setupController: function(controller, model) %7B%0A controller.setProperties(model );%0A %7D,%0A
b3f0f40e17367f1844757a69d3646195449adb06
Move sdc-healthcheck tests to system tests instead of post-install
tests/platform/001_base_build_sanity.js
tests/platform/001_base_build_sanity.js
#!/usr/bin/node var test = require('tap').test; var async = require('async'); var child = require('child_process'); var fs = require('fs'); test("Check services status", function(t){ t.plan(3); child.exec('svcs -xv', function(err, stdout, stderr){ t.equal(stdout, '', "svcs -xv shows no output on stdout"); t.equal(stderr, '', "svcs -xv shows no output on stderr"); t.equal(err, null, "svcs -xv exited cleanly"); t.end(); }); }); test("Check release.json is in place and looks good", function(t){ t.plan(5); var release_obj = JSON.parse(fs.readFileSync('/usbkey/release.json')); t.ok(release_obj.version, "has a version"); t.ok(release_obj.branch, "has a branch"); t.ok(release_obj.describe, "has a describe"); t.ok(release_obj.timestamp, "has a timestamp"); t.like(release_obj.timestamp, new RegExp('^\d{8}T\d{6}Z$'), "timestamp is correct format"); t.end(); }); test("Check platform version numbers", function(t){ t.plan(7); async.series([ function(cb){ child.exec('uname -v', function(err, stdout, stderr){ cb(null, { err: err, stdout: stdout, stderr: stderr }); }); }, function(cb){ fs.readdir('/usbkey/os', function(err, files){ cb(null, { err: err, files: files }); }); }, function(cb){ fs.readlink('/usbkey/os/latest', function(err, linkpath){ cb(null, { err: err, link: linkpath }); }); } ], function(err, results){ // uname -v var platform_dir = results[0].stdout.replace("\n", ''); t.like(platform_dir, new RegExp('joyent_\d{8}T\d{6}Z'), "uname -v format is correct"); t.equal(results[0].err, null, "uname -v exited cleanly"); t.equal(results[0].stderr, '', "uname -v has nothing on stderr"); platform_dir = platform_dir.replace('joyent_', ''); // /usbkey/os contents t.equal(results[1].files.length, 2, "There are only 2 entries in /usbkey/os"); t.equivalent(results[1].files.sort(), ['latest', platform_dir].sort(), "/usbkey/os entries are as expected"); t.equal(results[1].err, null, "no errors reading /usbkey/os"); // Ensure /usbkey/os/latest points to the correct place t.equal(results[2].link, platform_dir, "/usbkey/os/latest link is correct"); t.end(); }); });
JavaScript
0
@@ -131,24 +131,372 @@ ire('fs');%0A%0A +test(%22Check SDC health%22, function(t)%7B%0A t.plan(3);%0A child.exec('sdc-healthcheck -p', function(err, stdout, stderr)%7B%0A t.equal(err, null, %22sdc-healthcheck exited cleanly%22);%0A t.notEqual(stderr, '', %22service output is not blank%22);%0A t.notLike(stdout, /offline/g, %22no services showing as offline%22);%0A t.end()%0A %7D);%0A%7D);%0A%0A test(%22Check
f0456550e065007e9844f2d736dd4d42911d45e8
fix max level detection error
javascripts/scenes/_game_controller.js
javascripts/scenes/_game_controller.js
GameController = Class.create(Sprite, { initialize: function(scene) { Sprite.call(this, 0, 0); this.image = game.assets['images/square_glow.png']; this.x = -10; this.y = -10; this.scene = scene; this.level = 0; this.maxLevel = false; this.enemyChoiceTotalWeight = 0; this.levels = [ // LEVEL 0 { score: 0, spawn_rate: 60, enemies: [ ['Triangle', 50], ['Circle', 30], ['Square', 40], ['BlackHole', 60] ] }, // LEVEL 1 { score: 400, spawn_rate: 40, enemies: [ ['Triangle', 18], ['Circle', 20], ['Square', 40], ['Worm', 20] ] } ]; this.setEnemyChoiceTotalWeight(); }, onenterframe: function() { // Incrememnt level if needed if (!this.maxLevel && this.scene.score >= this.levels[this.level + 1]['score']) { if (++this.level >= this.levels.length) { this.level--; this.maxLevel = true; } } // Check to see if it's time to spawn an enemy if (this.age % this.levels[this.level]['spawn_rate'] === 0) this.spawnEnemy(); }, spawnEnemy: function() { var random = Math.floor(Math.random() * this.enemyChoiceTotalWeight); var i, cumulativeWeight = 0; var corner = this.randomSpawnCorner(); for (i = 0; i < this.levels[this.level]['enemies'].length; i++) { cumulativeWeight += this.levels[this.level]['enemies'][i][1]; if (random < cumulativeWeight) { var enemy = new window[this.levels[this.level]['enemies'][i][0]](corner[0], corner[1]); this.scene.addChild(enemy); return; } } }, randomSpawnCorner: function() { var horizontalSpawn = this.randomBinary() === 0 ? 0 : game.width, verticalSpawn = this.randomBinary() === 0 ? 0 : game.height; return [ horizontalSpawn, verticalSpawn ]; }, setEnemyChoiceTotalWeight: function() { this.enemyChoiceTotalWeight = 0; for (var i = 0; i < this.levels[this.level]['enemies'].length; i++) this.enemyChoiceTotalWeight += this.levels[this.level]['enemies'][i][1]; }, randomBinary: function() { return Math.floor(Math.random() * 2); } });
JavaScript
0.000021
@@ -984,16 +984,20 @@ s.length + - 1 ) %7B%0A
653ef9ee6b3321e46b1bf9b9d5d1fe9f5a196295
Update glift with parse-update.
deps/glift-core/parse/parse.js
deps/glift-core/parse/parse.js
goog.provide('glift.parse'); /** * Glift parsing for strings. */ glift.parse = { /** * Parse types * @enum {string} */ parseType: { /** FF1-FF4 Parse Type. */ SGF: 'SGF', /** Tygem .gib files. */ TYGEM: 'TYGEM', /** * DEPRECATED. This was created when I didn't understand the destinction * between the various FF1-3 versions and FF4 * * Prefer SGF, this is now equivalent. */ PANDANET: 'PANDANET' }, /** * Parse a Go-format format from a string. * * @param {string} str Raw contents that need to be parsed. * @param {string} filename Name of the file from which the contents came. * @return {!glift.rules.MoveTree} */ fromFileName: function(str, filename) { var parseType = glift.parse.parseType; var ttype = parseType.SGF; if (filename.indexOf('.sgf') > -1) { ttype = parseType.SGF; } else if (filename.indexOf('.gib') > -1) { ttype = parseType.TYGEM; } return glift.parse.fromString(str, ttype); }, /** * Transforms a stringified game-file into a movetree. * * @param {string} str Raw contents that need to be parsed. * @param {glift.parse.parseType=} opt_ttype The parse type. Defaults to SGF * if unspecified. * @return {!glift.rules.MoveTree} The generated movetree */ fromString: function(str, opt_ttype) { var ttype = opt_ttype || glift.parse.parseType.SGF; if (ttype === glift.parse.parseType.PANDANET) { // PANDANET type is now equivalent to SGF. ttype = glift.parse.parseType.SGF; } var methodName = glift.enums.toCamelCase(ttype); var func = glift.parse[methodName]; var movetree = func(str); return glift.rules.movetree.initRootProperties(movetree); } };
JavaScript
0
@@ -479,191 +479,86 @@ * -Parse a Go-format format from a string.%0A *%0A * @param %7Bstring%7D str Raw contents that need to be parsed.%0A * @param %7Bstring%7D filename Name of the file from which the contents c +Get the parse-type from a filename%0A *%0A * @param %7Bstring%7D filename Filen ame -. %0A @@ -572,48 +572,72 @@ rn %7B -! glift. -rules.MoveTree%7D%0A */%0A f +parse.parseType%7D The parse type%0A */%0A parseTypeF romFile -N +n ame: @@ -646,21 +646,16 @@ unction( -str, filename @@ -666,22 +666,18 @@ var -parseT +tt ype = gl @@ -699,40 +699,36 @@ Type -;%0A var ttype = parseType.SGF; +.SGF; // default type = SGF. %0A @@ -771,32 +771,44 @@ %7B%0A ttype = +glift.parse. parseType.SGF;%0A @@ -868,16 +868,28 @@ ttype = +glift.parse. parseTyp @@ -918,41 +918,392 @@ urn -glift.parse.fromString(str, ttype +ttype;%0A %7D,%0A%0A /**%0A * Parse a Go-format format from a string.%0A *%0A * @param %7Bstring%7D str Raw contents that need to be parsed.%0A * @param %7Bstring%7D filename Name of the file from which the contents came.%0A * @return %7B!glift.rules.MoveTree%7D%0A */%0A fromFileName: function(str, filename) %7B%0A return glift.parse.fromString(%0A str, glift.parse.parseTypeFromFilename(filename) );%0A
3c9cc20356cc7c4c08cf171dd864d02f0d824cf9
fix for default market on api hit
src/scripts/modules/item.model.js
src/scripts/modules/item.model.js
import Utils from './utils/utils' export default class Item { constructor({ id, history, price, thumbnail, title, permalink }) { this.id = id.replace(/\D/g, ''); this.market = id.replace(/[0-9]/g, ''); this.permalink = permalink; this.thumbnail = thumbnail; this.title = title; this.history = parseHistory({ history, price }); this.price = this.history[this.history.length - 1].price } static fetch(marketId, id) { return fetch(createEndpoint(marketId, id)) .then(pipeResponse) .then(res => res.json()) } addHistory({ price }) { this.history = parseHistory({ history: this.history, price }); this.price = this.history[this.history.length - 1].price } /* returns 0 for same price +1 for price increased -1 for price lowered */ getIndexedHistoryFluctuation(index) { if (index <= 0) return 0 const indexedPrice = this.history[index].price const priceBefore = this.history[index - 1].price return indexedPrice !== priceBefore ? indexedPrice > priceBefore ? 1 : -1 : 0 } get endpoint() { return createEndpoint(this.market, this.id); } } function parseHistory({ history, price }) { const date = Utils.formatDate() if (!history) return [{ price, date }]; const latest = history[history.length - 1]; if (!latest || latest.price != price || latest.date != date) { return [...history, { price, date }]; } return history; } function pipeResponse(response) { if (!response.ok) { throw Error(response.statusText); } return response; } function createEndpoint(marketId = '/MLA', id) { return `https://api.mercadolibre.com/items${marketId}${id}`; }
JavaScript
0
@@ -1736,16 +1736,47 @@ marketId +, id) %7B%0A const defaultMarket = '/MLA @@ -1776,23 +1776,17 @@ = '/MLA' -, id) %7B +; %0A ret @@ -1834,16 +1834,33 @@ marketId + %7C%7C defaultMarket %7D$%7Bid%7D%60;
fbbc4e29ebfc204ac40179c7b30159b4741a1f83
Fix user roles being removed after a reply
ui/features/discussion_topics_post/graphql/Mutations.js
ui/features/discussion_topics_post/graphql/Mutations.js
/* * Copyright (C) 2021 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import {DiscussionEntry} from './DiscussionEntry' import {Discussion} from './Discussion' import {Error} from '../../../shared/graphql/Error' import gql from 'graphql-tag' import {User} from './User' export const DELETE_DISCUSSION_TOPIC = gql` mutation DeleteDiscussionTopic($id: ID!) { deleteDiscussionTopic(input: {id: $id}) { discussionTopicId errors { ...Error } } } ${Error.fragment} ` // TODO: Support read state export const UPDATE_DISCUSSION_ENTRY_PARTICIPANT = gql` mutation UpdateDiscussionEntryParticipant( $discussionEntryId: ID! $read: Boolean $rating: RatingInputType $forcedReadState: Boolean ) { updateDiscussionEntryParticipant( input: { discussionEntryId: $discussionEntryId read: $read rating: $rating forcedReadState: $forcedReadState } ) { discussionEntry { ...DiscussionEntry editor { ...User } author { ...User } } } } ${User.fragment} ${DiscussionEntry.fragment} ` export const DELETE_DISCUSSION_ENTRY = gql` mutation DeleteDiscussionEntry($id: ID!) { deleteDiscussionEntry(input: {id: $id}) { discussionEntry { ...DiscussionEntry editor { ...User } author { ...User } } errors { ...Error } } } ${User.fragment} ${DiscussionEntry.fragment} ${Error.fragment} ` export const UPDATE_DISCUSSION_TOPIC = gql` mutation updateDiscussionTopic($discussionTopicId: ID!, $published: Boolean, $locked: Boolean) { updateDiscussionTopic( input: {discussionTopicId: $discussionTopicId, published: $published, locked: $locked} ) { discussionTopic { ...Discussion editor { ...User } author { ...User } } } } ${User.fragment} ${Discussion.fragment} ` export const SUBSCRIBE_TO_DISCUSSION_TOPIC = gql` mutation subscribeToDiscussionTopic($discussionTopicId: ID!, $subscribed: Boolean!) { subscribeToDiscussionTopic( input: {discussionTopicId: $discussionTopicId, subscribed: $subscribed} ) { discussionTopic { ...Discussion editor { ...User } author { ...User } } } } ${User.fragment} ${Discussion.fragment} ` export const CREATE_DISCUSSION_ENTRY = gql` mutation CreateDiscussionEntry( $discussionTopicId: ID! $message: String! $parentEntryId: ID $fileId: ID ) { createDiscussionEntry( input: { discussionTopicId: $discussionTopicId message: $message parentEntryId: $parentEntryId fileId: $fileId } ) { discussionEntry { ...DiscussionEntry editor { ...User courseRoles } author { ...User courseRoles } } errors { ...Error } } } ${User.fragment} ${DiscussionEntry.fragment} ${Error.fragment} ` export const UPDATE_DISCUSSION_ENTRY = gql` mutation UpdateDiscussionEntry($discussionEntryId: ID!, $message: String) { updateDiscussionEntry(input: {discussionEntryId: $discussionEntryId, message: $message}) { discussionEntry { ...DiscussionEntry editor { ...User } author { ...User } } errors { ...Error } } } ${User.fragment} ${DiscussionEntry.fragment} ${Error.fragment} ` export const UPDATE_DISCUSSION_ENTRIES_READ_STATE = gql` mutation UpdateDiscussionEntriesReadState($discussionEntryIds: [ID!]!, $read: Boolean!) { updateDiscussionEntriesReadState( input: {discussionEntryIds: $discussionEntryIds, read: $read} ) { discussionEntries { ...DiscussionEntry editor { ...User } author { ...User } } } } ${User.fragment} ${DiscussionEntry.fragment} ` export const UPDATE_DISCUSSION_READ_STATE = gql` mutation UpdateDiscussionReadState($discussionTopicId: ID!, $read: Boolean!) { updateDiscussionReadState(input: {discussionTopicId: $discussionTopicId, read: $read}) { discussionTopic { ...Discussion } } } ${Discussion.fragment} ` export const UPDATE_ISOLATED_VIEW_DEEPLY_NESTED_ALERT = gql` mutation UpdateIsolatedViewDeeplyNestedAlert($isolatedViewDeeplyNestedAlert: Boolean!) { updateIsolatedViewDeeplyNestedAlert( input: {isolatedViewDeeplyNestedAlert: $isolatedViewDeeplyNestedAlert} ) { user { ...User } } } ${User.fragment} `
JavaScript
0.008645
@@ -3562,38 +3562,16 @@ ...User%0A - courseRoles%0A @@ -3611,30 +3611,8 @@ ser%0A - courseRoles%0A
ac60654540511d1751571ee6745e3922decf9118
Fix Popover disappearing when hover off
ui/src/components/workflow/executions/WorkflowAction.js
ui/src/components/workflow/executions/WorkflowAction.js
import React from 'react'; import { Button, ButtonGroup, OverlayTrigger, Popover, Checkbox } from 'react-bootstrap'; import { connect } from 'react-redux'; import { terminateWorkflow, restartWorfklow, retryWorfklow, pauseWorfklow, resumeWorfklow } from '../../../actions/WorkflowActions'; class WorkflowAction extends React.Component { terminate = () => { this.props.dispatch(terminateWorkflow(this.props.workflowId)); }; restart = () => { this.props.dispatch(restartWorfklow(this.props.workflowId)); }; restartWithLatestDefinition = () => { this.props.dispatch(restartWorfklow(this.props.workflowId, true)) } retry = () => { this.props.dispatch(retryWorfklow(this.props.workflowId)); }; pause = () => { this.props.dispatch(pauseWorfklow(this.props.workflowId)); }; resume = () => { this.props.dispatch(resumeWorfklow(this.props.workflowId)); }; render() { const { terminating, restarting, retrying, pausing, resuming } = this.props; const ttTerm = ( <Popover id="popover-trigger-hover-focus" title="Terminate Workflow"> Terminate workflow execution. All running tasks will be cancelled. </Popover> ); const ttRestart = ( <Popover id="popover-trigger-hover-focus" title="Restart Workflow"> <p> Restart the workflow from the begining (First Task).</p> <div> <Button bsStyle="default" bsSize="xsmall" disabled={restarting} onClick={!restarting ? this.restart : null}> {restarting ? <i className="fa fa-spinner fa-spin" /> : 'Restart With Current Definition'} </Button> &nbsp; <Button bsStyle="default" bsSize="xsmall" disabled={restarting} onClick={!restarting ? this.restartWithLatestDefinition : null}> {restarting ? <i className="fa fa-spinner fa-spin" /> : 'Restart With Latest Definition'} </Button> </div> </Popover> ); const ttRetry = ( <Popover id="popover-trigger-hover-focus" title="Retry Last Failed Task"> Retry the last failed task and put workflow in running state </Popover> ); const ttPause = ( <Popover id="popover-trigger-hover-focus" title="Pause Workflow"> Pauses workflow execution. No new tasks will be scheduled until workflow has been resumed. </Popover> ); const ttResume = ( <Popover id="popover-trigger-hover-focus" title="Resume Workflow"> Resume workflow execution </Popover> ); if (this.props.workflowStatus === 'RUNNING') { return ( <ButtonGroup> <OverlayTrigger placement="bottom" overlay={ttTerm}> <Button bsStyle="danger" bsSize="xsmall" disabled={terminating} onClick={!terminating ? this.terminate : null} > {terminating ? <i className="fa fa-spinner fa-spin" /> : 'Terminate'} </Button> </OverlayTrigger> <OverlayTrigger placement="bottom" overlay={ttPause}> <Button bsStyle="warning" bsSize="xsmall" disabled={pausing} onClick={!pausing ? this.pause : null}> {pausing ? <i className="fa fa-spinner fa-spin" /> : 'Pause'} </Button> </OverlayTrigger> </ButtonGroup> ); } if (this.props.workflowStatus === 'COMPLETED') { return ( <OverlayTrigger placement="bottom" trigger="click" overlay={ttRestart}> <Button bsStyle="default" bsSize="xsmall" disabled={restarting}> {restarting ? <i className="fa fa-spinner fa-spin" /> : 'Restart'} </Button> </OverlayTrigger> ); } else if (this.props.workflowStatus === 'FAILED' || this.props.workflowStatus === 'TERMINATED') { return ( <ButtonGroup> <OverlayTrigger placement="bottom" overlay={ttRestart}> <Button bsStyle="default" bsSize="xsmall" disabled={restarting}> {restarting ? <i className="fa fa-spinner fa-spin" /> : 'Restart'} </Button> </OverlayTrigger> <OverlayTrigger placement="bottom" overlay={ttRetry}> <Button bsStyle="default" bsSize="xsmall" disabled={retrying} onClick={!retrying ? this.retry : null}> {retrying ? <i className="fa fa-spinner fa-spin" /> : 'Retry'} </Button> </OverlayTrigger> </ButtonGroup> ); } else if (this.props.workflowStatus === 'PAUSED') { return ( <ButtonGroup> <OverlayTrigger placement="bottom" overlay={ttResume}> <Button bsStyle="success" bsSize="xsmall" disabled={resuming} onClick={!resuming ? this.resume : null}> {resuming ? <i className="fa fa-spinner fa-spin" /> : 'Resume'} </Button> </OverlayTrigger> </ButtonGroup> ); } return ( <ButtonGroup> <OverlayTrigger placement="bottom" overlay={ttRestart}> <Button bsStyle="default" bsSize="xsmall" disabled={restarting}> {restarting ? <i className="fa fa-spinner fa-spin" /> : 'Restart'} </Button> </OverlayTrigger> </ButtonGroup> ); } } export default connect(state => state.workflow)(WorkflowAction);
JavaScript
0.000001
@@ -3867,32 +3867,48 @@ acement=%22bottom%22 + trigger=%22click%22 overlay=%7BttRest @@ -4967,32 +4967,48 @@ acement=%22bottom%22 + trigger=%22click%22 overlay=%7BttRest
cbb8d2c65205c670ca75fb449a577857b1bdc2a5
Change the position of popup
assets/js/UserPopup.js
assets/js/UserPopup.js
import React from 'react' import { Popup, Image, Segment, Container, Statistic, Icon } from 'semantic-ui-react' const User = ({ user, children }) => { const url = user.url || `https://twitter.com/${user.screen_name}` const profile_banner_url = user.profile_banner_url const items = [ {label: 'Tweets', value: user.statuses_count}, {label: 'Following', value: user.friends_count}, {label: 'Followers', value: user.followers_count}, ] return ( <Popup trigger={children} position='bottom right' hoverable wide size='huge' > <a href={url}>{user.name}</a> {profile_banner_url ? ( <Image src={profile_banner_url} fluid /> ) : null} {user.description && user.description.length > 0 ? ( <Segment basic> {user.description} </Segment> ) : null} <Statistic.Group items={items} size='mini' horizontal /> </Popup> ) } export default User
JavaScript
0.00009
@@ -521,12 +521,11 @@ tom -righ +lef t'%0A
6af358b8b9f6f385accc9412e72b39fd80ed992e
Update html5shiv to v3.7.0.
assets/js/html5shiv.js
assets/js/html5shiv.js
/* HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ (function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag(); a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/\w+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}</style>"; c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode|| "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup main mark meter nav output progress section summary time video",version:"3.6.2",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);if(g)return a.createDocumentFragment(); for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
JavaScript
0
@@ -11,19 +11,19 @@ Shiv v3. -6.2 +7.0 %7C @afar @@ -800,10 +800,14 @@ ce(/ +%5B %5Cw +%5C-%5D +/g, @@ -1090,16 +1090,23 @@ e,aside, +dialog, figcapti @@ -1199,16 +1199,38 @@ or:#000%7D +template%7Bdisplay:none%7D %3C/style%3E @@ -1941,16 +1941,23 @@ details +dialog figcapti @@ -2039,16 +2039,25 @@ summary +template time vid @@ -2075,11 +2075,11 @@ :%223. -6.2 +7.0 %22,sh @@ -2244,24 +2244,25 @@ b)%7Ba%7C%7C(a=f); +%0A if(g)return @@ -2288,17 +2288,16 @@ gment(); -%0A for(var
1c944e1e75fc67206d3007ed1d42032f26580156
Clean up
source/core/objects/audio/PositionalAudio.js
source/core/objects/audio/PositionalAudio.js
"use strict"; /** * PositionalAudio is used to play audio with positional audio effect using a WebAudio panner. * * Using the positional audio object the sound is controlled by the camera that renders first in the scene. * * @param {Audio} audio Audio used by this emitter * @class PositionalAudio * @extends {AudioEmitter} * @module Audio */ function PositionalAudio(audio) { AudioEmitter.call(this, audio); this.type = "PositionalAudio"; this.matrixAutoUpdate = true; /** * Distance model to be applied to the audio panner. * * @property distanceModel * @type {String} */ this.distanceModel = "inverse"; /** * Model to be applied to the audio panner. * * @property panningModel * @type {String} */ this.panningModel = "HRTF"; /** * WebAudio panner effect. * * https://developer.mozilla.org/en-US/docs/Web/API/PannerNode * * @property panner * @type {PannerNode} */ this.panner = this.context.createPanner(); this.panner.connect(this.gain); this.panner.panningModel = this.panningModel; this.panner.distanceModel = this.distanceModel; this.panner.refDistance = 1; this.panner.maxDistance = 10000; this.panner.rolloffFactor = 1; this.panner.coneInnerAngle = 360; this.panner.coneOuterAngle = 0; this.panner.coneOuterGain = 0; this.cameras = null; this.tempPosition = new THREE.Vector3(); this.tempPositionCamera = new THREE.Vector3(); this.tempQuaternionCamera = new THREE.Quaternion(); } THREE._PositionalAudio = THREE.PositionalAudio; THREE.PositionalAudio = PositionalAudio; PositionalAudio.prototype = Object.create(AudioEmitter.prototype); /** * Initialize audio object, loads audio data decodes it and starts playback if autoplay is set to True. * * @method initialize */ PositionalAudio.prototype.initialize = function() { AudioEmitter.prototype.initialize.call(this); var node = this; while(node.parent !== null) { node = node.parent; if(node instanceof Scene) { this.cameras = node.cameras; } } }; /** * Update positional audio panner relative to the camera. * * @method update */ PositionalAudio.prototype.update = function(delta) { if(this.cameras.length > 0) { var camera = this.cameras[0]; this.getWorldPosition(this.tempPosition); camera.getWorldPosition(this.tempPositionCamera); camera.getWorldQuaternion(this.tempQuaternionCamera); this.tempPosition.sub(this.tempPositionCamera); this.tempPosition.z = -this.tempPosition.z; this.tempPosition.applyQuaternion(this.tempQuaternionCamera); this.panner.setPosition(this.tempPosition.x, this.tempPosition.z, this.tempPosition.y); } else { this.panner.setPosition(0, 0, 0); this.panner.setOrientation(0, 0, 0); } THREE.Object3D.prototype.update.call(this, delta); }; /** * Get output audio node. * * @method getOutput * @return {Object} Output audio node. */ PositionalAudio.prototype.getOutput = function() { return this.panner; }; /** * Get reference distance. * * @method getRefDistance * @return {Number} Reference distance. */ PositionalAudio.prototype.getRefDistance = function() { return this.panner.refDistance; }; /** * Set reference distance. * * @method setRefDistance * @param {Number} value Reference distance. */ PositionalAudio.prototype.setRefDistance = function(value) { this.panner.refDistance = value; }; /** * Get rolloff factor. * * @method getRolloffFactor * @return {Number} Rolloff factor. */ PositionalAudio.prototype.getRolloffFactor = function() { return this.panner.rolloffFactor; }; /** * Set rolloff factor. * * @method setRolloffFactor * @param {Number} value Rolloff factor. */ PositionalAudio.prototype.setRolloffFactor = function(value) { this.panner.rolloffFactor = value; }; /** * Get distance model in use by this audio emitter. * * @method getDistanceModel * @return {String} Distance model. */ PositionalAudio.prototype.getDistanceModel = function() { return this.panner.distanceModel; }; /** * Set distance model to be used. * * Distance model defined how the emitter controls its volume from its position in the world, relative to the camera. * * By default the mode used is "inverse", can be also set to: * - "linear": A linear distance model calculating the gain induced by the distance according to * - 1 - rolloffFactor * (distance - refDistance) / (maxDistance - refDistance) * - "inverse": An inverse distance model calculating the gain induced by the distance according to: * - refDistance / (refDistance + rolloffFactor * (distance - refDistance)) * - "exponential": An exponential distance model calculating the gain induced by the distance according to: * - pow(distance / refDistance, -rolloffFactor). * * @method setDistanceModel * @param {String} model Distance Model to be used. */ PositionalAudio.prototype.setDistanceModel = function(distanceModel) { this.panner.distanceModel = distanceModel; }; /** * Get maximum distance for this audio emitter. * * @method getMaxDistance * @return Maximum distance. */ PositionalAudio.prototype.getMaxDistance = function() { return this.panner.maxDistance; }; /** * Set maximum distance for this audio emitter. * * @method setMaxDistance * @param {Number} value Maximum distance. */ PositionalAudio.prototype.setMaxDistance = function(value) { this.panner.maxDistance = value; }; PositionalAudio.prototype.toJSON = function(meta) { var data = AudioEmitter.prototype.toJSON.call(this, meta); //data.object.distanceModel = distanceModel; //data.object.panningModel = panningModel; return data; };
JavaScript
0.000002
@@ -5700,16 +5700,62 @@ ta);%0D%0A%0D%0A +%09//TODO %3CSERIALIZE AND LOAD THESE VALUES%3E%0D%0A%09%0D%0A %09//data. @@ -5769,32 +5769,37 @@ distanceModel = +this. distanceModel;%0D%0A @@ -5828,16 +5828,21 @@ Model = +this. panningM
b331a9be6a287eb2913e663598618005a0cd1b23
Fix launcher logging
source/main/cardano/CardanoWalletLauncher.js
source/main/cardano/CardanoWalletLauncher.js
// @flow import { merge } from 'lodash'; import * as cardanoLauncher from 'cardano-launcher'; import type { Launcher } from 'cardano-launcher'; import type { NodeConfig } from '../config'; import { STAKE_POOL_REGISTRY_URL } from '../config'; import { NIGHTLY, SELFNODE, QA, ITN_REWARDS_V1, } from '../../common/types/environment.types'; import { Logger } from '../utils/logging'; export type WalletOpts = { nodeImplementation: 'jormungandr' | 'cardano-node', nodeConfig: NodeConfig, cluster: string, stateDir: string, block0Path: string, block0Hash: string, secretPath: string, configPath: string, syncTolerance: string, logFile: any, }; export function CardanoWalletLauncher(walletOpts: WalletOpts): Launcher { const { nodeImplementation, nodeConfig, // For cardano-node / byron only! cluster, stateDir, block0Path, block0Hash, secretPath, configPath, syncTolerance, logFile, } = walletOpts; // TODO: Update launcher config to pass number const syncToleranceSeconds = parseInt(syncTolerance.replace('s', ''), 10); // Shared launcher config (node implementations agnostic) const launcherConfig = { networkName: cluster, stateDir, nodeConfig: { kind: nodeImplementation, configurationDir: '', network: { configFile: configPath, }, }, syncToleranceSeconds, childProcessLogWriteStream: logFile, }; // This switch statement handles any node specifc // configuration, prior to spawning the child process Logger.info('Node implementation', { nodeImplementation }); switch (nodeImplementation) { case 'cardano': merge(launcherConfig, { nodeConfig }); break; case 'jormungandr': if (cluster === SELFNODE) { merge(launcherConfig, { apiPort: 8088, nodeConfig: { restPort: 8888, network: { genesisBlock: { file: block0Path, hash: block0Hash, }, secretFile: [secretPath], }, }, stakePoolRegistryUrl: STAKE_POOL_REGISTRY_URL[SELFNODE], }); } if (cluster === NIGHTLY) { merge(launcherConfig, { nodeConfig: { network: { genesisBlock: { hash: block0Hash, }, }, }, stakePoolRegistryUrl: STAKE_POOL_REGISTRY_URL[NIGHTLY], }); } if (cluster === QA) { merge(launcherConfig, { nodeConfig: { network: { genesisBlock: { hash: block0Hash, }, }, }, stakePoolRegistryUrl: STAKE_POOL_REGISTRY_URL[QA], }); } if (cluster === ITN_REWARDS_V1) { merge(launcherConfig, { nodeConfig: { network: { genesisBlock: { file: block0Path, hash: block0Hash, }, }, }, }); } break; default: break; } Logger.info('Setting up CardanoLauncher now...', { walletOpts, launcherConfig, }); return new cardanoLauncher.Launcher(launcherConfig); }
JavaScript
0
@@ -3248,13 +3248,21 @@ erConfig +, Logger );%0A%7D%0A
5de339f6bfbe97963811d530c632223bda3ba537
Refactor button render
src/Components/Table/TableRow/index.js
src/Components/Table/TableRow/index.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import Button from '../../Button/index.js' export default class TableRow extends Component{ static propTypes = { readOnly: PropTypes.bool, editing: PropTypes.bool, cells: PropTypes.arrayOf(PropTypes.shape({ value: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]).isRequired, type: PropTypes.string })).isRequired } static defaultProps = { editing: false, } state = { editing: this.props.editing, cells: this.props.cells } handleChange = (e, index) => { const cells = this.state.cells.map((cell, i) => { return i === index ? {...cell, value: e.target.value} : cell }) this.setState({cells}) } handleSubmit = (e) => { e.preventDefault() this.setState({editing: false}) } setEditing = () =>{ this.setState({editing: true}) } render(){ if(this.state.editing){ const cells = this.state.cells.map((cell, index) => { return( <div className="tableCell" key={index}> <input key={index} type={cell.type} value={cell.value} onChange={(e) => {this.handleChange(e, index)}} /> </div> ) }) return( <div className="tableRow"> <form onSubmit={this.handleSubmit}> {cells} <Button onClick={() => {}} className="round" type="submit" buttonText="save" backgroundColor="#05a905" /> </form> </div> ) }else{ const cells = this.state.cells.map((cell, index) => { return( <div className="tableCell" key={index}> <p>{cell.value}</p> </div> ) }) return( <div className="tableRow"> {cells} <Button className="round" onClick={this.setEditing} buttonText="edit" backgroundColor="#a7a6a6" /> </div> ) } } }
JavaScript
0
@@ -1977,35 +1977,47 @@ -%3CButton%0A +%7Bthis.props.readOnly %7C%7C %3CButton classNa @@ -2026,28 +2026,16 @@ =%22round%22 -%0A onClick @@ -2052,28 +2052,16 @@ Editing%7D -%0A buttonT @@ -2070,28 +2070,16 @@ t=%22edit%22 -%0A backgro @@ -2100,21 +2100,12 @@ 6a6%22 -%0A /%3E +%7D %0A
b785ec0ecb78eb020397cc5ed88c020361843b51
missing title
app/assets/javascripts/components/CollectionTree.js
app/assets/javascripts/components/CollectionTree.js
import React from 'react'; import {Button,Glyphicon} from 'react-bootstrap'; import CollectionStore from './stores/CollectionStore'; import CollectionActions from './actions/CollectionActions'; import CollectionSubtree from './CollectionSubtree'; import UIActions from './actions/UIActions'; import UIStore from './stores/UIStore'; export default class CollectionTree extends React.Component { constructor(props) { super(props); this.state = CollectionStore.getState(); } componentDidMount() { CollectionStore.listen(this.onChange.bind(this)); CollectionActions.fetchLockedCollectionRoots(); CollectionActions.fetchUnsharedCollectionRoots(); CollectionActions.fetchSharedCollectionRoots(); CollectionActions.fetchRemoteCollectionRoots(); } componentWillUnmount() { CollectionStore.unlisten(this.onChange.bind(this)); } onChange(state) { this.setState(state); } lockedSubtrees() { const roots = this.state.lockedRoots; return this.subtrees(roots, null, false); } unsharedSubtrees() { let roots = this.state.unsharedRoots; return this.subtrees(roots, null, false); } sharedSubtrees() { let roots = this.state.sharedRoots; let sharedWithLabels = roots.map((root) => { return root.label; }).unique(); let fakeRoots = sharedWithLabels.map((label) => { return { label: label, id: '', children: [], descendant_ids: [] } }); this.assignRootsAsChildrenToFakeRoots(roots, fakeRoots); fakeRoots.forEach((root) => { root.label = root.label.replace('project', 'projects'); }); return this.subtrees(fakeRoots, <div className="tree-view"><div className={"title "} style={{backgroundColor:'white'}}><i className="fa fa-list" /> My shared projects <i className="fa fa-share-alt" /></div></div>, false); } remoteSubtrees() { let roots = this.state.remoteRoots; // for unique see below (end of file) let sharedByNames = roots.map((root) => { return root.shared_by_name }).unique(); let fakeRoots = sharedByNames.map((name) => { return { label: 'From ' + name, id: '',//'from-' + this.convertToSlug(name), children: [], descendant_ids: [] } }); this.assignRootsAsChildrenToFakeRoots(roots, fakeRoots); return this.subtrees(fakeRoots, 'Shared with me', true) } convertToSlug(name) { return name.toLowerCase() } assignRootsAsChildrenToFakeRoots(roots, fakeRoots) { roots.forEach((root) => { let fakeRootForRoot = fakeRoots.filter((fakeRoot) => { return fakeRoot.label == `From ${root.shared_by_name}` || fakeRoot.label == root.label; })[0]; fakeRootForRoot.children.push(root); fakeRootForRoot.descendant_ids.push(root.id); }) } subtrees(roots, label, isRemote) { if(roots.length > 0) { let subtrees = roots.map((root, index) => { return <CollectionSubtree key={index} root={root} isRemote={isRemote}/> }); return ( <div> {label} {subtrees} </div> ) } else { return <div></div>; } } collectionManagementButton() { return ( <div className="take-ownership-btn"> <Button bsStyle="danger" bsSize="xsmall" onClick={() => this.handleCollectionManagementToggle()}> <i className="fa fa-cog"></i> </Button> </div> ) } handleCollectionManagementToggle() { UIActions.toggleCollectionManagement(); const {showCollectionManagement, currentCollection} = UIStore.getState(); if(showCollectionManagement) { Aviator.navigate('/collection/management'); } else { if(currentCollection.label == 'All') { Aviator.navigate(`/collection/all/${this.urlForCurrentElement()}`); } else { Aviator.navigate(`/collection/${currentCollection.id}/${this.urlForCurrentElement()}`); } } } urlForCurrentElement() { const {currentElement} = ElementStore.getState(); if(currentElement) { if(currentElement.isNew) { return `${currentElement.type}/new`; } else{ return `${currentElement.type}/${currentElement.id}`; } } else { return ''; } } render() { return ( <div> <div className="tree-view">{this.collectionManagementButton()}<div className={"title "} style={{backgroundColor:'white'}}><i className="fa fa-list" /> Collections </div></div> <div className="tree-wrapper"> {this.lockedSubtrees()} {this.unsharedSubtrees()} </div> <div className="tree-wrapper"> {this.sharedSubtrees()} </div> <div className="tree-wrapper"> {this.remoteSubtrees()} </div> </div> ) } } Array.prototype.unique = function(a){ return function(){ return this.filter(a) } }(function(a,b,c){ return c.indexOf(a,b+1) < 0 });
JavaScript
0.999773
@@ -2387,24 +2387,184 @@ ts, -'Shared with me' +%3Cdiv className=%22tree-view%22%3E%3Cdiv className=%7B%22title %22%7D style=%7B%7BbackgroundColor:'white'%7D%7D%3E%3Ci className=%22fa fa-list%22 /%3E Shared with me %3Ci className=%22fa fa-share-alt%22 /%3E%3C/div%3E%3C/div%3E , tr
30d7bc9040a3d162fa0b1d3e6c1d075e53889b97
fix date format issue with datepicker label
app/assets/javascripts/lib/components/datepicker.js
app/assets/javascripts/lib/components/datepicker.js
// ------------------------------------------------------------------------------ // // Datepicker // // ------------------------------------------------------------------------------ define([ "jquery", "picker", "pickerDate", "pickerLegacy" ], function($) { "use strict"; var defaults = { callbacks: {}, dateFormat: "d mmm yyyy", dateFormatLabel: "yyyy/mm/dd", listener: "#js-row--content", target: "#js-row--content", startSelector: "#js-av-start", endSelector: "#js-av-end", startLabelSelector: ".js-av-start-label", endLabelSelector: ".js-av-end-label" }; // @args = {} // el: {string} selector for parent element // listener: {string} selector for the listener function Datepicker(args) { this.config = $.extend({}, defaults, args); this.$listener = $(this.config.listener); this.init(); } Datepicker.prototype.init = function() { var _this = this, today = [], tomorrow = [], d = new Date(), inOpts, outOpts; this.inDate = $(this.config.target).find(this.config.startSelector); this.outDate = $(this.config.target).find(this.config.endSelector); this.inLabel = $(this.config.startLabelSelector); this.outLabel = $(this.config.endLabelSelector); this.firstTime = !!this.inDate.val(); this.day = 86400000; today.push(d.getFullYear(), d.getMonth(), d.getDate()); tomorrow.push(d.getFullYear(), d.getMonth(), (d.getDate() + 1)); inOpts = { format: this.config.dateFormat, onSet: function() { _this._dateSelected(this.get("select", _this.config.dateFormatLabel), "start"); } }; outOpts = { format: this.config.dateFormat, onSet: function() { _this._dateSelected(this.get("select", _this.config.dateFormatLabel), "end"); } }; if (this.config.backwards) { inOpts.max = today; outOpts.max = today; } else { inOpts.min = today; outOpts.min = tomorrow; } this.inDate.pickadate(inOpts); this.outDate.pickadate(outOpts); }; // ------------------------------------------------------------------------- // Private Functions // ------------------------------------------------------------------------- Datepicker.prototype._dateSelected = function(date, type) { if (type === "start") { if (!this._isValidEndDate()) { this.outDate.data("pickadate").set("select", new Date(date).getTime() + this.day); } this.inLabel.text(date); } else if (type === "end") { if (!this._isValidEndDate() || this.firstTime) { this.inDate.data("pickadate").set("select", new Date(date).getTime() - this.day); } this.outLabel.text(this.outDate.val()).removeClass("is-hidden"); } this.firstTime = false; if (this.config.callbacks.onDateSelect) { this.config.callbacks.onDateSelect(date, type); } }; Datepicker.prototype._inValue = function() { return new Date($(this.inDate).data("pickadate").get("select", this.config.dateFormatLabel)); }; Datepicker.prototype._outValue = function() { return new Date($(this.outDate).data("pickadate").get("select", this.config.dateFormatLabel)); }; Datepicker.prototype._isValidEndDate = function() { return this._inValue() < this._outValue(); }; return Datepicker; });
JavaScript
0
@@ -2503,20 +2503,33 @@ el.text( -date +this.inDate.val() );%0A %7D
266c044f79080a67ac6a34d309bfd25e8364046a
parse referal code
app/assets/javascripts/map/services/PlaceService.js
app/assets/javascripts/map/services/PlaceService.js
/** * The PlaceService class manages places in the application. * * A place is just the current state of the application which can be * represented as an Object or a URL. For example, the place associated with: * * http://localhost:5000/map/6/2/17/ALL/terrain/loss * * Can also be represented like this: * * zoom - 6 * lat - 2 * lng - 17 * iso - ALL * maptype - terrain * baselayers - loss * * The PlaceService class handles the following use cases: * * 1) New route updates views * * The Router receives a new URL and all application views need to be updated * with the state encoded in the URL. * * Here the router publishes the "Place/update" event passing in the route * name and route parameters. The PlaceService handles the event by * standardizing the route parameters and publishing them in a "Place/go" * event. Any presenters listening to the event receives the updated * application state and can update their views. * * 2) Updated view updates URL * * A View state changes (e.g., a new map zoom) and the URL needs to be * updated, not only with its new state, but from the state of all views in * the application that provide state for URLs. * * Here presenters publishe the "Place/register" event passing in a * reference to themselves. The PlaceService subscribes to the * "Place/register" event so that it can keep references to all presenters * that provide state. Then the view publishes the "Place/update" event * passing in a "go" parameter. If "go" is false, the PlaceService will * update the URL. Otherwise it will publish the "Place/go" event which will * notify all subscribed presenters. * * @return {PlaceService} The PlaceService class */ define([ 'underscore', 'mps', 'uri', 'moment', 'map/presenters/PresenterClass', 'map/services/LayerSpecService' ], function (_, mps, UriTemplate, moment, PresenterClass, layerSpecService) { 'use strict'; var urlDefaultsParams = { baselayers: 'loss,forestgain', zoom: 3, lat: 15, lng: 27, maptype: 'grayscale', iso: 'ALL' }; var PlaceService = PresenterClass.extend({ _uriTemplate: '{name}{/zoom}{/lat}{/lng}{/iso}{/maptype}{/baselayers}{/sublayers}{?geojson,wdpaid,begin,end,threshold,dont_analyze}', /** * Create new PlaceService with supplied Backbone.Router. * * @param {Backbond.Router} router Instance of Backbone.Router */ init: function(router) { this.router = router; this._presenters = []; this._name = null; this._presenters.push(layerSpecService); // this makes the test fail this._super(); }, /** * Subscribe to application events. */ _subscriptions: [{ 'Place/register': function(presenter) { this._presenters = _.union(this._presenters, [presenter]); } }, { 'Place/update': function() { this._updatePlace(); } }], /** * Init by the router to set the name * and publish the first place. * * @param {String} name Place name * @param {Object} params Url params */ initPlace: function(name, params) { this._name = name; this._newPlace(params); }, /** * Silently updates the url from the presenter params. */ _updatePlace: function() { var route, params; params = this._destandardizeParams( this._getPresenterParams(this._presenters)); route = this._getRoute(params); this.router.navigateTo(route, {silent: true}); }, /** * Handles a new place. * * @param {Object} params The place parameters */ _newPlace: function(params) { var where, place = {}; place.params = this._standardizeParams(params); where = _.union(place.params.baselayers, place.params.sublayers); layerSpecService.toggle( where, _.bind(function(layerSpec) { place.layerSpec = layerSpec; mps.publish('Place/go', [place]); }, this) ); }, /** * Return route URL for supplied route name and route params. * * @param {Object} params The route params * @return {string} The route URL */ _getRoute: function(param) { var url = new UriTemplate(this._uriTemplate).fillFromObject(param); return decodeURIComponent(url); }, /** * Return standardized representation of supplied params object. * * @param {Object} params The params to standardize * @return {Object} The standardized params. */ _standardizeParams: function(params) { var p = _.extendNonNull({}, urlDefaultsParams, params); p.name = this._name; p.baselayers = _.map(p.baselayers.split(','), function(slug) { return {slug: slug}; }); p.sublayers = p.sublayers ? _.map(p.sublayers.split(','), function(id) { return {id: _.toNumber(id)}; }) : []; p.zoom = _.toNumber(p.zoom); p.lat = _.toNumber(p.lat); p.lng = _.toNumber(p.lng); p.iso = _.object(['country', 'region'], p.iso.split('-')); p.begin = p.begin ? moment(p.begin) : null; p.end = p.end ? moment(p.end) : null; p.geojson = p.geojson ? JSON.parse(decodeURIComponent(p.geojson)) : null; p.wdpaid = p.wdpaid ? _.toNumber(p.wdpaid) : null; p.threshold = p.threshold ? _.toNumber(p.threshold) : null; p.subscribe_alerts = (p.subscribe_alerts == 'subscribe') ? true : null; return p; }, /** * Return formated URL representation of supplied params object based on * a route name. * * @param {Object} params Place to standardize * @return {Object} Params ready for URL */ _destandardizeParams: function(params) { var p = _.extendNonNull({}, urlDefaultsParams, params); var baselayers = _.pluck(p.baselayers, 'slug'); p.name = this._name; p.baselayers = (baselayers.length > 0) ? baselayers : 'none'; p.sublayers = p.sublayers ? p.sublayers.join(',') : null; p.zoom = String(p.zoom); p.lat = p.lat.toFixed(2); p.lng = p.lng.toFixed(2); p.iso = _.compact(_.values(p.iso)).join('-') || 'ALL'; p.begin = p.begin ? p.begin.format('YYYY-MM-DD') : null; p.end = p.end ? p.end.format('YYYY-MM-DD') : null; p.geojson = p.geojson ? encodeURIComponent(p.geojson) : null; p.wdpaid = p.wdpaid ? String(p.wdpaid) : null; p.threshold = p.threshold ? String(p.threshold) : null; return p; }, /** * Return param object representing state from all registered presenters * that implement getPlaceParams(). * * @param {Array} presenters The registered presenters * @return {Object} Params representing state from all presenters */ _getPresenterParams: function(presenters) { var p = {}; _.each(presenters, function(presenter) { _.extend(p, presenter.getPlaceParams()); }, this); return p; } }); return PlaceService; });
JavaScript
0.998608
@@ -5490,16 +5490,17 @@ lerts == += 'subscr @@ -5520,16 +5520,44 @@ : null;%0A + p.referal = p.referal; %0A r
5b21db962032eef6831c64b7f62684c0d3038a0f
Adding check for float value with multiple '.' characters PR: 32351
src/javascript/org/apache/commons/validator/javascript/validateFloat.js
src/javascript/org/apache/commons/validator/javascript/validateFloat.js
/*$RCSfile: validateFloat.js,v $ $Rev$ $Date$ */ /** * Check to see if fields are a valid float. * Fields are not checked if they are disabled. * <p> * @param form The form validation is taking place on. */ function validateFloat(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); oFloat = eval('new ' + retrieveFormName(form) + '_FloatValidations()'); for (x in oFloat) { var field = form[oFloat[x][0]]; if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'select-one' || field.type == 'radio') && field.disabled == false) { var value = ''; // get field's value if (field.type == "select-one") { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } else { value = field.value; } if (value.length > 0) { // remove '.' before checking digits var tempArray = value.split('.'); //Strip off leading '0' var zeroIndex = 0; var joinedString= tempArray.join(''); while (joinedString.charAt(zeroIndex) == '0') { zeroIndex++; } var noZeroString = joinedString.substring(zeroIndex,joinedString.length); if (!isAllDigits(noZeroString)) { bValid = false; if (i == 0) { focusField = field; } fields[i++] = oFloat[x][1]; } else { var iValue = parseFloat(value); if (isNaN(iValue)) { if (i == 0) { focusField = field; } fields[i++] = oFloat[x][1]; bValid = false; } } } } } if (fields.length > 0) { focusField.focus(); alert(fields.join('\n')); } return bValid; }
JavaScript
0.997225
@@ -1741,16 +1741,40 @@ oString) + %7C%7C tempArray.length %3E 2 ) %7B%0A
705611560d73bc68a27d24a2614fb1b5a3818945
Fix geometry buffer exporting
src/GeometryBuffer.js
src/GeometryBuffer.js
import Buffer from './Buffer'; /** * Используется для хранения и подготовки данных для передачи в атрибуты шейдера. * В отличие от {@link Buffer}, принимает в качестве аргумента типизированный массив. * Это позволяет работать с данными в {@link Geometry}, например, вычислять BoundingBox. * * @param {TypedArray} array Типизированный массив данных, например, координат вершин * @param {?BufferBindOptions} options Параметры передачи буфера в видеокарту */ export default class GeometryBuffer extends Buffer { constructor(array, options) { super(array, options); this._array = array; /** * Количество элементов в массиве данных * @type {Number} */ this.length = array.length / this.options.itemSize; } /** * Возвращает массив данных * @returns {TypedArray} */ getArray() { return this._array; } /** * Возвращает элемент из массива данных * @param {Number} index Номер элемента в массиве данных * @returns {TypedArray} */ getElement(index) { return this._array.subarray(index * this.options.itemSize, (index + 1) * this.options.itemSize); } /** * Возвращает тройку элементов из массива данных * @param {Number} index Индекс * @returns {TypedArray[]} */ getTriangle(index) { index *= 3; return [ this.getElement(index), this.getElement(index + 1), this.getElement(index + 2) ]; } /** * Конкатенирует данный буфер с другим. * Осторожно, метод не проверяет одинаковой размерности данные или нет. * @param {GeometryBuffer} buffer */ concat(buffer) { const addArray = buffer.getArray(); const newArray = new this._array.constructor(this._array.length + addArray.length); newArray.set(this._array, 0); newArray.set(addArray, this._array.length); this._array = newArray; this.length = newArray.length / this.options.itemSize; return this; } }
JavaScript
0.000001
@@ -461,23 +461,8 @@ */%0A -export default clas @@ -2051,8 +2051,40 @@ %7D%0A%7D%0A +%0Aexport default GeometryBuffer;%0A
3393213ce2606b91816caaf0abe1b525bb1b683b
use correct command builder in canary
app/scripts/modules/core/pipeline/config/stages/canary/canaryStage.js
app/scripts/modules/core/pipeline/config/stages/canary/canaryStage.js
'use strict'; let angular = require('angular'); module.exports = angular.module('spinnaker.core.pipeline.stage.canaryStage', [ require('../../../../../amazon/serverGroup/configure/serverGroupCommandBuilder.service.js'), require('../../../../cloudProvider/cloudProvider.registry.js'), ]) .config(function (pipelineConfigProvider, settings) { if (settings.feature.canary === true) { pipelineConfigProvider.registerStage({ label: 'Canary', description: 'Canary tests new changes against a baseline version', key: 'canary', templateUrl: require('./canaryStage.html'), executionDetailsUrl: require('./canaryExecutionDetails.html'), executionSummaryUrl: require('./canaryExecutionSummary.html'), executionLabelTemplateUrl: require('./canaryExecutionLabel.html'), controller: 'CanaryStageCtrl', controllerAs: 'canaryStageCtrl', validators: [ { type: 'stageBeforeType', stageTypes: ['bake', 'findAmi'], message: 'You must have a Bake or Find AMI stage before a canary stage.' }, ], }); } }) .controller('CanaryStageCtrl', function ($scope, $modal, stage, _, namingService, providerSelectionService, authenticationService, cloudProviderRegistry, serverGroupCommandBuilder, awsServerGroupTransformer, accountService) { var user = authenticationService.getAuthenticatedUser(); $scope.stage = stage; $scope.stage.baseline = $scope.stage.baseline || {}; $scope.stage.scaleUp = $scope.stage.scaleUp || {}; $scope.stage.canary = $scope.stage.canary || {}; $scope.stage.canary.owner = $scope.stage.canary.owner || (user.authenticated ? user.name : null); $scope.stage.canary.watchers = $scope.stage.canary.watchers || []; $scope.stage.canary.canaryConfig = $scope.stage.canary.canaryConfig || { name: [$scope.pipeline.name, 'Canary'].join(' - ') }; $scope.stage.canary.canaryConfig.canaryAnalysisConfig = $scope.stage.canary.canaryConfig.canaryAnalysisConfig || {}; $scope.stage.canary.canaryConfig.canaryAnalysisConfig.notificationHours = $scope.stage.canary.canaryConfig.canaryAnalysisConfig.notificationHours || []; accountService.listAccounts('aws').then(function(accounts) { $scope.accounts = accounts; }); $scope.notificationHours = $scope.stage.canary.canaryConfig.canaryAnalysisConfig.notificationHours.join(','); this.splitNotificationHours = function() { var hoursField = $scope.notificationHours || ''; $scope.stage.canary.canaryConfig.canaryAnalysisConfig.notificationHours = _.map(hoursField.split(','), function(str) { if (!parseInt(str.trim()).isNaN) { return parseInt(str.trim()); } return 0; }); }; this.getRegion = function(cluster) { var availabilityZones = cluster.availabilityZones; if (availabilityZones) { var regions = Object.keys(availabilityZones); if (regions && regions.length) { return regions[0]; } } return 'n/a'; }; function getClusterName(cluster) { return namingService.getClusterName(cluster.application, cluster.stack, cluster.freeFormDetails); } this.getClusterName = getClusterName; function cleanupClusterConfig(cluster, type) { delete cluster.credentials; if (cluster.freeFormDetails && cluster.freeFormDetails.split('-').pop() === type.toLowerCase()) { return; } if (cluster.freeFormDetails) { cluster.freeFormDetails += '-'; } cluster.freeFormDetails += type.toLowerCase(); } function configureServerGroupCommandForEditing(command) { command.viewState.disableStrategySelection = true; command.viewState.hideClusterNamePreview = true; command.viewState.readOnlyFields = { credentials: true, region: true, subnet: true }; delete command.strategy; } this.addClusterPair = function() { $scope.stage.clusterPairs = $scope.stage.clusterPairs || []; providerSelectionService.selectProvider($scope.application).then(function(selectedProvider) { let config = cloudProviderRegistry.getValue(selectedProvider, 'serverGroup'); $modal.open({ templateUrl: config.cloneServerGroupTemplateUrl, controller: `${config.cloneServerGroupController} as ctrl`, resolve: { title: function () { return 'Add Cluster Pair'; }, application: function () { return $scope.application; }, serverGroupCommand: function () { return serverGroupCommandBuilder.buildNewServerGroupCommandForPipeline(selectedProvider) .then(function(command) { configureServerGroupCommandForEditing(command); command.viewState.overrides = { capacity: { min: 1, max: 1, desired: 1, } }; command.viewState.disableNoTemplateSelection = true; command.viewState.customTemplateMessage = 'Select a template to configure the canary and baseline ' + 'cluster pair. If you want to configure the server groups differently, you can do so by clicking ' + '"Edit" after adding the pair.'; return command; }); }, } }).result.then(function(command) { var baselineCluster = awsServerGroupTransformer.convertServerGroupCommandToDeployConfiguration(command), canaryCluster = _.cloneDeep(baselineCluster); cleanupClusterConfig(baselineCluster, 'baseline'); cleanupClusterConfig(canaryCluster, 'canary'); $scope.stage.clusterPairs.push({baseline: baselineCluster, canary: canaryCluster}); }); }); }; this.editCluster = function(cluster, index, type) { cluster.provider = cluster.provider || 'aws'; let config = cloudProviderRegistry.getValue(cluster.provider, 'serverGroup'); $modal.open({ templateUrl: config.cloneServerGroupTemplateUrl, controller: `${config.cloneServerGroupController} as ctrl`, resolve: { title: function () { return 'Configure ' + type + ' Cluster'; }, application: function () { return $scope.application; }, serverGroupCommand: function () { return serverGroupCommandBuilder.buildServerGroupCommandFromPipeline($scope.application, cluster) .then(function(command) { configureServerGroupCommandForEditing(command); var detailsParts = command.freeFormDetails.split('-'); var lastPart = detailsParts.pop(); if (lastPart === type.toLowerCase()) { command.freeFormDetails = detailsParts.join('-'); } return command; }); }, } }).result.then(function(command) { var stageCluster = awsServerGroupTransformer.convertServerGroupCommandToDeployConfiguration(command); cleanupClusterConfig(stageCluster, type); $scope.stage.clusterPairs[index][type.toLowerCase()] = stageCluster; }); }; this.deleteClusterPair = function(index) { $scope.stage.clusterPairs.splice(index, 1); }; }).name;
JavaScript
0.000001
@@ -149,18 +149,8 @@ /../ -../amazon/ serv @@ -167,16 +167,23 @@ nfigure/ +common/ serverGr @@ -204,16 +204,8 @@ der. -service. js')
f0932cad23a963d9c3513b8b4f6ce99f7b570da9
Fix forward button behaviour
Environment.js
Environment.js
"use strict"; var merge = require('react/lib/merge'); var ReactUpdates = require('react/lib/ReactUpdates'); /** * Base methods for an environment. * * @private */ var EnvironmentBase = { notify: function(cb) { var latch = this.routers.length; ReactUpdates.batchedUpdates(function() { for (var i = 0, len = this.routers.length; i < len; i++) { this.routers[i].setPath(this.path, function() { latch -= 1; if (cb && latch === 0) { cb(); } }); } }.bind(this)); }, register: function(router) { if (this.routers.length === 0) { this.start(); } if (!router.getParentRouter()) { this.routers.push(router); } }, unregister: function(router) { this.routers.splice(this.routers.indexOf(router), 1); if (this.routers.length === 0) { this.stop(); } } }; /** * Routing method which routes on window.location.pathname. */ var PathnameRoutingMethod = merge(EnvironmentBase, { getPath: function() { return window.location.pathname; }, setPath: function(path, cb) { window.history.pushState({}, '', path); this.path = path; this.notify(cb); }, start: function() { window.addEventListener('popstate', this.onPopState.bind(this)); }, stop: function() { window.removeEventListener('popstate', this.onPopState.bind(this)); }, onPopState: function(e) { var path = window.location.pathname; if (this.path !== path) { this.setPath(path); } } }); /** * Routing method which routes on window.location.hash. */ var HashRoutingMethod = merge(EnvironmentBase, { getPath: function() { return window.location.hash.slice(1); }, setPath: function(path, cb) { window.location.hash = path; this.path = path; this.notify(cb); }, start: function() { window.addEventListener('hashchange', this.onHashChange.bind(this)); }, stop: function() { window.removeEventListener('hashchange', this.onHashChange.bind(this)); }, onHashChange: function() { var path = window.location.hash.slice(1); if (this.path !== path) { this.setPath(path); } } }); /** * Dummy routing environment which does nothing. Should be used on server and/or * in WebWorker. */ var DummyRoutingMethod = merge(EnvironmentBase, { getPath: function(path) { return null; }, setPath: function(path, cb) { cb(); }, start: function() {}, stop: function() {} }); /** * Create new routing environment which routes with specified method. * * @param {Object} method */ function createEnvironment(method) { var env = Object.create(method); env.path = env.getPath(); env.routers = []; return env; } module.exports.createEnvironment = createEnvironment; module.exports.PathnameRoutingMethod = PathnameRoutingMethod; module.exports.HashRoutingMethod = HashRoutingMethod; module.exports.DummyRoutingMethod = DummyRoutingMethod;
JavaScript
0.000013
@@ -1104,36 +1104,79 @@ unction(path, cb -) %7B%0A +, retrospective) %7B%0A if (!retrospective) %7B%0A window.histo @@ -1199,24 +1199,30 @@ '', path);%0A + %7D%0A this.pat @@ -1569,32 +1569,49 @@ his.setPath(path +, undefined, true );%0A %7D%0A %7D%0A%7D); @@ -1826,20 +1826,63 @@ path, cb -) %7B%0A +, retrospective) %7B%0A if (!retrospective) %7B%0A wind @@ -1898,32 +1898,38 @@ on.hash = path;%0A + %7D%0A this.path = @@ -2263,32 +2263,32 @@ ath !== path) %7B%0A - this.setPa @@ -2290,24 +2290,41 @@ setPath(path +, undefined, true );%0A %7D%0A %7D
31098d81dfeb18994c5c883b2741fcb59b02eb3e
add locales
src/modules/wallet/modules/transactions/controllers/TransactionsCtrl.js
src/modules/wallet/modules/transactions/controllers/TransactionsCtrl.js
(function () { 'use strict'; /** * @param {User} user * @param Base * @param {$rootScope.Scope} $scope * @param {TransactionsCsvGen} transactionsCsvGen * @param {Waves} waves * @param {IPollCreate} createPoll * @param {INotification} notification * @return {TransactionsCtrl} */ const controller = function (user, Base, $scope, transactionsCsvGen, waves, createPoll, notification) { const analytics = require('@waves/event-sender'); class TransactionsCtrl extends Base { constructor() { super($scope); /** * @type {ITransaction[]} */ this.transactions = []; /** * @type {boolean} */ this.pending = true; /** * @type {string} */ this.filter = null; /** * @type {ITransaction[]} * @private */ this.txList = []; /** * @type {number} */ this.limit = 100; this.observe(['filter'], this._sendAnalytics); this.syncSettings({ filter: 'wallet.transactions.filter' }); const poll = createPoll(this, this._getTxList, this._setTxList, 4000, { isBalance: true }); this.observe(['txList', 'filter'], this._applyTransactionList); this.observe('limit', () => poll.restart()); } exportTransactions(maxTransactions = 10000) { // analytics.push('TransactionsPage', `TransactionsPage.CSV.${WavesApp.type}`, 'download'); analytics.send({ name: 'Transactions Export Click', target: 'ui' }); const MAX_LIMIT = 1000; const getSeriesTransactions = async ({ allTransactions = [], after = '' } = {}) => { let transactions; let downloadError = false; try { transactions = await waves.node.transactions.list(MAX_LIMIT, after); } catch (e) { downloadError = true; if (!allTransactions.length) { notification.error({ ns: 'app.wallet.transactions', title: { literal: 'errors.download.title' }, body: { literal: 'errors.download.body' } }); return []; } transactions = []; notification.error({ ns: 'app.wallet.transactions', title: { literal: 'errors.complete.title' }, body: { literal: 'errors.complete.body' } }); } allTransactions = allTransactions.concat(transactions.filter(el => !user.scam[el.assetId])); if (transactions.length < MAX_LIMIT || allTransactions.length > maxTransactions) { return { allTransactions, downloadError }; } else { return getSeriesTransactions({ allTransactions, after: transactions[transactions.length - 1].id }); } }; const promiseGetTransactions = getSeriesTransactions(); promiseGetTransactions.then(({ allTransactions, downloadError }) => { if (allTransactions.length) { transactionsCsvGen.generate(allTransactions); } else if (!downloadError) { notification.info({ ns: 'app.wallet.transactions', title: { literal: 'errors.download.title' }, body: { literal: 'errors.download.body' } }); } }); return promiseGetTransactions; } _getTxList() { return waves.node.transactions.list(this.limit); } /** * @private */ _applyTransactionList() { const filter = this.filter; const list = this.txList; const availableTypes = filter.split(',') .map((type) => type.trim()) .reduce((result, type) => { result[type] = true; return result; }, Object.create(null)); if (filter === 'all') { this.transactions = list.slice(); } else { this.transactions = list.filter(({ typeName }) => availableTypes[typeName]); } } /** * @private */ _sendAnalytics() { let actionName; switch (this.filter) { case 'all': actionName = 'Transactions All Show'; break; case 'send,mass-send': actionName = 'Transactions Sent Show'; break; case 'receive,mass-receive,sponsorship-fee': actionName = 'Transactions Received Show'; break; case 'exchange-buy,exchange-sell': actionName = 'Transactions Exchanged Show'; break; case 'lease-in,lease-out,cancel-leasing': actionName = 'Transactions Leased Show'; break; case 'issue,reissue,burn,sponsorship-stop,sponsorship-start': actionName = 'Transactions Issued Show'; break; default: break; } analytics.send({ name: actionName, target: 'ui' }); } /** * @param {ITransaction[]} transactions * @private */ _setTxList(transactions) { this.pending = false; this.txList = transactions; $scope.$digest(); } } return new TransactionsCtrl(); }; controller.$inject = ['user', 'Base', '$scope', 'transactionsCsvGen', 'waves', 'createPoll', 'notification']; angular.module('app.wallet.transactions').controller('TransactionsCtrl', controller); })();
JavaScript
0
@@ -3967,12 +3967,13 @@ ion. -info +error (%7B%0A @@ -4080,32 +4080,29 @@ al: 'errors. -download +empty .title' %7D,%0A @@ -4149,32 +4149,29 @@ al: 'errors. -download +empty .body' %7D%0A
98d36e00fedb14a1d490d3b267f40075f94cf147
Work on Depth Module
src/parser/priest/discipline/modules/azeritetraits/DepthOfTheShadows.js
src/parser/priest/discipline/modules/azeritetraits/DepthOfTheShadows.js
import React from 'react'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import { calculateAzeriteEffects } from 'common/stats'; import { formatNumber, formatPercentage } from 'common/format'; import isAtonement from '../core/isAtonement'; /* refresh */ const DEPTH_OF_THE_SHADOWS_BONUS_MS = 2000; const EVANGELISM_BONUS_MS = 6000; class DepthOfTheShadows extends Analyzer { _bonusFromAtonementDuration = 0; _bonusFromDirectHealBuff = 0; _shadowMendCasts = []; _bonusHealingForSingleDepthStack = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.DEPTH_OF_THE_SHADOWS.id); this._bonusHealingForSingleDepthStack = this.selectedCombatant.traitsBySpellId[SPELLS.DEPTH_OF_THE_SHADOWS.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.DEPTH_OF_THE_SHADOWS.id, rank)[0], 0); this._bonusHealingForSingleDepthStack *= 2; } on_byPlayer_cast(event) { if (event.ability.guid === SPELLS.SHADOW_MEND.id) { event.lowerBound = event.timestamp + SPELLS.SHADOW_MEND.atonementDuration * 1000; event.upperBound = event.timestamp + SPELLS.SHADOW_MEND.atonementDuration * 1000 + DEPTH_OF_THE_SHADOWS_BONUS_MS; this._shadowMendCasts.push(event); } if (event.ability.guid === SPELLS.EVANGELISM_TALENT.id) { this._shadowMendCasts.forEach((cast, castIndex) => { if(event.timestamp < cast.lowerBound || event.timestamp > cast.upperBound) { cast.lowerBound += EVANGELISM_BONUS_MS; } cast.upperBound += EVANGELISM_BONUS_MS; }); } } calculateBonusAtonement(event) { if(!isAtonement(event)) { return; } this._shadowMendCasts.forEach((cast, castIndex) => { if(event.targetID === cast.targetID && event.timestamp > cast.lowerBound && event.timestamp < cast.upperBound) { this._bonusFromAtonementDuration += event.amount; } }); } on_byPlayer_heal(event) { if (event.ability.guid === SPELLS.SHADOW_MEND.id) { let _depthStacks = 0; const depthBuff = this.selectedCombatant.getBuff(SPELLS.DEPTH_OF_THE_SHADOWS_BUFF.id); if(depthBuff) { _depthStacks = depthBuff.stacks; } const bonusHealing = _depthStacks * this._bonusHealingForSingleDepthStack; if(!event.overheal || (event.overheal && event.overheal < bonusHealing)) { this._bonusFromDirectHealBuff += bonusHealing - (event.overheal || 0); } } this.calculateBonusAtonement(event); } statistic() { const fightDuration = this.owner.fightDuration; const total = this._bonusFromAtonementDuration + this._bonusFromDirectHealBuff; const totalPct = this.owner.getPercentageOfTotalHealingDone(total); const bonusFromAtonementPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromAtonementDuration); const bonusFromDirectHealBuffPct = this.owner.getPercentageOfTotalHealingDone(this._bonusFromDirectHealBuff); return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.DEPTH_OF_THE_SHADOWS.id} value={`${formatNumber(total / fightDuration * 1000)} HPS`} tooltip={ `Depth of the Shadow provided <b>${formatPercentage(totalPct)}%</b> healing. <ul> <li><b>${formatPercentage(bonusFromAtonementPct)}%</b> from extended Atonement <li><b>${formatPercentage(bonusFromDirectHealBuffPct)}%</b> from direct shadow mend buff </ul> `} /> ); } } export default DepthOfTheShadows;
JavaScript
0
@@ -358,16 +358,98 @@ nement'; +%0Aimport atonementApplicationSource from '../features/AtonementApplicationSource'; %0A%0A/*%0A r @@ -1061,32 +1061,44 @@ k)%5B0%5D, 0);%0A%0A +console.log( this._bonusHeali @@ -1122,13 +1122,9 @@ tack - *= 2 +) ;%0A @@ -1146,33 +1146,32 @@ r_cast(event) %7B%0A -%0A if (event.ab @@ -1220,322 +1220,131 @@ -event.lowerBound = event.timestamp + SPELLS.SHADOW_MEND.atonementDuration * 1000;%0A event.upperBound = event.timestamp + SPELLS.SHADOW_MEND.atonementDuration * 1000 + DEPTH_OF_THE_SHADOWS_BONUS_MS;%0A this._shadowMendCasts.push(event);%0A %7D%0A%0A if (event.ability.guid === SPELLS.EVANGELISM_TALENT.id) %7B%0A +this._shadowMendCasts.push(event);%0A %7D%0A %7D%0A%0A calculateBonusAtonement(event) %7B%0A%0A if(!isAtonement(event)) %7B return; %7D%0A%0A @@ -1407,36 +1407,14 @@ - if(event.timestamp %3C cast. +const lowe @@ -1424,15 +1424,13 @@ und -%7C%7C even += cas t.ti @@ -1441,55 +1441,78 @@ amp -%3E cast.upperBound) %7B%0A cast.low ++ SPELLS.SHADOW_MEND.atonementDuration * 1000;%0A const upp erBound += E @@ -1511,248 +1511,105 @@ und -+ = -EVANGELISM_BONUS_MS;%0A %7D%0A%0A cast.upperBound += EVANGELISM_BONUS_MS;%0A %7D);%0A %7D%0A %7D%0A%0A calculateBonusAtonement(event) %7B%0A%0A if(!isAtonement(event)) %7B return; %7D%0A%0A this._shadowMendCasts.forEach((cast, castIndex) =%3E %7B%0A +cast.timestamp + SPELLS.SHADOW_MEND.atonementDuration * 1000 + DEPTH_OF_THE_SHADOWS_BONUS_MS;%0A%0A @@ -1667,21 +1667,16 @@ stamp %3E -cast. lowerBou @@ -1699,21 +1699,16 @@ stamp %3C -cast. upperBou @@ -1709,26 +1709,24 @@ perBound) %7B%0A - th @@ -1773,18 +1773,16 @@ amount;%0A - %7D%0A
2b379beaaaefbfe265476f8e3c36d7b41921a957
Add factory navigation
ipojo/webconsole-plugin/src/main/resources/res/ui/instance_detail.js
ipojo/webconsole-plugin/src/main/resources/res/ui/instance_detail.js
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function renderInstanceDetails(data) { $(".statline").html(getInstancesStatLine(data)); createDetail( data.data ); } function getInstancesStatLine(instances) { return instances.count + " instances in total, " + instances.valid_count + " valid instances, " + instances.invalid_count + " invalid instances."; } function createDetail(instance) { console.log("Create details"); var service = "No provided services" var _ = tableBody; // Set the name _.find('td.Vname').html(instance.name); // Set the state _.find('td.Vstate').text(instance.state); // Set the factory _.find('td.Vfactory').html(instance.factory); //TODO Link if (instance.services) { $(tableServiceBody).empty(); for (var s in instance.services) { var service = instance.services[s]; // For each service clone the template var entry = serviceEntryTemplate.clone().appendTo(tableServiceBody).attr('id', 'service-' + service.specification); entry.find('td.name').text(service.specification); entry.find('td.state').text(service.state); if (service.id) { entry.find('td.id').text(service.id); } else { entry.find('td.id').html('<i>not registered</i>'); } if (service.properties) { var list = $('<ul>'); for (var x in service.properties) { list.append($('<li>').append(service.properties[x].name + ' = ' + service.properties[x].value)); } entry.find('td.properties').html(list); } else { entry.find('td.properties').html('<i>not properties</i>'); } } } else { // Hide the table $('services').hide(); _.find('td.Vservices').html("No provided services"); } if (instance.req) { $(tableReqBody).empty(); for (var s in instance.req) { var service = instance.req[s]; console.dir(service); // For each service clone the template var entry = reqEntryTemplate.clone().appendTo(tableReqBody).attr('id', 'req-' + service.id); entry.find('td.name').text(service.specification); if (service.filter) { entry.find('td.filter').text(service.filter); } else { entry.find('td.filter').html('<i>no filter</i>'); } entry.find('td.state').text(service.state); entry.find('td.policy').text(service.policy); entry.find('td.optional').text(service.optional); entry.find('td.aggregate').text(service.aggregate); if (service.matching) { var list = $('<ul>'); for (var x in service.matching) { if (service.matching[x].instance) { var text = service.matching[x].instance + ' [' + service.matching[x].id + ']'; var link = $('<a href=\'' + instances_url + '/' + service.matching[x].instance +'\'>' + text + '</a>'); list.append($('<li>').append(link)); } else { list.append($('<li>').append(service.matching[x].id)); } } entry.find('td.matching').html(list); } else { entry.find('td.matching').html('<i>no matching services</i>'); } if (service.used) { var list = $('<ul>'); for (var x in service.used) { if (service.used[x].instance) { var text = service.used[x].instance + ' [' + service.used[x].id + ']'; var link = $('<a href=\'' + instances_url + '/' + service.used[x].instance +'\'>' + text + '</a>'); list.append($('<li>').append(link)); } else { list.append($('<li>').append(service.used[x].id)); } } entry.find('td.used').html(list); } else { entry.find('td.used').html('<i>no used services</i>'); } } } else { // Hide the table $('reqServices').hide(); _.find('td.VreqServices').html("No required services"); } _.find('pre.architecture_content').text(instance.architecture); } function retrieveDetails() { $.get(pluginRoot + '/instances/' + instance_name + '.json', null, function(data) { renderInstanceDetails(data); }, "json"); } function loadFactoriesData() { window.location = factories_url; } function loadInstancesData() { window.location = instances_url; } function loadHandlersData() { window.location = handlers_url; } var tableBody = false; var tableServiceBody = false; var serviceEntryTemplate = false; var tableReqBody = false; var reqEntryTemplate = false; $(document).ready(function(){ tableBody = $('#plugin_table tbody'); tableServiceBody = $('.services tbody'); serviceEntryTemplate = tableServiceBody.find('tr').clone(); tableReqBody = $('.reqServices tbody'); reqEntryTemplate = tableReqBody.find('tr').clone(); retrieveDetails(); $(".instancesButton").click(loadInstancesData); $(".factoriesButton").click(loadFactoriesData); $(".handlersButton").click(loadHandlersData); var extractMethod = function(node) { var link = node.getElementsByTagName("a"); if ( link && link.length == 1 ) { return link[0].innerHTML; } return node.innerHTML; }; });
JavaScript
0
@@ -1475,38 +1475,97 @@ tml( -instance.factory); //TODO Link +'%3Ca href=%22' + factories_url + '/' + instance.factory + '%22%3E' + instance.factory + '%3C/a%3E'); %0A
126db448107f1b3447193490ebeaa6aae806c4e7
call app chat not chat-sharelatex
app/js/server.js
app/js/server.js
/* eslint-disable no-unused-vars, */ // TODO: This file was created by bulk-decaffeinate. // Fix any style issues and re-enable lint. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ const metrics = require('metrics-sharelatex') metrics.initialize('chat') const logger = require('logger-sharelatex') logger.initialize('chat-sharelatex') const Path = require('path') const express = require('express') const app = express() const server = require('http').createServer(app) const Router = require('./router') app.use(express.bodyParser()) app.use(metrics.http.monitor(logger)) metrics.injectMetricsRoute(app) if (app.get('env') === 'development') { console.log('Development Enviroment') app.use(express.errorHandler({ dumpExceptions: true, showStack: true })) } if (app.get('env') === 'production') { console.log('Production Enviroment') app.use(express.logger()) app.use(express.errorHandler()) } const profiler = require('v8-profiler') app.get('/profile', function(req, res) { const time = parseInt(req.query.time || '1000') profiler.startProfiling('test') return setTimeout(function() { const profile = profiler.stopProfiling('test') return res.json(profile) }, time) }) Router.route(app) module.exports = { server, app }
JavaScript
0.000001
@@ -468,27 +468,16 @@ ze('chat --sharelatex ')%0Aconst
f9d44eb596a9d345fe85a9aed6e1fc711a1bb4ae
fix about window
app/main/menu.js
app/main/menu.js
module.exports = { init, getMenuItem }; const electron = require('electron'); const {shell} = require('electron'); const {BrowserWindow} = require('electron'); const path = require('path'); const openAboutWindow = require('about-window').default; const app = electron.app; let win; let menu; function init() { menu = electron.Menu.buildFromTemplate(getMenuTemplate()); electron.Menu.setApplicationMenu(menu); win = BrowserWindow.getAllWindows()[0]; } function getMenuItem(label) { for (let i = 0; i < menu.items.length; i++) { const menuItem = menu.items[i].submenu.items.find(item => { return item.label === label; }); if (menuItem) { return menuItem; } } } function getMenuTemplate() { const template = [ { label: 'File', submenu: [ { label: 'Homepage', click: () => { win.loadURL(`file://${__dirname}/../index.html`); } }, { label: 'Downloader', click: () => { win.loadURL(`file://${__dirname}/../downloader.html`); } }, { label: 'Viewer', click: () => { win.loadURL(`file://${__dirname}/../viewer.html`); } }, { label: 'Streamer', click: () => { win.loadURL(`file://${__dirname}/../streamer.html`); } } ] }, { label: 'Edit', submenu: [ { role: 'cut' }, { role: 'copy' }, { role: 'paste' } ] }, { label: 'View', submenu: [ { role: 'reload' }, { role: 'forcereload' }, { type: 'separator' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { role: 'window', submenu: [ { role: 'minimize' }, { role: 'close' } ] }, { role: 'help', submenu: [ { label: 'Learn More about Electron', click() { shell.openExternal('http://electron.atom.io'); } }, { label: 'About', click: () => openAboutWindow({ icon_path: path.join(__dirname, '..', 'icon.png'), // eslint-disable-line camelcase bug_report_url: 'https://github.com/willyb321/media_mate/issues', // eslint-disable-line camelcase homepage: 'https://github.com/willyb321/media-mate' }) } ] } ]; if (process.platform === 'darwin') { template.unshift({ label: app.getName(), submenu: [ { role: 'about' }, { type: 'separator' }, { role: 'services', submenu: [] }, { type: 'separator' }, { role: 'hide' }, { role: 'hideothers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' } ] }); // Edit menu. // Window menu. template[3].submenu = [ { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' }, { label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize' }, { label: 'Zoom', role: 'zoom' }, { type: 'separator' }, { label: 'Bring All to Front', role: 'front' } ]; } return template; }
JavaScript
0.000005
@@ -2211,17 +2211,17 @@ 21/media -- +_ mate'%0A%09%09
d55d358491991a1ad599c117eeee5cf90c4143c6
添加接口提示缺少catid bug
client/containers/Project/Interface/InterfaceList/AddInterfaceForm.js
client/containers/Project/Interface/InterfaceList/AddInterfaceForm.js
import React, { Component } from 'react' import PropTypes from 'prop-types' import { Form, Input, Select, Button } from 'antd'; import constants from '../../../../constants/variable.js' import { handlePath } from '../../../../common.js' const HTTP_METHOD = constants.HTTP_METHOD; const HTTP_METHOD_KEYS = Object.keys(HTTP_METHOD); const FormItem = Form.Item; const Option = Select.Option; function hasErrors(fieldsError) { return Object.keys(fieldsError).some(field => fieldsError[field]); } class AddInterfaceForm extends Component { static propTypes = { form: PropTypes.object, onSubmit: PropTypes.func, onCancel: PropTypes.func, catid: PropTypes.number, catdata: PropTypes.array } handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { values.catid = this.props.catid this.props.onSubmit(values) } }); } handlePath = (e) => { let val = e.target.value this.props.form.setFieldsValue({ path: handlePath(val) }) } render() { const { getFieldDecorator, getFieldsError } = this.props.form; const prefixSelector = getFieldDecorator('method', { initialValue: 'GET' })( <Select style={{ width: 75 }}> {HTTP_METHOD_KEYS.map(item => { return <Option key={item} value={item}>{item}</Option> })} </Select> ); const formItemLayout = { labelCol: { xs: { span: 24 }, sm: { span: 6 } }, wrapperCol: { xs: { span: 24 }, sm: { span: 14 } } }; return ( <Form onSubmit={this.handleSubmit}> <FormItem {...formItemLayout} label="接口分类" > {getFieldDecorator('catid', { initialValue: this.props.catid ? this.props.catid + '' : this.props.catdata[0]._id + '' })( <Select> {this.props.catdata.map(item => { return <Option key={item._id} value={item._id+""}>{item.name}</Option> })} </Select> )} </FormItem> <FormItem {...formItemLayout} label="接口名称" > {getFieldDecorator('title', { rules: [{ required: true, message: '清输入接口名称!' }] })( <Input placeholder="接口名称" /> )} </FormItem> <FormItem {...formItemLayout} label="接口路径" > {getFieldDecorator('path', { rules: [{ required: true, message: '清输入接口路径!' }] })( <Input onBlur={this.handlePath} addonBefore={prefixSelector} placeholder="/path" /> )} </FormItem> <br /> <FormItem wrapperCol={{ span: 24, offset: 8 }} > <Button onClick={this.props.onCancel} style={{ marginRight: "10px" }} >取消</Button> <Button type="primary" htmlType="submit" disabled={hasErrors(getFieldsError())} > 提交 </Button> </FormItem> </Form> ); } } export default Form.create()(AddInterfaceForm);
JavaScript
0
@@ -833,48 +833,8 @@ ) %7B%0A - values.catid = this.props.catid%0A
ebc2cc9c4d1a5a78766918ac72211ed53e86909b
Update mathjax
lib/assets/javascripts/require/main.js
lib/assets/javascripts/require/main.js
requirejs.config({ paths: { 'jquery': 'http://code.jquery.com/jquery-1.11.0.min.js', 'mathjax': https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' } });
JavaScript
0.000001
@@ -99,16 +99,17 @@ thjax': +' https://
a8fd7f0d4a3b7cd684c65fddb44a2fa381a30ad2
update biul script
docs/scripts/gh-pages-build.js
docs/scripts/gh-pages-build.js
const fs = require('fs') const path = require('path') const { execSync } = require('child_process') const usage = '\nbuild <vn.n.n[-pre[.n]]> | <HEAD> [-p]\n' const versionsFile = path.resolve(__dirname, '../public/versions.json') const args = process.argv if (args.length < 3) { console.log(usage, '\n') process.exit() } const version = args[2] const versions = JSON.parse(fs.readFileSync(path.resolve(__dirname, versionsFile), 'utf8')) const versionIsHEAD = version === 'HEAD' const useForcePush = args[3] === '-p' const versionNumber = versionIsHEAD ? ( `v${JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')).version}` ) : version function execSyncWithLog(command) { console.log(command) try { execSync(command, { stdio: 'inherit' }) } catch (error) { console.error(error.output[1]) process.exit(error.status) } } function saveVersionsFile() { if (!version.includes(versionNumber)) { versions.push(versionNumber) versions.sort() fs.writeFileSync(versionsFile, JSON.stringify(versions, null, 2), 'utf8') execSyncWithLog(`git add ${versionsFile} && git commit -m "add ${versionNumber} to versions file"`) } } function savePublicVersionsFile() { const publicVersionsFile = path.resolve(__dirname, '../../versions.json') if (fs.existsSync(publicVersionsFile)) { const publicVersions = JSON.parse(fs.readFileSync(publicVersionsFile, 'utf8')) if (!publicVersions.includes(versionNumber)) { publicVersions.push(versionNumber) publicVersions.sort() } fs.writeFileSync(publicVersionsFile, JSON.stringify(publicVersions, null, 2), 'utf8') } else { fs.writeFileSync(publicVersionsFile, JSON.stringify(versions, null, 2), 'utf8') } } function buildDocs() { process.chdir(__dirname) execSyncWithLog('git checkout gh-pages') execSyncWithLog('git reset --hard HEAD~1') if (versionIsHEAD) { execSyncWithLog('git checkout --detach master') } else { execSyncWithLog(`git checkout tags/${version}`) } execSyncWithLog('test -d \"./build\" && rm -r \"./build\" || exit 0') execSyncWithLog('cd ../../ && npm install && cd docs && npm run build') execSyncWithLog('git checkout gh-pages') execSyncWithLog(`mv ../build ../../${versionNumber}`) if (versionIsHEAD) { execSyncWithLog(`echo "./${versionNumber}" > ../../release`) } savePublicVersionsFile() if (versionIsHEAD) { execSyncWithLog('git commit --amend --no-edit') } else { execSyncWithLog(`git add ../../ && git commit -m '${version}'`) } execSyncWithLog(`git push${useForcePush ? ' -f' : ''}`) } saveVersionsFile() buildDocs()
JavaScript
0
@@ -2319,17 +2319,16 @@ g(%60echo -%22 ./$%7Bvers @@ -2337,17 +2337,16 @@ nNumber%7D -%22 %3E ../.. @@ -2392,96 +2392,8 @@ ()%0A%0A - if (versionIsHEAD) %7B%0A execSyncWithLog('git commit --amend --no-edit')%0A %7D else %7B%0A ex @@ -2440,16 +2440,23 @@ mit -m ' +Update $%7Bversio @@ -2458,22 +2458,23 @@ ersion%7D' -%60)%0A %7D + Docs%60) %0A%0A exec
332244866ccfcf9b9d1f93b0f058b692809365f3
Revert button
lib/controllers/conflict-controller.js
lib/controllers/conflict-controller.js
import React from 'react'; import Decoration from '../views/decoration'; import Octicon from '../views/octicon'; export default class ConflictController extends React.Component { static propTypes = { editor: React.PropTypes.object.isRequired, conflict: React.PropTypes.object.isRequired, resolveAsSequence: React.PropTypes.func, }; static defaultProps = { resolveAsSequence: sources => {}, } constructor(props, context) { super(props, context); this.state = { chosenSide: this.props.conflict.getChosenSide(), } } resolveAsSequence(sources) { this.props.resolveAsSequence(sources); this.setState({ chosenSide: this.props.conflict.getChosenSide(), }); } render() { if (!this.state.chosenSide) { return ( <div> {this.renderSide(this.props.conflict.ours)} {this.props.conflict.base ? this.renderSide(this.props.conflict.base) : null} <Decoration key={this.props.conflict.separator.marker.id} editor={this.props.editor} marker={this.props.conflict.separator.marker} type="line" className="github-ConflictSeparator" /> {this.renderSide(this.props.conflict.theirs)} </div> ); } else { return ( <Decoration editor={this.props.editor} marker={this.state.chosenSide.getMarker()} type="line" className="github-ResolvedLines" /> ) } } renderSide(side) { const source = side.getSource(); return ( <div> <Decoration key={side.banner.marker.id} editor={this.props.editor} marker={side.getBannerMarker()} type="line" className={side.getBannerCSSClass()} /> {side.isBannerModified() || <Decoration key={'banner-modified-' + side.banner.marker.id} editor={this.props.editor} marker={side.getBannerMarker()} type="line" className="github-ConflictUnmodifiedBanner" /> } <Decoration key={side.marker.id} editor={this.props.editor} marker={side.getMarker()} type="line" className={side.getLineCSSClass()} /> <Decoration key={'block-' + side.marker.id} editor={this.props.editor} marker={side.getBlockMarker()} type="block" position={side.getBlockPosition()}> <div className={side.getBlockCSSClasses()}> <span className="github-ResolutionControls"> <button className="btn btn-sm inline-block" onClick={() => this.resolveAsSequence([source])}> Use me </button> <Octicon icon="ellipses" className="inline-block" /> </span> <span className="github-SideDescription">{source.toUIString()}</span> </div> </Decoration> </div> ); } }
JavaScript
0.000001
@@ -717,24 +717,138 @@ %7D);%0A %7D%0A%0A + revert(side) %7B%0A side.isModified() && side.revert();%0A side.isBannerModified() && side.revertBanner();%0A %7D%0A%0A render() %7B @@ -2908,24 +2908,251 @@ %3C/button%3E%0A + %7B(side.isModified() %7C%7C side.isBannerModified()) &&%0A %3Cbutton className=%22btn btn-sm inline-block%22 onClick=%7B() =%3E this.revert(side)%7D%3E%0A Revert%0A %3C/button%3E%0A %7D%0A
093d8d0332b73fedebfdfca17de973ac11e1b55e
Properly turn promises into Results
src/Native/Promise.js
src/Native/Promise.js
Elm.Native.Promise = {}; Elm.Native.Promise.make = function(localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.Promise = localRuntime.Native.Promise || {}; if (localRuntime.Native.Promise.values) { return localRuntime.Native.Promise.values; } var Result = Elm.Result.make(localRuntime); var Signal = Elm.Native.Signal.make(localRuntime); var Utils = Elm.Native.Utils.make(localRuntime); // CONSTRUCTORS function succeed(value) { return { tag: 'Succeed', value: value }; } function fail(error) { return { tag: 'Fail', value: error }; } function asyncFunction(func) { return { tag: 'Async', asyncFunction: func }; } function andThen(promise, callback) { return { tag: 'AndThen', promise: promise, callback: callback }; } function catch_(promise, callback) { return { tag: 'Catch', promise: promise, callback: callback }; } // RUNNER function runOne(promise) { runPromise({ promise: promise }, function() {}); } function runStream(name, stream, notify) { var workQueue = []; function onComplete() { var result = workQueue.shift(); setTimeout(function() { notify(result); if (workQueue.length > 0) { runPromise(workQueue[0], onComplete); } }, 0); } function register(promise) { var root = { promise: promise }; workQueue.push(root); if (workQueue.length === 1) { runPromise(root, onComplete); } } Signal.output('loopback-' + name + '-promises', register, stream); } function mark(status, promise) { return { status: status, promise: promise }; } function runPromise(root, onComplete) { var result = mark('runnable', root.promise); while (result.status === 'runnable') { result = stepPromise(onComplete, root, result.promise); } if (result.status === 'done') { onComplete(); } if (result.status === 'blocked') { root.promise = result.promise; } } function stepPromise(onComplete, root, promise) { var tag = promise.tag; if (tag === 'Succeed' || tag === 'Fail') { return mark('done', promise); } if (tag === 'Async') { var placeHolder = {}; var couldBeSync = true; var wasSync = false; promise.asyncFunction(function(result) { placeHolder.tag = result.tag; placeHolder.value = result.value; if (couldBeSync) { wasSync = true; } else { runPromise(root, onComplete); } }); couldBeSync = false; return mark(wasSync ? 'done' : 'blocked', placeHolder); } if (tag === 'AndThen' || tag === 'Catch') { var result = mark('runnable', promise.promise); while (result.status === 'runnable') { result = stepPromise(onComplete, root, result.promise); } if (result.status === 'done') { var activePromise = result.promise; var activeTag = activePromise.tag; var succeedChain = activeTag === 'Succeed' && tag === 'AndThen'; var failChain = activeTag === 'Fail' && tag === 'Catch'; return (succeedChain || failChain) ? mark('runnable', promise.callback(activePromise.value)) : mark('runnable', activePromise); } if (result.status === 'blocked') { return mark('blocked', { tag: tag, promise: result.promise, callback: promise.callback }); } } } // THREADS function sleep(time) { return asyncFunction(function(callback) { setTimeout(function() { callback(succeed(Utils.Tuple0)); }, time); }); } function spawn(promise) { return asyncFunction(function(callback) { var id = setTimeout(function() { runOne(promise); }, 0); callback(succeed(id)); }); } return localRuntime.Native.Promise.values = { succeed: succeed, fail: fail, asyncFunction: asyncFunction, andThen: F2(andThen), catch_: F2(catch_), runStream: runStream, runOne: runOne, spawn: spawn, sleep: sleep }; };
JavaScript
0.999312
@@ -1131,33 +1131,38 @@ te()%0A%09%09%7B%0A%09%09%09var -r +queueR esult = workQueu @@ -1172,16 +1172,161 @@ hift();%0A +%09%09%09var promise = queueResult.promise;%0A%09%09%09var result = promise.tag === 'Succeed'%0A%09%09%09%09? Result.Ok(promise.value)%0A%09%09%09%09: Result.Err(promise.value);%0A%0A %09%09%09setTi @@ -2029,16 +2029,50 @@ e')%0A%09%09%7B%0A +%09%09%09root.promise = result.promise;%0A %09%09%09onCom
b9413528522481dcb75b9450ab4045b37334b6ec
Update form_demo.js
docs/v1/static/js/form_demo.js
docs/v1/static/js/form_demo.js
/*global $, window, goinstant, document, getOrSetRoomCookie, jQuery */ 'use strict'; var console=console||{"error":function(){}}; function connect(options) { var connectUrl = 'https://goinstant.net/goinstant-services/docs'; var connection = new goinstant.Connection(connectUrl, options); connection.connect(function(err, connection) { if (err) { return console.error('could not connect:', err); } var roomName = getOrSetRoomCookie("form"); var currentRoom = connection.room(roomName); var Form = goinstant.widgets.Form; currentRoom.join(function(err) { if (err) { return console.error('Error joining room:', err); } var color = options.guestId == "1" ? "#f00" : "#0f0"; var userKey = currentRoom.self(); userKey.key('displayName').set('Guest ' + options.guestId, function(err) { if (err) { return console.error("Error setting userId", err); } }); userKey.key('avatarColor').set(color, function(err) { if (err) { return console.error("error setting avatarColor", err); } // The user now appears red in the user-list, etc. }); var formKey = currentRoom.key('example-form-key'); var form = new Form({ key: formKey, el: document.getElementById('form-id'), room: currentRoom }); form.initialize(function(err) { if (err) { return console.error('Could not initialize widget:', err); } // Your form should now be initialized! }); }); }); } $(window).ready(function() { // window.options comes from an inline script tag in each iframe. connect(window.options); });
JavaScript
0
@@ -1111,67 +1111,8 @@ %7D%0A - // The user now appears red in the user-list, etc.%0A
3ea310a6dd225b32c93f84858bfd775072a5a82f
Fix ESLint error for strings.
assets/js/components/wp-dashboard/WPDashboardApp.js
assets/js/components/wp-dashboard/WPDashboardApp.js
/** * WPDashboardApp component. * * Site Kit by Google, Copyright 2021 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import { useIntersection } from 'react-use'; /** * WordPress dependencies */ import { useEffect, useState, useRef } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import Link from '../Link'; import WPDashboardWidgets from './WPDashboardWidgets'; import InViewProvider from '../../components/InViewProvider'; import { CORE_SITE } from '../../googlesitekit/datastore/site/constants'; const { useSelect } = Data; const WPDashboardApp = () => { const trackingRef = useRef(); const intersectionEntry = useIntersection( trackingRef, { threshold: 0, // Trigger "in-view" as soon as one pixel is visible. } ); const dashboardURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-dashboard' ) ); const [ inViewState, setInViewState ] = useState( { key: `WPDashboardApp`, value: !! intersectionEntry?.intersectionRatio, } ); useEffect( () => { setInViewState( { key: `WPDashboardApp`, value: !! intersectionEntry?.intersectionRatio, } ); }, [ intersectionEntry ] ); if ( dashboardURL === undefined ) { return <div ref={ trackingRef } />; } if ( ! dashboardURL ) { return null; } return ( <InViewProvider value={ inViewState }> <div className="googlesitekit-wp-dashboard" ref={ trackingRef }> <div className="googlesitekit-wp-dashboard__cta"> <Link className="googlesitekit-wp-dashboard__cta-link" href={ dashboardURL } > { __( 'Visit your Site Kit Dashboard', 'google-site-kit' ) } </Link> </div> <WPDashboardWidgets /> </div> </InViewProvider> ); }; export default WPDashboardApp;
JavaScript
0.000001
@@ -1549,25 +1549,25 @@ e( %7B%0A%09%09key: -%60 +' WPDashboardA @@ -1564,25 +1564,25 @@ DashboardApp -%60 +' ,%0A%09%09value: ! @@ -1676,17 +1676,17 @@ %09%09%09key: -%60 +' WPDashbo @@ -1695,9 +1695,9 @@ dApp -%60 +' ,%0A%09%09
bad828743f495fa75d8e588c761c4f1bb2627ff2
Fix this stupid lib ...
assets/lib/ng-infinite-scroll/ng-infinite-scroll.js
assets/lib/ng-infinite-scroll/ng-infinite-scroll.js
/* ng-infinite-scroll - v1.0.0 - 2013-02-23 */ var mod; mod = angular.module('infinite-scroll', []); mod.directive('infiniteScroll', [ '$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) { return { link: function(scope, elem, attrs) { var checkWhenEnabled, handler, scrollDistance, scrollEnabled; $window = angular.element($window); scrollDistance = 0; if (attrs.infiniteScrollDistance != null) { scope.$watch(attrs.infiniteScrollDistance, function(value) { return scrollDistance = parseInt(value, 10); }); } scrollEnabled = true; checkWhenEnabled = false; if (attrs.infiniteScrollDisabled != null) { scope.$watch(attrs.infiniteScrollDisabled, function(value) { scrollEnabled = !value; if (scrollEnabled && checkWhenEnabled) { checkWhenEnabled = false; return handler(); } }); } handler = function() { var elementBottom, remaining, shouldScroll, windowBottom; windowBottom = $window.height() + $window.scrollTop(); elementBottom = elem.offset().top + elem.height(); remaining = elementBottom - windowBottom; shouldScroll = remaining <= $window.height() * scrollDistance; if (shouldScroll && scrollEnabled) { if ($rootScope.$$phase) { return scope.$eval(attrs.infiniteScroll); } else { return scope.$apply(attrs.infiniteScroll); } } else if (shouldScroll) { return checkWhenEnabled = true; } }; $window.on('scroll', handler); scope.$on('$destroy', function() { return $window.off('scroll', handler); }); return $timeout((function() { if (attrs.infiniteScrollImmediateCheck) { if (scope.$eval(attrs.infiniteScrollImmediateCheck)) { return handler(); } } else { return handler(); } }), 0); } }; } ]);
JavaScript
0.000034
@@ -149,19 +149,8 @@ pe', - '$window', '$t @@ -182,17 +182,8 @@ ope, - $window, $ti @@ -243,24 +243,200 @@ m, attrs) %7B%0A + var scrollElemSel = attrs.scrollElemSel %7C%7C 'body'%0A , scrollElem = document.querySelector(scrollElemSel)%0A , $scrollElem = angular.element(scrollElem)%0A%0A var @@ -497,52 +497,8 @@ ed;%0A - $window = angular.element($window);%0A @@ -1239,34 +1239,44 @@ m = -$window.h +scrollElem.clientH eight -() + -$window +scrollElem .scr @@ -1281,18 +1281,16 @@ crollTop -() ;%0A @@ -1317,19 +1317,19 @@ elem +%5B0%5D .offset -().t +T op + @@ -1333,25 +1333,32 @@ p + elem -.h +%5B0%5D.clientH eight -() ;%0A @@ -1445,24 +1445,31 @@ %3C= -$window.h +scrollElem.clientH eight -() * s @@ -1829,22 +1829,26 @@ $ -window +scrollElem .on('scr @@ -1845,39 +1845,56 @@ em.on('scroll', +_.throttle( handler +, 200) );%0A scope @@ -1941,22 +1941,26 @@ return $ -window +scrollElem .off('sc
b7df9b9ec7db6f6028bb5ee735b63f21d3d369ca
Add SSL to API endpoint (api-adresse.data.gouv.fr)
lib/geocoder/opendatafrancegeocoder.js
lib/geocoder/opendatafrancegeocoder.js
var util = require('util'), AbstractGeocoder = require('./abstractgeocoder'); /** * Constructor */ var OpendataFranceGeocoder = function OpendataFranceGeocoder(httpAdapter, options) { this.options = ['language','email','apiKey']; OpendataFranceGeocoder.super_.call(this, httpAdapter, options); }; util.inherits(OpendataFranceGeocoder, AbstractGeocoder); OpendataFranceGeocoder.prototype._endpoint = 'http://api-adresse.data.gouv.fr/search'; OpendataFranceGeocoder.prototype._endpoint_reverse = 'http://api-adresse.data.gouv.fr/reverse'; /** * Geocode * @param <string|object> value Value to geocode (Address or parameters, as specified at https://opendatafrance/api/) * @param <function> callback Callback method */ OpendataFranceGeocoder.prototype._geocode = function(value, callback) { var _this = this; var params = this._getCommonParams(); if (typeof value == 'string') { params.q = value; } else { if (value.address) { params.q = value.address; } if (value.lat && value.lon) { params.lat = value.lat; params.lon = value.lon; } if (value.zipcode) { params.postcode = value.zipcode; } if (value.type) { params.type = value.type; } if (value.citycode) { params.citycode = value.citycode; } } this._forceParams(params); this.httpAdapter.get(this._endpoint, params, function(err, result) { if (err) { return callback(err); } else { if (result.error) { return callback(new Error(result.error)); } var results = []; if (result.features) { for (var i = 0; i < result.features.length; i++) { results.push(_this._formatResult(result.features[i])); } } results.raw = result; callback(false, results); } }); }; OpendataFranceGeocoder.prototype._formatResult = function(result) { var latitude = result.geometry.coordinates[1]; if (latitude) { latitude = parseFloat(latitude); } var longitude = result.geometry.coordinates[0]; if (longitude) { longitude = parseFloat(longitude); } var properties = result.properties; var formatedResult = { latitude : latitude, longitude : longitude, state : properties.context, city : properties.city, zipcode : properties.postcode, citycode : properties.citycode, countryCode : 'FR', country : 'France', type: properties.type, id: properties.id }; if (properties.type === 'housenumber') { formatedResult.streetName = properties.street; formatedResult.streetNumber = properties.housenumber; } else if (properties.type === 'street') { formatedResult.streetName = properties.name; } else if (properties.type === 'city') { formatedResult.population = properties.population; formatedResult.adm_weight = properties.adm_weight; } else if (properties.type === 'village') { formatedResult.population = properties.population; } else if (properties.type === 'locality') { formatedResult.streetName = properties.name; } return formatedResult; }; /** * Reverse geocoding * @param {lat:<number>,lon:<number>, ...} lat: Latitude, lon: Longitude, ... see https://wiki.openstreetmap.org/wiki/Nominatim#Parameters_2 * @param <function> callback Callback method */ OpendataFranceGeocoder.prototype._reverse = function(query, callback) { var _this = this; var params = this._getCommonParams(); for (var k in query) { var v = query[k]; params[k] = v; } this._forceParams(params); this.httpAdapter.get(this._endpoint_reverse , params, function(err, result) { if (err) { return callback(err); } else { if(result.error) { return callback(new Error(result.error)); } var results = []; if (result.features) { for (var i = 0; i < result.features.length; i++) { results.push(_this._formatResult(result.features[i])); } } results.raw = result; callback(false, results); } }); }; /** * Prepare common params * * @return <Object> common params */ OpendataFranceGeocoder.prototype._getCommonParams = function(){ var params = {}; for (var k in this.options) { var v = this.options[k]; if (!v) { continue; } if (k === 'language') { k = 'accept-language'; } params[k] = v; } return params; }; OpendataFranceGeocoder.prototype._forceParams = function(params){ params.limit = 20; }; module.exports = OpendataFranceGeocoder;
JavaScript
0.000001
@@ -419,32 +419,33 @@ endpoint = 'http +s ://api-adresse.d @@ -524,16 +524,17 @@ = 'http +s ://api-a
a90706e30579586caa91b57fe476bcf69ccf6f32
remove updated at in entity attribute
lib/modeling/entity_attribute_model.js
lib/modeling/entity_attribute_model.js
/** * @function entityAttributeModel */ 'use strict' const { normalizeAttributeValues } = require('../helpers/normalizer') const co = require('co') const { STRING, INTEGER } = require('sequelize') const { typeOf } = require('clay-serial') const { serialize, deserialize } = require('../helpers/serializer') const { ENTITY_SUFFIX, ID_SUFFIX, ENTITY_ATTRIBUTE_SUFFIX } = require('../constants/model_keywords') /** @lends entityAttributeModel */ function entityAttributeModel ({ db, prefix = '' }) { const modelName = prefix + ENTITY_ATTRIBUTE_SUFFIX const entityModelIdName = prefix + ENTITY_SUFFIX + ID_SUFFIX const EntityAttribute = db.define(modelName, { name: { comment: 'Name of attribute', type: STRING, allowNull: false }, type: { comment: 'Type of attribute', type: STRING, defaultValue: 'string', allowNull: false }, value: { comment: 'Value of attribute', type: STRING, allowNull: true }, [entityModelIdName]: { type: INTEGER, allowNull: false } }, { freezeTableName: true, createdAt: false, indexes: [ { unique: true, fields: [ entityModelIdName, 'name' ] } ], instanceMethods: { toValue () { const s = this const { value, type } = s return deserialize(value, type) } }, classMethods: { setAttributeValues (entity, values) { const { id: EntityId } = entity return co(function * () { const tasks = [] const attributeValues = Object.keys(values) .filter((name) => !/^\$\$/.test(name)) .reduce((attributeValues, name) => Object.assign( attributeValues, normalizeAttributeValues(name, values[ name ]) ), {}) const names = Object.keys(attributeValues) const knownEntityAttributes = yield EntityAttribute.findAll({ attributes: [ 'id', 'name', 'type', 'value' ], where: { [entityModelIdName]: EntityId, name: { $in: names } } }) const knownNames = knownEntityAttributes.map(({ name }) => name) const unknownNames = names.filter((name) => !knownNames.includes(name)) tasks.push( EntityAttribute.bulkCreate( unknownNames.map((name) => { const value = attributeValues[ name ] const type = typeOf(value) return { [entityModelIdName]: EntityId, name, type, value: serialize(value, type) } }) ) ) for (let instance of knownEntityAttributes) { const { name } = instance const type = typeOf(attributeValues[ name ]) const value = serialize(attributeValues[ name ], type) const skip = (instance.value === value) && (instance.type === type) if (skip) { continue } tasks.push( instance.update({ type, value }) ) } yield Promise.all(tasks) }) } } }) return EntityAttribute } module.exports = entityAttributeModel
JavaScript
0
@@ -1117,16 +1117,38 @@ false,%0A + updatedAt: false,%0A inde
8e34fa3d34deb35d8c25f5ce33ef7bf864678971
Check before calling is method
lib/rules/empty-line-between-blocks.js
lib/rules/empty-line-between-blocks.js
'use strict'; var helpers = require('../helpers'); var counter, syntax; var findNearestReturnSCSS = function (parent, i) { var previous, doublePrevious, space; if (parent.content[i - 1]) { previous = parent.content[i - 1]; if (i >= 2) { doublePrevious = parent.content[i - 2]; // First check to see that the previous line is not a new line as if it is // we don't want to recursively run the function again if (!helpers.isEmptyLine(previous.content)) { if (doublePrevious.type.indexOf('Comment') !== -1) { return findNearestReturnSCSS(parent, i - 1); } } } if (i >= 1) { if (previous.type.indexOf('Comment') !== -1) { return findNearestReturnSCSS(parent, i - 1); } if (previous.type === 'space') { space = helpers.isEmptyLine(previous.content); // If there's not a new line and it's the first within the block, ignore if (!space && (i - 1 === 0)) { return false; } return { 'space': space, 'previous': previous }; } } } return false; }; var findNearestReturnSass = function (parent, i) { var previous; if (parent.content[i - 1]) { previous = parent.content[i - 1]; if (counter === 2) { return { space: true, previous: previous }; } if (previous.is('space') || previous.is('declarationDelimiter')) { if (helpers.hasEOL(previous.content)) { counter++; } return findNearestReturnSass(parent, i - 1); } // If ruleset, we must reset the parent to be the previous node and // loop through that else if (previous.is('ruleset') || previous.is('include')) { var previousNode = previous.content[previous.content.length - 1]; // Set the i parameter for findNearestReturn to be the length of the // content array in order to get the last one return findNearestReturnSass(previousNode, previousNode.content.length); } else { counter = 0; if (previous.type.indexOf('Comment') !== -1) { // If it's the first line if (previous.start.line === 1) { return { space: true, previous: previous }; } return findNearestReturnSass(parent, i - 1); } } } return { space: false, previous: previous }; }; module.exports = { 'name': 'empty-line-between-blocks', 'defaults': { 'include': true, 'allow-single-line-rulesets': true }, 'detect': function (ast, parser) { var result = []; syntax = ast.syntax; ast.traverseByType('ruleset', function (node, j, p) { var space; if ((node.start.line === node.end.line) && parser.options['allow-single-line-rulesets']) { return false; } if (syntax === 'scss') { space = findNearestReturnSCSS(p, j); if (space) { if (parser.options.include && !space.space && j !== 1) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': space.previous.end.line, 'column': 1, 'message': 'Space expected between blocks', 'severity': parser.severity }); } else if (!parser.options.include && space.space) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': space.previous.end.line, 'column': 1, 'message': 'Space not allowed between blocks', 'severity': parser.severity }); } } } else if (syntax === 'sass') { // Reset the counter for each ruleset counter = 0; if (node.is('ruleset')) { node.forEach('block', function (block, i, parent) { var previous; // Capture the previous node if (parent.content[i - 1]) { previous = parent.content[i - 1]; } else { // Else set the block to act as the previous node previous = block; } // If it's a new line, lets go back up to the selector if (previous.is('space') && helpers.hasEOL(previous.content)) { space = findNearestReturnSass(p, j); } }); } if (space && space.previous) { if (space.previous.start.line !== 1) { if (parser.options.include && !space.space) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': space.previous.end.line + 1, 'column': 1, 'message': 'Space expected between blocks', 'severity': parser.severity }); } else if (!parser.options.include && space.space) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': space.previous.end.line + 1, 'column': 1, 'message': 'Space not allowed between blocks', 'severity': parser.severity }); } } } } return true; }); return result; } };
JavaScript
0.000003
@@ -1218,32 +1218,55 @@ revious;%0A%0A if ( +!parent.is('ident') && parent.content%5Bi
f3720f0229ec0ba719e0d63f161612407d16f694
put -> get
src/IO/Girder/HpcCloudEndpoints/taskflows.js
src/IO/Girder/HpcCloudEndpoints/taskflows.js
export default function ({ client, filterQuery, mustContain, busy }) { return { // POST /taskflows Create the taskflow createTaskflow(taskFlowClass) { return busy(client._.post('/taskflows', { taskFlowClass, })); }, // GET /taskflows/{id} Get a taskflow getTaskflow(id, path) { if (path) { return busy(client._.get(`/taskflows/${id}?path=${path}`)); } return busy(client._.get(`/taskflows/${id}`)); }, // PATCH /taskflows/{id} Update the taskflow updateTaskflow(id, params) { return busy(client._.patch(`/taskflows/${id}`, params)); }, // DELETE /taskflows/{id} Delete the taskflow deleteTaskflow(id) { return busy(client._.delete(`/taskflows/${id}`)); }, // GET /taskflows/{id}/log Get log entries for taskflow getTaskflowLog(id, offset = 0) { if (offset !== 0) { return busy(client._.put(`/taskflows/${id}/log?offset=${offset}`)); } return busy(client._.put(`/taskflows/${id}/log`)); }, // PUT /taskflows/{id}/start Start the taskflow startTaskflow(id, cluster) { return busy(client._.put(`/taskflows/${id}/start`, cluster)); }, // GET /taskflows/{id}/status Get the taskflow status getTaskflowStatus(id) { return busy(client._.get(`/taskflows/${id}/status`)); }, // GET /taskflows/{id}/tasks Get all the tasks associated with this taskflow getTaskflowTasks(id) { return busy(client._.get(`/taskflows/${id}/tasks`)); }, // POST /taskflows/{id}/tasks Create a new task associated with this flow createNewTaskForTaskflow(id, params) { return busy(client._.post(`/taskflows/${id}/tasks`, params)); }, // PUT /taskflows/{id}/terminate Terminate the taskflow endTaskflow(id) { return busy(client._.put(`/taskflows/${id}/terminate`)); }, }; }
JavaScript
0
@@ -906,34 +906,34 @@ n busy(client._. -pu +ge t(%60/taskflows/$%7B @@ -988,34 +988,34 @@ n busy(client._. -pu +ge t(%60/taskflows/$%7B
b56332e350409eb9b35cf41830576e1896c089a7
Fix for DM message not triggering without greeting
src/SlackInterface.js
src/SlackInterface.js
//TEST /** * Example for creating and working with the Slack RTM API. */ /* eslint no-console:0 */ /******************************************************************************* * Globals */ const RtmClient = require('@slack/client').RtmClient; const MemoryDataStore = require('@slack/client').MemoryDataStore; const RTM_EVENTS = require('@slack/client').RTM_EVENTS; const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS; const AWS = require('./AWS_API.js'); const GIT = require('./gitHubModule.js'); const token = process.env.SLACK_API_TOKEN || ''; const DEBUG = process.env.DEBUG || false; AWS.DEBUG = DEBUG; var rtm; var problemMessage = 'Looks like there was a problem processing your request.'; var activeConv = []; /*Jarvis Include*/ var mainController = require('./mainController'); /******************************************************************************* * Functions */ var handleRtmMessage = function(message) { if (DEBUG) { console.log('Message:', message) } var text = message.text; var firstChar = message.channel.substring(0, 1); var initCommands = /^(hey jarvis,? ?)|^(jarvis,? ?)/i; //DO NOT ADD GLOBAL FLAG //Message is from a channel or group if (firstChar === 'C' | firstChar === 'G') { if (initCommands.test(text)){ text = text.replace(initCommands, ""); if(text.length > 0){ if (DEBUG) { console.log("Greeting + Command")} message.text = text; parseCommand(message); }else{ if (DEBUG) { console.log("Greeting w/o Command")} var temp = new Conversation(message.user, message.channel); activeConv.push(temp); rtm.sendMessage("yes?", message.channel); } } else{ //Check Active Conversations for (var i = 0, len = activeConv.length; i < len; i++){ if(activeConv[i].user == message.user && activeConv[i].channel == message.channel){ if (DEBUG) { console.log("Conversation"); rtm.sendMessage("processing command .. conversation continued", message.channel);} parseCommand(message); activeConv.splice(i,1); break; } } } } //Direct Message to Jarvis else if (firstChar === 'D') { if (initCommands.test(text)){ text = text.replace(initCommands, ""); if(text.length > 0){ if (DEBUG) { console.log("DM Greeting + Command")} rtm.sendMessage("No need for initial commands in Direct Messages.", message.channel); message.text = text; parseCommand(message); }else{ if (DEBUG) { console.log("DM Greeting w/o Command")} rtm.sendMessage("No need to include initial commands in Direct Messages. Please enter command.", message.channel); } } } } var parseCommand = function(message) { var text = message.text; if (DEBUG) { console.log("Parsing Command: "+text)} if (keyMessage(text, 'aws ')) { text = text.substring('aws '.length, text.length); if (keyMessage(text, 'check ec2 ')) { text = text.substring('check ec2 '.length, text.length); if (keyMessage(text, 'instance ')) { handleMessagePromise(AWS.checkEC2Instance(text.substring('instance '.length, text.length)), message); } else { handleMessagePromise(AWS.checkEC2(), message); } } else if (keyMessage(text, 'check number of instances ')) { handleMessagePromise(AWS.checkNumInstances(), message); } else { rtm.sendMessage(rtm.dataStore.getUserById(message.user).name+" I'm sorry, this isn't an AWS command I'm familiar with.", message.channel); } } else if (keyMessage(text, 'slack ')) { text = text.substring('slack '.length, text.length); var userRegex = /<@([A-Z|1-9]+.)>/g; var channelRegex = /<?#([A-Z0-9]+)(\|\w+>)?/g; if (userRegex.test(text)) { var user = rtm.dataStore.getUserById(text.replace(userRegex, '$1')); rtm.sendMessage("User lookup: "+user.real_name/*+" "+JSON.stringify(user)*/, message.channel); } else if (channelRegex.test(text)) { var key = text.replace(channelRegex, '$1'); var channel = rtm.dataStore.getChannelGroupOrDMById(key); rtm.sendMessage("Channel lookup: "+key/*+" "+JSON.stringify(channel)*/, message.channel); } else if (keyMessage(text, 'debug ')) { rtm.sendMessage("Debug: "+JSON.stringify(message), message.channel); } else { rtm.sendMessage("Slack command DNE", message.channel); } } else if (keyMessage(text, 'git ')) { rtm.sendMessage("Git commands: coming soon", message.channel); } else { rtm.sendMessage("I'm sorry, this isn't a command I'm familiar with.", message.channel); } } /******************************************************************************* * Helper functions */ function keyMessage(text, key) { var temptext = text + ' '; if (temptext.length >= key.length && temptext.substring(0, key.length).toLowerCase() === key) { return true; } return false; } function handleMessagePromise(promise, message) { promise.then(function (resp) { rtm.sendMessage(resp, message.channel); }, function (err) { rtm.sendMessage(problemMessage, message.channel); console.log(err); }); } function Conversation(user, channel){ this.user = user; this.channel = channel; this.active = false; } /******************************************************************************* * Test stuff */ /* Sample inputs: aws describe ec2 instance i-0a681657adec3b3ee aws describe ec2 */ var mockRTM = function() { var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); process.stdout.write("Please input your test message text: "); rl.on('line', function (line) { var message = { 'text': line, 'channel': 3 }; // mocking rtm rtm = {}; rtm.sendMessage = function(message, channel) { console.log('----------Response message----------'); console.log('Text: ' + message); console.log('Channel: ' + channel); } // run the test handleRtmMessage(message); }); } /******************************************************************************* * main() */ var main = function() { rtm = new RtmClient(token); rtm.start(); rtm.on(RTM_EVENTS.MESSAGE, handleRtmMessage); rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function handleRTMAuthenticated() { console.log('Jarvis is Online.'); }); rtm.on(RTM_EVENTS.REACTION_ADDED, function handleRtmReactionAdded(reaction) { if (DEBUG) { console.log('Reaction added:', reaction)} rtm.sendMessage("Thanks "+rtm.dataStore.getUserById(reaction.user).name,reaction.item.channel); }); rtm.on(RTM_EVENTS.REACTION_REMOVED, function handleRtmReactionRemoved(reaction) { if (DEBUG) { console.log('Reaction removed:', reaction)} rtm.sendMessage(":unamused: :"+reaction.reaction+":",reaction.item.channel); }); } if (DEBUG) { mockRTM(); } else { main(); }
JavaScript
0
@@ -3003,24 +3003,84 @@ %7D%0A %7D%0A + else %7B%0A parseCommand(message);%0A %7D%0A %7D %0A %0A
92fcb7a7c451d14e9c4feaee5c469e00b56076a0
fix word break and line height
src/Recommendations/Recommendations.js
src/Recommendations/Recommendations.js
import React from 'react'; require("./Recommendations.css"); var Recommendation = React.createClass({ render(){ return ( <div className="recommendation"> <span className="description"> <p>{this.props.description}</p> </span> </div> ) } }); var Recommendations = React.createClass({ recommendationOneDescription(){ return ( <div> <p>Weekly <span className="recommendation-highlight">pair programming</span> and <span className="recommendation-highlight">code reviews with a senior</span>.</p> </div> ) }, recommendationTwoDescription(){ return ( <div> <p>A <span className="recommendation-highlight">supportive environment</span> where juniors can be vulnerable without fear.</p> </div> ) }, recommendationThreeDescription(){ return ( <div> <p>Allocated work <span className="recommendation-highlight">time to learn</span> all the things.</p> </div> ) }, render(){ var recommendationOneDescription = this.recommendationOneDescription(); var recommendationTwoDescription = this.recommendationTwoDescription(); var recommendationThreeDescription = this.recommendationThreeDescription(); return ( <div className="recommendations-container"> <div className="recommendations-heading"> <h2>Recommendations</h2> </div> <Recommendation description={recommendationOneDescription}/> <Recommendation description={recommendationTwoDescription}/> <Recommendation description={recommendationThreeDescription}/> </div> ) } }); module.exports = Recommendations;
JavaScript
0.000238
@@ -529,16 +529,23 @@ reviews +%3C/span%3E with a @@ -550,23 +550,16 @@ a senior -%3C/span%3E .%3C/p%3E%0A
d94e82f2ecc69c069c934fd091f1cea1fe5b46ae
Use new urlResource options from CM
library/Denkmal/library/Denkmal/App.js
library/Denkmal/library/Denkmal/App.js
/** * @class Denkmal_App * @extends CM_App */ var Denkmal_App = CM_App.extend({ ready: function() { CM_App.prototype.ready.call(this); this._registerServiceWorker(); }, _registerServiceWorker: function() { if ('serviceWorker' in navigator) { var path = cm.getUrlResource('layout', 'js/service-worker.js'); /** * Same-origin workaround * @todo replace with https://github.com/cargomedia/CM/pull/1715 */ path = path.replace(cm.getUrlResource(), cm.getUrl()); navigator.serviceWorker.register(path).then(function(registration) { cm.debug.log('ServiceWorker registration succeeded.'); }).catch(function(error) { cm.debug.log('ServiceWorker registration failed.', error); }); } else { cm.debug.log('ServiceWorker not supported.'); } } });
JavaScript
0
@@ -330,192 +330,40 @@ .js' -);%0A /**%0A * Same-o +, %7BsameO rigin - workaround%0A * @todo replace with https://github.com/cargomedia/CM/pull/1715%0A */%0A path = path.replace(cm.getUrlResource(), cm.getUrl() +: true, root: true%7D );%0A%0A
098c72711f024b1d7dc2fbafee8f0e89a0b74c5e
create a new object before modifying
src/actions/notifs.js
src/actions/notifs.js
export const NOTIF_SEND = 'NOTIF_SEND'; export const NOTIF_DISMISS = 'NOTIF_DISMISS'; export const NOTIF_CLEAR = 'NOTIF_CLEAR'; /** * Publish a notification, * - if `dismissAfter` was set, the notification will be auto dismissed after the given period. * - if id wasn't specified, a time based id will be generated.`` */ export function notifSend(notif) { if (!notif.id) { notif.id = new Date().getTime(); } return dispatch => { dispatch({ type: NOTIF_SEND, payload: notif }); if (notif.dismissAfter) { setTimeout(() => { dispatch({ type: NOTIF_DISMISS, payload: notif.id }); }, notif.dismissAfter); } }; } /** * Dismiss a notification by the given id. */ export function notifDismiss(id) { return { type: NOTIF_DISMISS, payload: id }; } /** * Clear all notifications */ export function notifClear() { return { type: NOTIF_CLEAR }; }
JavaScript
0.000001
@@ -360,18 +360,64 @@ %7B%0A -if (!notif +const payload = Object.assign(%7B%7D, notif);%0A if (!payload .id) @@ -423,21 +423,23 @@ ) %7B%0A -notif +payload .id = ne @@ -525,23 +525,16 @@ payload -: notif %7D);%0A%0A @@ -539,21 +539,23 @@ if ( -notif +payload .dismiss @@ -629,21 +629,23 @@ ayload: -notif +payload .id %7D); @@ -647,21 +647,23 @@ %7D); %7D, -notif +payload .dismiss
3a61e0912a160d9fa50c3cc90f05fad6da200b1d
Fix code style
packages/react-jsx-highcharts/src/components/ColorAxis/ColorAxis.js
packages/react-jsx-highcharts/src/components/ColorAxis/ColorAxis.js
import React, { useEffect, useRef } from 'react'; import uuid from 'uuid/v4'; import { attempt } from 'lodash-es'; import { getNonEventHandlerProps, getEventsConfig } from '../../utils/events'; import ColorAxisContext from '../ColorAxisContext'; import useModifiedProps from '../UseModifiedProps'; import useChart from '../UseChart'; import createProvidedColorAxis from './createProvidedColorAxis'; const ColorAxis = ({ children = null, ...restProps }) => { const chart = useChart(); const colorAxisRef = useRef(null); const providedColorAxisRef = useRef(null); useEffect(() => { return () => { const colorAxis = colorAxisRef.current; if (colorAxis && colorAxis.remove) { // Axis may have already been removed, i.e. when Chart unmounted attempt(colorAxis.remove.bind(colorAxis), false); chart.needsRedraw(); } }; }, []); const modifiedProps = useModifiedProps(restProps); useEffect(() => { if (colorAxisRef.current !== null) { if (modifiedProps !== false) { const colorAxis = colorAxisRef.current; colorAxis.update(modifiedProps, false); chart.needsRedraw(); } } }); if (colorAxisRef.current === null) { colorAxisRef.current = createColorAxis(chart, restProps); providedColorAxisRef.current = createProvidedColorAxis( colorAxisRef.current ); chart.needsRedraw(); } return ( <ColorAxisContext.Provider value={providedColorAxisRef.current}> {children} </ColorAxisContext.Provider> ); }; const getColorAxisConfig = props => { const { id = uuid, ...rest } = props; const colorAxisId = typeof id === 'function' ? id() : id; const nonEventProps = getNonEventHandlerProps(rest); const events = getEventsConfig(rest); return { id: colorAxisId, events, ...nonEventProps }; }; const createColorAxis = (chart, props) => { const opts = getColorAxisConfig(props); let colorAxis; colorAxis = chart.addColorAxis(opts, false); return colorAxis; }; export default ColorAxis;
JavaScript
0.000169
@@ -992,22 +992,12 @@ null -) %7B%0A if ( + && modi @@ -1021,26 +1021,24 @@ se) %7B%0A - const colorA @@ -1061,26 +1061,24 @@ ef.current;%0A - colorA @@ -1109,34 +1109,32 @@ , false);%0A - chart.needsRedra @@ -1134,32 +1134,24 @@ dsRedraw();%0A - %7D%0A %7D%0A %7D);%0A @@ -1916,36 +1916,14 @@ ;%0A -let colorAxis;%0A colorAxis = +return cha @@ -1956,28 +1956,8 @@ e);%0A - return colorAxis;%0A %7D;%0A%0A
5fbf4f21ab328a403f4589db8a2b09960eddac93
remove a module in UI on double click
be.iminds.iot.dianne.builder/resources/js/dianne.js
be.iminds.iot.dianne.builder/resources/js/dianne.js
var source = { isSource:true, anchor : "Right", paintStyle:{ strokeStyle:"#555", fillStyle:"#FFF", lineWidth:2 }, hoverPaintStyle:{ lineWidth:3 }, connectorStyle:{ lineWidth:4, strokeStyle:"#333", joinstyle:"round", outlineColor:"white", outlineWidth:2 }, connectorHoverStyle:{ lineWidth:4, strokeStyle:"#555", outlineWidth:2, outlineColor:"white" }, // maxConnections:-1, } // the definition of target endpoints (will appear when the user drags a connection) var target = { isTarget:true, anchor: "Left", paintStyle:{ fillStyle:"#333" }, hoverPaintStyle:{ fillStyle: "#555" }, // maxConnections:-1, } jsPlumb.ready(function() { // your jsPlumb related init code goes here console.log("init jsPlumb"); jsPlumb.setContainer($("canvas")); jsPlumb.importDefaults({ ConnectionOverlays : [[ "Arrow", { location : 1 } ]], Connector : [ "Flowchart", { stub:[40, 60], gap:10, cornerRadius:5, alwaysRespectStubs:true } ], DragOptions : { cursor: 'pointer', zIndex:2000 }, }); var init = function(connection) { connection.getOverlay("label").setLabel(connection.sourceId.substring(15) + "-" + connection.targetId.substring(15)); connection.bind("editCompleted", function(o) { if (typeof console != "undefined") console.log("connection edited. path is now ", o.path); }); }; // suspend drawing and initialise. jsPlumb.doWhileSuspended(function() { // listen for new connections; initialise them the same way we initialise the connections at startup. jsPlumb.bind("connection", function(connInfo, originalEvent) { init(connInfo.connection); }); // make all the window divs draggable (intially canvas will be empty so not needed...) // jsPlumb.draggable($(".module.draggable"), { grid: [20, 20] }); // // listen for connection add/removes // jsPlumb.bind("beforeDetach", function(connection) { console.log("connection detach " + connection.sourceId + " -> " + connection.targetId); // TODO check whether connection can be detached return true; }); jsPlumb.bind("beforeDrop", function(connection) { console.log("connection add " + connection.sourceId + " -> " + connection.targetId); // TODO check whether connection is OK? return true; }); }); }); $( ".module.toolbox" ).click(function() { var module = $( this ).clone().removeClass("toolbox").addClass("draggable").appendTo("#canvas"); // TODO configure module dialog? var type = module.attr("id"); var id = guid(); module.attr("id",id); if(type==="Input"){ jsPlumb.addEndpoint(module, source); } else if(type==="Output"){ jsPlumb.addEndpoint(module, target); } else { jsPlumb.addEndpoint(module, source); jsPlumb.addEndpoint(module, target); } jsPlumb.draggable(module); }); /** * Generates a GUID string. * @returns {String} The generated GUID. * @example af8a8416-6e18-a307-bd9c-f2c947bbb3aa * @author Slavik Meltser (slavik@meltser.info). * @link http://slavik.meltser.info/?p=142 */ function guid() { function _p8(s) { var p = (Math.random().toString(16)+"000000000").substr(2,8); return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ; } return _p8() + _p8(true) + _p8(true) + _p8(); }
JavaScript
0.000001
@@ -1973,32 +1973,39 @@ %09%09%09console.log(%22 +Remove connection detac @@ -2003,15 +2003,8 @@ ion -detach %22 + @@ -2193,32 +2193,36 @@ %09%09%09console.log(%22 +Add connection add %22 @@ -2220,12 +2220,8 @@ ion -add %22 + @@ -2821,32 +2821,352 @@ %0A%09%0A%09 -jsPlumb.draggable(module +module.dblclick(function() %7B%0A%09%09console.log(%22Remove module %22+$(this).attr(%22id%22));%0A%09%09// delete this module%0A%09%09$.each(jsPlumb.getEndpoints($(this)), function(index, endpoint)%7B%0A%09%09%09jsPlumb.deleteEndpoint(endpoint)%7D%0A%09%09);%0A%09%09%0A%09%09jsPlumb.detachAllConnections($(this));%0A%09%09$(this).remove();%0A%09%7D);%0A%09%0A%09jsPlumb.draggable(module);%0A%09%0A%09console.log(%22Add module %22+id );%0A%7D
7959105e8012c832d7ed9cf11811d8163b10c4e4
check states and redirects
modules/users/client/controllers/authentication.client.controller.js
modules/users/client/controllers/authentication.client.controller.js
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', function ($scope, $state, $http, $location, $window, Authentication, PasswordValidator) { $scope.authentication = Authentication; $scope.popoverMsg = PasswordValidator.getPopoverMsg(); // Get an eventual error defined in the URL query string: $scope.error = $location.search().err; // If user is signed in then redirect back home if ($scope.authentication.user) { $location.path('/'); } $scope.signup = function (isValid) { $scope.error = null; if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'userForm'); return false; } $http.post('/api/auth/signup', $scope.credentials).success(function (response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the previous or home page $state.go($state.previous.state.name || 'home', $state.previous.params); }).error(function (response) { $scope.error = response.message; }); }; $scope.signin = function (isValid) { $scope.error = null; if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'userForm'); return false; } $http.post('/api/auth/signin', $scope.credentials).success(function (response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the previous or home page $state.go($state.previous.state.name || 'home', $state.previous.params); }).error(function (response) { $scope.error = response.message; }); }; // OAuth provider request $scope.callOauthProvider = function (url) { console.log($state.previous , $state.previous.href, url, $state, $state.state); if ($state.previous && $state.previous.href) { url += '?redirect_to=' + encodeURIComponent($state.previous.href).toString(); } // Effectively call OAuth authentication route: $window.location.href = url; }; } ]);
JavaScript
0
@@ -2016,24 +2016,26 @@ ate);%0A +// if ($state.p @@ -2042,16 +2042,29 @@ revious +!= undefined && $stat @@ -2078,16 +2078,29 @@ ous.href + != undefined ) %7B%0A @@ -2101,16 +2101,18 @@ %7B%0A +// url += @@ -2181,32 +2181,34 @@ String();%0A +// %7D%0A%0A // Effe
2161d5754e96e6e70547fcd9c29caf9e1710d30a
use map() and join()
osmaxx/excerptexport/static/excerptexport/scripts/utm_zone_filter.js
osmaxx/excerptexport/static/excerptexport/scripts/utm_zone_filter.js
jQuery(document).ready(function(){ var utm_optgroup_html_element = '#id_coordinate_reference_system optgroup[label="UTM zones"]', utm_zone_optgroup_original = jQuery(utm_optgroup_html_element).clone(); window.filterUTMZones = function (leafletGeometry) { var utm_zone_optgroup = jQuery(utm_optgroup_html_element); if (utm_zone_optgroup !== null) { utm_zone_optgroup.html(""); getUTMZones(leafletGeometry).done(function(data){ var srids = data["utm_zone_srids"].sort(), options_html = ''; srids.forEach(function(srid){ var original_text = utm_zone_optgroup_original.find('option[value=' + srid + ']').text(); options_html += _optionHTML(srid, original_text); }); utm_zone_optgroup.html(options_html); }).fail(console.log); } function getUTMZones(leafletGeometry) { var geometry = leafletGeometry.toGeoJSON()["geometry"], srid = 4326, csrftoken = Cookies.get('csrftoken'); return jQuery.ajax({ url: '/api/utm-zone-info/', contentType: "application/json; charset=utf-8", dataType: 'json', type: 'POST', data: JSON.stringify({"geom": geometry, "srid": srid}), beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); } function _optionHTML(srid, name) { return '<option value="' + srid + '">' + name + '</option>'; } }; });
JavaScript
0.000004
@@ -575,41 +575,17 @@ l = -'';%0A srids.forEach +srids.map (fun @@ -597,16 +597,20 @@ (srid)%7B%0A + @@ -735,23 +735,18 @@ -options_html += + return _op @@ -784,33 +784,46 @@ -%7D + %7D).join('' );%0A
8d455015a6a8783fa6d91ce94a5e9b113dc9a71c
Handle errors when traversing the node_modules dir to stop EventEmitter throwing an exception
packages/navy-plugin-nodejs/src/hooks/rewrite-linked-node-modules.js
packages/navy-plugin-nodejs/src/hooks/rewrite-linked-node-modules.js
import findit from 'findit' import path from 'path' import fs from 'fs' export default () => { const finder = findit(path.join(process.cwd(), 'node_modules')) finder.on('link', link => { if (link.indexOf('.bin') !== -1) return const absolutePath = fs.realpathSync(link) fs.unlinkSync(link) fs.symlinkSync(absolutePath, link) console.log('Linked', link, '->', absolutePath) }) }
JavaScript
0
@@ -64,16 +64,91 @@ rom 'fs' +%0Aimport os from 'os'%0A%0Aimport %7Bname as pluginName%7D from '../../package.json' %0A%0Aexport @@ -231,16 +231,159 @@ les'))%0A%0A + finder.on('error', err =%3E %7B%0A console.error(%60$%7BpluginName%7D failed to traverse your node_modules directory:%60, os.EOL, err.toString())%0A %7D)%0A%0A finder
9109ea1968b91b648cae81c6fa136fa025cdfb0f
Add console.error for server errors
polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js
polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager.js
// Copyright (C) 2016 The Android Open Source Project // // 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. (function() { 'use strict'; const HIDE_ALERT_TIMEOUT_MS = 5000; const CHECK_SIGN_IN_INTERVAL_MS = 60 * 1000; const STALE_CREDENTIAL_THRESHOLD_MS = 10 * 60 * 1000; const SIGN_IN_WIDTH_PX = 690; const SIGN_IN_HEIGHT_PX = 500; const TOO_MANY_FILES = 'too many files to find conflicts'; const AUTHENTICATION_REQUIRED = 'Authentication required\n'; Polymer({ is: 'gr-error-manager', behaviors: [ Gerrit.BaseUrlBehavior, ], properties: { /** * The ID of the account that was logged in when the app was launched. If * not set, then there was no account at launch. */ knownAccountId: Number, _alertElement: Element, _hideAlertHandle: Number, _refreshingCredentials: { type: Boolean, value: false, }, /** * The time (in milliseconds) since the most recent credential check. */ _lastCredentialCheck: { type: Number, value() { return Date.now(); }, }, }, attached() { this.listen(document, 'server-error', '_handleServerError'); this.listen(document, 'network-error', '_handleNetworkError'); this.listen(document, 'show-alert', '_handleShowAlert'); this.listen(document, 'visibilitychange', '_handleVisibilityChange'); this.listen(document, 'show-auth-required', '_handleAuthRequired'); }, detached() { this._clearHideAlertHandle(); this.unlisten(document, 'server-error', '_handleServerError'); this.unlisten(document, 'network-error', '_handleNetworkError'); this.unlisten(document, 'show-auth-required', '_handleAuthRequired'); this.unlisten(document, 'visibilitychange', '_handleVisibilityChange'); }, _shouldSuppressError(msg) { return msg.includes(TOO_MANY_FILES); }, _handleAuthRequired() { this._showAuthErrorAlert( 'Log in is required to perform that action.', 'Log in.'); }, _handleServerError(e) { Promise.all([ e.detail.response.text(), this._getLoggedIn(), ]).then(values => { const text = values[0]; const loggedIn = values[1]; if (e.detail.response.status === 403 && loggedIn && text === AUTHENTICATION_REQUIRED) { // The app was logged at one point and is now getting auth errors. // This indicates the auth token is no longer valid. this._showAuthErrorAlert('Auth error', 'Refresh credentials.'); } else if (!this._shouldSuppressError(text)) { this._showAlert('Server error: ' + text); } }); }, _handleShowAlert(e) { this._showAlert(e.detail.message, e.detail.action, e.detail.callback, e.detail.dismissOnNavigation); }, _handleNetworkError(e) { this._showAlert('Server unavailable'); console.error(e.detail.error.message); }, _getLoggedIn() { return this.$.restAPI.getLoggedIn(); }, _showAlert(text, opt_actionText, opt_actionCallback, dismissOnNavigation) { if (this._alertElement) { return; } this._clearHideAlertHandle(); if (dismissOnNavigation) { // Persist alert until navigation. this.listen(document, 'location-change', '_hideAlert'); } else { this._hideAlertHandle = this.async(this._hideAlert, HIDE_ALERT_TIMEOUT_MS); } const el = this._createToastAlert(); el.show(text, opt_actionText, opt_actionCallback); this._alertElement = el; }, _hideAlert() { if (!this._alertElement) { return; } this._alertElement.hide(); this._alertElement = null; // Remove listener for page navigation, if it exists. this.unlisten(document, 'location-change', '_hideAlert'); }, _clearHideAlertHandle() { if (this._hideAlertHandle != null) { this.cancelAsync(this._hideAlertHandle); this._hideAlertHandle = null; } }, _showAuthErrorAlert(errorText, actionText) { // TODO(viktard): close alert if it's not for auth error. if (this._alertElement) { return; } this._alertElement = this._createToastAlert(); this._alertElement.show(errorText, actionText, this._createLoginPopup.bind(this)); this._refreshingCredentials = true; this._requestCheckLoggedIn(); if (!document.hidden) { this._handleVisibilityChange(); } }, _createToastAlert() { const el = document.createElement('gr-alert'); el.toast = true; return el; }, _handleVisibilityChange() { // Ignore when the page is transitioning to hidden (or hidden is // undefined). if (document.hidden !== false) { return; } // If not currently refreshing credentials and the credentials are old, // request them to confirm their validity or (display an auth toast if it // fails). const timeSinceLastCheck = Date.now() - this._lastCredentialCheck; if (!this._refreshingCredentials && this.knownAccountId !== undefined && timeSinceLastCheck > STALE_CREDENTIAL_THRESHOLD_MS) { this._lastCredentialCheck = Date.now(); this.$.restAPI.checkCredentials(); } }, _requestCheckLoggedIn() { this.debounce( 'checkLoggedIn', this._checkSignedIn, CHECK_SIGN_IN_INTERVAL_MS); }, _checkSignedIn() { this.$.restAPI.checkCredentials().then(account => { const isLoggedIn = !!account; this._lastCredentialCheck = Date.now(); if (this._refreshingCredentials) { if (isLoggedIn) { // If the credentials were refreshed but the account is different // then reload the page completely. if (account._account_id !== this.knownAccountId) { this._reloadPage(); return; } this._handleCredentialRefreshed(); } else { this._requestCheckLoggedIn(); } } }); }, _reloadPage() { window.location.reload(); }, _createLoginPopup() { const left = window.screenLeft + (window.outerWidth - SIGN_IN_WIDTH_PX) / 2; const top = window.screenTop + (window.outerHeight - SIGN_IN_HEIGHT_PX) / 2; const options = [ 'width=' + SIGN_IN_WIDTH_PX, 'height=' + SIGN_IN_HEIGHT_PX, 'left=' + left, 'top=' + top, ]; window.open(this.getBaseUrl() + '/login/%3FcloseAfterLogin', '_blank', options.join(',')); this.listen(window, 'focus', '_handleWindowFocus'); }, _handleCredentialRefreshed() { this.unlisten(window, 'focus', '_handleWindowFocus'); this._refreshingCredentials = false; this._hideAlert(); this._showAlert('Credentials refreshed.'); }, _handleWindowFocus() { this.flushDebouncer('checkLoggedIn'); }, }); })();
JavaScript
0.000001
@@ -3205,32 +3205,61 @@ ext);%0A %7D%0A + console.error(text);%0A %7D);%0A %7D,
9141e41ed183bb337d58c3057680cf6b5d68b337
Fix metrics recording in the File Browser.
chrome/browser/resources/file_manager/js/metrics.js
chrome/browser/resources/file_manager/js/metrics.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Utility methods for accessing chrome.metricsPrivate API. * * To be included as a first script in main.html */ var metrics = {}; metrics.intervals = {}; metrics.startInterval = function(name) { metrics.intervals[name] = Date.now(); }; metrics.startInterval('Load.Total'); metrics.startInterval('Load.Script'); metrics.convertName_ = function(name) { return 'FileBrowser.' + name; }; metrics.decorate = function(name) { this[name] = function() { var args = Array.apply(null, arguments); args[0] = metrics.convertName_(args[0]); chrome.metricsPrivate[name].apply(chrome.metricsPrivate, args); if (localStorage.logMetrics) { console.log('chrome.metricsPrivate.' + name, args); } } }; metrics.decorate('recordMediumCount'); metrics.decorate('recordSmallCount'); metrics.decorate('recordTime'); metrics.decorate('recordUserAction'); metrics.recordInterval = function(name) { if (name in metrics.intervals) { metrics.recordTime(name, Date.now() - metrics.intervals[name]); } else { console.error('Unknown interval: ' + name); } }; metrics.recordEnum = function(name, value, validValues) { var maxValue; var index; if (validValues.constructor.name == 'Array') { index = validValues.indexOf(value); maxValue = validValues.length - 1; } else { index = value; maxValue = validValues - 1; } // Collect invalid values in the extra bucket at the end. if (index < 0 || index > maxValue) index = maxValue; var metricDescr = { 'metricName': metrics.convertName_(name), 'type': 'histogram-linear', 'min': 0, 'max': maxValue, 'buckets': maxValue + 1 }; chrome.metricsPrivate.recordValue(metricDescr, index); if (localStorage.logMetrics) { console.log('chrome.metricsPrivate.recordValue', [metricDescr.metricName, index, value]); } };
JavaScript
0.999717
@@ -13,17 +13,17 @@ (c) 201 -1 +2 The Chr @@ -1332,19 +1332,24 @@ %7B%0A var -max +boundary Value;%0A @@ -1449,27 +1449,32 @@ value);%0A -max +boundary Value = vali @@ -1487,20 +1487,16 @@ s.length - - 1 ;%0A %7D el @@ -1523,19 +1523,24 @@ ue;%0A -max +boundary Value = @@ -1554,12 +1554,8 @@ lues - - 1 ;%0A @@ -1595,13 +1595,16 @@ the -extra +overflow buc @@ -1646,19 +1646,24 @@ index %3E -max +boundary Value)%0A @@ -1677,18 +1677,292 @@ x = -maxValue;%0A +boundaryValue;%0A%0A // Setting min to 1 looks strange but this is exactly the recommended way%0A // of using histograms for enum-like types. Bucket #0 works as a regular%0A // bucket AND the underflow bucket.%0A // (Source: UMA_HISTOGRAM_ENUMERATION definition in base/metrics/histogram.h) %0A v @@ -2069,17 +2069,17 @@ 'min': -0 +1 ,%0A 'm @@ -2083,19 +2083,24 @@ 'max': -max +boundary Value,%0A @@ -2113,19 +2113,24 @@ ckets': -max +boundary Value +
a74c8c560dc7fb31ffc330ed17f398964f0450cf
Handle Android livestream
clientapp/controllers/ClientLiveStreamController.js
clientapp/controllers/ClientLiveStreamController.js
/* Copyright 2017 PSU Capstone Team D This code is available under the "MIT License". Please see the file LICENSE in this distribution for license terms.*/ // Define the ClientLiveStreamController on clientUI module angular.module('clientUI') .controller('ClientLiveStreamController', ['$scope', function ($scope) { $scope.skipHlsCheck = false; $scope.loadVideo = function() { if(($scope.skipHlsCheck === false) || (Hls.isSupported() !== undefined)) { var video = document.getElementById('video'); var hls = new Hls(); hls.loadSource('http://delta-1-yanexx65s8e5.live.elementalclouddev.com/out/p/15/it me.m3u8'); hls.attachMedia(video); } else { toastr.error("Your browswer does not support HLS streaming", "Error"); } } }]);
JavaScript
0.000001
@@ -241,9 +241,10 @@ I')%0A -%09 + .con @@ -308,28 +308,24 @@ ($scope) %7B%0A - $scope.s @@ -349,20 +349,16 @@ se;%0A - - $scope.l @@ -376,16 +376,17 @@ function + () %7B%0A @@ -392,18 +392,263 @@ - if +var ua = navigator.userAgent.toLowerCase();%0A var isAndroid = ua.indexOf(%22android%22) %3E -1;%0A%0A if (isAndroid) %7B%0A window.location = 'http://delta-1-yanexx65s8e5.live.elementalclouddev.com/out/p/15/it me.m3u8';%0A return;%0A %7D%0A if (($s @@ -720,32 +720,24 @@ ) %7B%0A - - var video = @@ -766,32 +766,24 @@ d('video');%0A - var @@ -803,32 +803,24 @@ ();%0A - - hls.loadSour @@ -901,24 +901,16 @@ m3u8');%0A - @@ -943,41 +943,23 @@ - %7D%0A +%7D%0A - else %7B%0A - @@ -1039,28 +1039,18 @@ ;%0A - %7D%0A +%7D%0A %7D%0A%7D%5D
c6f7549a0ff3065e204d3e3bf93e0d03ba7adfc4
Update code
Scripts/App.js
Scripts/App.js
(function ($, marked, MathJax) { function getQueryStringParameters() { var params = document.URL.split("?")[1].split("&"); var obj = {}; for (var i = 0; i < params.length; i = i + 1) { var singleParam = params[i].split("="); obj[singleParam[0]] = decodeURIComponent(singleParam[1]); } return obj; } function getFileServerRelativeUrl() { var deferred = $.Deferred(); var queryStringParameters = getQueryStringParameters(); if (!queryStringParameters.SPListId && !queryStringParameters.SPListItemId) { return deferred.reject('This app is a custom menu item action, please visit this page from menu item.'); } var appWebUrl = queryStringParameters.SPAppWebUrl; var hostWebUrl = queryStringParameters.SPHostUrl; var clientContext = SP.ClientContext.get_current(); var appContextSite = new SP.AppContextSite(clientContext, hostWebUrl); var web = appContextSite.get_web(); var list = web.get_lists().getById(queryStringParameters.SPListId); var listItem = list.getItemById(queryStringParameters.SPListItemId); var file = listItem.get_file(); clientContext.load(file, 'ServerRelativeUrl'); clientContext.executeQueryAsync(function (sender, args) { var serverRelativeUrl = file.get_serverRelativeUrl(); deferred.resolve(serverRelativeUrl, appWebUrl, hostWebUrl); }, function (sender, args) { var message = args.get_message(); deferred.reject(message); }); return deferred.promise(); } function getFileServerRelativeUrlOnFail(message) { $('.spinner').hide(); $('.error').text(message).show(); } function readFileContents(serverRelativeUrl, appWebUrl, hostWebUrl) { var deferred = $.Deferred(); if (!serverRelativeUrl.match(/\.md$/)) { return deferred.reject('Sorry, only markdown files are supported.'); } var executor = new SP.RequestExecutor(appWebUrl); var options = { url: appWebUrl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('" + serverRelativeUrl + "')/$value?@target='" + hostWebUrl + "'", type: "GET", success: function (response) { if (response.statusCode == 200) { var markdown = response.body; deferred.resolve(markdown); } else { deferred.reject(response.statusCode + ": " + response.statusText); } }, error: function (response) { deferred.reject(response.statusCode + ": " + response.statusText); } }; executor.executeAsync(options); return deferred.promise(); } function readFileContentsDeferred(serverRelativeUrl, appWebUrl, hostWebUrl) { readFileContents(serverRelativeUrl, appWebUrl, hostWebUrl).done(render).fail(readFileContentsOnFail); } function readFileContentsOnFail(message) { $('.spinner').hide(); $('.error').text(message).show(); } function render(markdown) { var renderer = new marked.Renderer(); renderer.table = function (header, body) { return '<table class=\'table\'>\n' + '<thead>\n' + header + '</thead>\n' + '<tbody>\n' + body + '</tbody>\n' + '</table>\n'; }; var html = marked(markdown, { renderer: renderer }); $('.container').html(html); MathJax.Hub.Typeset(); } getFileServerRelativeUrl().done(readFileContentsDeferred).fail(getFileServerRelativeUrlOnFail); })(jQuery, marked, MathJax);
JavaScript
0
@@ -2969,211 +2969,8 @@ %0D%0A%0D%0A - function readFileContentsDeferred(serverRelativeUrl, appWebUrl, hostWebUrl) %7B%0D%0A readFileContents(serverRelativeUrl, appWebUrl, hostWebUrl).done(render).fail(readFileContentsOnFail);%0D%0A %7D%0D%0A%0D%0A @@ -3676,12 +3676,12 @@ l(). -done +then (rea @@ -3697,23 +3697,10 @@ ents -Deferred).fail( +, getF @@ -3726,16 +3726,53 @@ lOnFail) +.then(render, readFileContentsOnFail) ;%0D%0A%7D)(jQ
b1611cce3ee216ee05228e3bf2059d14fe00d79b
Add the redirectTo property
src/andamio.router.js
src/andamio.router.js
Andamio.Router = Backbone.Router.extend({ // Override Backbone.Router._bindRoutes _bindRoutes: function () { if (!this.routes) { return; } this.routes = _.result(this, 'routes'); _.each(this.routes, function (route) { var urls = _.isArray(route.url) ? route.url : [route.url]; var callback; _.each(urls, function (url) { // Register the same callback for the same route urls callback = callback || this._createCallback(url, route.name, route.view); this.route(url, route.name, callback); }, this); }, this); }, _createCallback: function (url, name, View) { var router = this; var callback = function () { var urlParams = arguments; var view = new View(); // Execute view's model load method if (view.model && _.isFunction(view.model.load)) { view.model.load.apply(view.model, urlParams); } router.trigger('navigate', view, url, urlParams); }; return callback; } });
JavaScript
0.000001
@@ -491,25 +491,8 @@ oute -.name, route.view );%0A @@ -612,18 +612,13 @@ rl, -name, View +route ) %7B%0A @@ -640,24 +640,206 @@ = this;%0A -%0A var + callback;%0A%0A if (route.redirectTo) %7B%0A callback = function () %7B%0A Backbone.history.navigate(route.redirectTo, %7Btrigger: true, replace: true%7D);%0A %7D;%0A %7D else %7B%0A callbac @@ -858,24 +858,26 @@ () %7B%0A + var urlParam @@ -880,16 +880,30 @@ arams = +%5B%5D.slice.call( argument @@ -903,18 +903,21 @@ rguments +) ;%0A + va @@ -933,17 +933,76 @@ new -View();%0A%0A +route.view();%0A var model = view.model %7C%7C view.collection;%0A%0A @@ -1027,16 +1027,30 @@ s model +or collection load met @@ -1063,17 +1063,14 @@ + if ( -view. mode @@ -1087,21 +1087,16 @@ unction( -view. model.lo @@ -1110,21 +1110,57 @@ -view. + model.urlParams = urlParams;%0A model.lo @@ -1168,21 +1168,16 @@ d.apply( -view. model, u @@ -1189,27 +1189,31 @@ ams);%0A + + %7D%0A%0A + router @@ -1260,18 +1260,26 @@ s);%0A + %7D;%0A %7D -; %0A%0A re
150dd3ae65d82e1d3b81a3ce384fddd257456707
Use Debug for logging errors
Source/Main.js
Source/Main.js
"use strict"; var OS = require('os'), Net = require('net'), CPP = require('childprocess-promise'); class Main{ constructor(Port){ this.Port = Number(Port); this.Server = null; this.Children = []; this.Database = new Map(); } Run(){ let NumCPUs = OS.cpus().length; let SupportedEvents = []; for(let Name in Main){ if (typeof Main[Name] === 'function' && Name.substr(0, 6) === 'Action') SupportedEvents.push(Name.substr(6)); } for(var i = 0; i < NumCPUs; ++i){ let Child = new CPP(__dirname + '/../Main.js'); SupportedEvents.forEach(function(Child, Event){ Child.on(Event, function(Request, Message){ try { Message.Result = Main['Action' + Event].call(this, Request, Child, Message); } catch(error){ Message.Result = {Type: 'Error', Message: error.message}; } Child.Finished(Message); }.bind(this)); }.bind(this, Child)); Child.Send('SupportedEvents', SupportedEvents); this.Children.push(Child); } let Server = this.Server = Net.createServer(); this.Server.listen(this.Port, this.Children.forEach.bind(this.Children, function(Child){ Child.Target.send('Server', Server); })); } static NormalizeType(Value){ let ValueInt = parseInt(Value); if(!isNaN(ValueInt) && ValueInt.toString() === Value){ return ValueInt; } return Value; } static Validate(Type, Action, Value){ if(Type === Main.VAL_NUMERIC){ if(typeof Value !== 'number') throw new Error(`Cant ${Action} Non-Numeric Item`); } else if(Type === Main.VAL_STRINGISH){ if(typeof Value !== 'string' && typeof Value !== 'number') throw new Error(`Cant ${Action} Non-Stringish Item`); } else if(Type === Main.VAL_HASH){ if(typeof Value !== 'object' || !Value.constructor || !Value.constructor.name === 'Map') throw new Error(`Cant ${Action} Non-Hash Item`); } else if(Type === Main.VAL_LIST){ if(typeof Value !== 'object' || !Value.constructor || !Value.constructor.name === 'Set') throw new Error(`Cant ${Action} Non-List Item`); } return Value; } static ValidateArguments(TypeOrLength, Length){ if(typeof TypeOrLength === 'string'){ let IsOdd = Length % 2; if(TypeOrLength === Main.ARGS_EVEN && IsOdd) throw new Error(Main.MSG_ARGS_INVALID + '; Expected Even'); else if(TypeOrLength === Main.ARGS_ODD && !IsOdd){ throw new Error(Main.MSG_ARGS_INVALID + '; Expected Odd'); } } else{ if(TypeOrLength > Length){ throw new Error(Main.MSG_ARGS_MORE); } else if(TypeOrLength < Length){ throw new Error(Main.MSG_ARGS_LESS); } } } } Main.VAL_NUMERIC = 'VAL_NUMERIC'; Main.VAL_STRINGISH = 'VAL_STRING'; Main.VAL_HASH = 'VAL_HASH'; Main.VAL_LIST = 'VAL_LIST'; Main.MSG_ARGS_MORE = 'Too Many Arguments'; Main.MSG_ARGS_LESS = 'Too less Arguments'; Main.MSG_ARGS_INVALID = 'Invalid Number of Arguments'; Main.ARGS_EVEN = 'EVEN'; Main.ARGS_ODD = 'ODD'; Main.prototype.Timeouts = {}; module.exports = Main; // Load the functions require('./Methods_Basic'); require('./Methods_Hash');
JavaScript
0
@@ -98,16 +98,63 @@ romise') +,%0A Debug = require('debug')('happy-db:errors') ;%0Aclass @@ -855,16 +855,48 @@ error)%7B%0A + Debug(error.stack);%0A
351e9afff132c9f7d508d7529e1d65101b607b68
Update JSDoc
TimeCounter.js
TimeCounter.js
/** * This is a simple time counter. * It counts only how long it runs in following format: * <b>hh:mm:ss</b> * */ function TimeCounter() { /** * Private members */ var count = 0; var _intervalTimer = undefined; // given options var options = arguments[0] || {}; /** * Default attributes * * @type {{autostart: boolean, hours: number, minutes: number, seconds: number, timeString: string}} */ var defaults = { autostart : false, hours : 0, minutes : 0, seconds : 0, timeString : '00:00:00' } if(options) { // run through the defaults to replace the defaults with the given options var key; for (key in defaults) { if (options[key] !== undefined) { defaults[key] = options[key]; } } } /** * Define getters and setters */ Object.defineProperty(this, 'count', { get: function () { return count; }, set: function (value) { count = value; } }); Object.defineProperty(this, 'hours', { get: function () { return this.formatNumber(defaults.hours); }, set: function (value) { defaults.hours = value; } }); Object.defineProperty(this, 'minutes', { get: function () { return this.formatNumber(defaults.minutes); }, set: function (value) { defaults.minutes = value; } }); Object.defineProperty(this, 'seconds', { get: function () { return this.formatNumber(defaults.seconds); }, set: function (value) { defaults.seconds = value; } }); // sets the time this.setTime(defaults); if (defaults.autostart) { this.start(); } } /** * Define class methods. */ TimeCounter.prototype = { /** * Starts the counter */ start: function () { // start the timer if it is not running. if(this._intervalTimer !== undefined) { return false; } console.log('Start time counting with: ' + this.getTime()); this._intervalTimer = window.setInterval(this.tick, 1000, this); }, /** * Stops counter and reset props */ stop: function () { // do the clearing only if the timer is currently running if(this._intervalTimer === undefined) { return false; } console.log('Stop time counting at: ' + this.getTime()); window.clearInterval(this._intervalTimer); this._intervalTimer = undefined; this.reset(); }, /** * Resets the counter props */ reset: function () { this.count = this.seconds = this.minutes = this.hours = 0; }, /** * Returns the whole time string. */ getTime: function () { return [this.hours, this.minutes, this.seconds].join(':'); }, /** * Sets the time of the time counter. */ setTime: function (opts) { var options = arguments[0] || opts || {}; var hrs = 0; var mins = 0; var secs = 0; if(Object.keys(options).length) { if(options.hasOwnProperty('timeString')) { // user given time string! // If the user specify a time string and the separate times (hours, minutes and seconds), // prefer the time string instead. var times = options.timeString.split(':'); if(times.length === 3) { hrs = (!isNaN(times[0])) ? parseInt(times[0]) : 0; mins = (!isNaN(times[1])) ? parseInt(times[1]) : 0; secs = (!isNaN(times[2])) ? parseInt(times[2]) : 0; } else { throw new SyntaxError('The given time string is invalid! Please use the following format "hh:mm:ss". Given time is: ' + options.timeString); } } else { // user gives the times separately. hrs = (!isNaN(options.hours)) ? parseInt(options.hours) : 0; mins = (!isNaN(options.minutes)) ? parseInt(options.minutes) : 0; secs = (!isNaN(options.seconds)) ? parseInt(options.seconds) : 0; } // If the given seconds are greater than 59, // then throw an error. if(secs > 59) { throw new Error('Seconds must be between 0 - 59'); } // If the given minutes are greater than 59, // then throw an error. if(mins > 59) { throw new Error('Minutes must be between 0 - 59'); } this.hours = hrs; this.minutes = mins; this.seconds = secs; } else { if(opts === undefined) { throw new SyntaxError('No arguments was given!'); } } }, /** * Handler called on each tick of the timer. * * @param timeCounter TimeCounter */ tick: function (timeCounter) { timeCounter.count++; timeCounter.seconds++; if(timeCounter.seconds % 60 === 0) { // have one minute completed timeCounter.seconds = 0; timeCounter.minutes++; if(timeCounter.minutes % 60 === 0) { // have an hour completed timeCounter.minutes = 0; timeCounter.hours++; } } timeCounter.triggerTickEvent(); }, /** * Triggers the tick event. * Includes the current time of the tick. */ triggerTickEvent: function () { var ev = new CustomEvent('TimeCounter:tick', {'detail': {'time': this.getTime()} }); document.dispatchEvent(ev); }, /** * 'Formats' the given number * * @param number int */ formatNumber: function (number) { return (number < 10) ? '0' + number : number; } };
JavaScript
0
@@ -109,16 +109,63 @@ %3C/b%3E%0A *%0A + * @author Sascha Hofrichter%0A * @version 1.0.0%0A */%0Afunc
af20f26856af78cb1f572945f25f64ab860f1a35
remove use strict
Transformer.js
Transformer.js
'use strict'; var Visitor = require('tree-visitor'); module.exports = Transformer; function Transformer(actions) { Visitor.apply(this, arguments); } Transformer.prototype = Object.create(Visitor.prototype); Transformer.replaceNode = function (ret, i, nodes) { if (ret === null) { nodes.splice(i, 1); return i; } if (Array.isArray(ret)) { nodes.splice.apply(nodes, [i, 1].concat(ret)); return i + ret.length; } if (ret !== undefined) nodes[i] = ret; return i + 1; } Transformer.prototype._visitNodes = function (nodes) { var i = 0; while (i < nodes.length) { var ret = this._visitNode(nodes[i]); i = Transformer.replaceNode(ret, i, nodes); } return nodes; }; Transformer.prototype._visitNode = function (node) { var ret = Visitor.prototype._visitNode.apply(this, arguments); return ret === undefined ? node : ret; };
JavaScript
0.000007
@@ -1,19 +1,4 @@ -'use strict';%0A%0A var
c63bdb5fb16514cf568d5052bddc6dd48551ee7c
Remove redundant doc tag descriptions
src/client/voice/util/PlayInterface.js
src/client/voice/util/PlayInterface.js
const { Readable } = require('stream'); const prism = require('prism-media'); /** * Options that can be passed to stream-playing methods: * @typedef {Object} StreamOptions * @property {StreamType} [type='unknown'] The type of stream. 'unknown', 'converted', 'opus', 'broadcast. * @property {number} [seek=0] The time to seek to * @property {number|boolean} [volume=1] The volume to play at. Set this to false to disable volume transforms for * this stream to improve performance. * @property {number} [passes=1] How many times to send the voice packet to reduce packet loss * @property {number} [plp] Expected packet loss percentage * @property {boolean} [fec] Enabled forward error correction * @property {number|string} [bitrate=96] The bitrate (quality) of the audio in kbps. * If set to 'auto', the voice channel's bitrate will be used * @property {number} [highWaterMark=12] The maximum number of opus packets to make and store before they are * actually needed. See https://nodejs.org/en/docs/guides/backpressuring-in-streams/. Setting this value to * 1 means that changes in volume will be more instant. */ /** * An option passed as part of `StreamOptions` specifying the type of the stream. * * `unknown`: The default type, streams/input will be passed through to ffmpeg before encoding. * Will play most streams. * * `converted`: Play a stream of 16bit signed stereo PCM data, skipping ffmpeg. * * `opus`: Play a stream of opus packets, skipping ffmpeg. You lose the ability to alter volume. * * `ogg/opus`: Play an ogg file with the opus encoding, skipping ffmpeg. You lose the ability to alter volume. * * `webm/opus`: Play a webm file with opus audio, skipping ffmpeg. You lose the ability to alter volume. * @typedef {string} StreamType */ /** * An interface class to allow you to play audio over VoiceConnections and VoiceBroadcasts. */ class PlayInterface { constructor(player) { this.player = player; } /** * Play an audio resource. * @param {VoiceBroadcast|ReadableStream|string} resource The resource to play. * @param {StreamOptions} [options] The options to play. * @example * // Play a local audio file * connection.play('/home/hydrabolt/audio.mp3', { volume: 0.5 }); * @example * // Play a ReadableStream * connection.play(ytdl('https://www.youtube.com/watch?v=ZlAU_w7-Xp8', { filter: 'audioonly' })); * @example * // Play a voice broadcast * const broadcast = client.createVoiceBroadcast(); * broadcast.play('/home/hydrabolt/audio.mp3'); * connection.play(broadcast); * @example * // Using different protocols: https://ffmpeg.org/ffmpeg-protocols.html * connection.play('http://www.sample-videos.com/audio/mp3/wave.mp3'); * @returns {StreamDispatcher} */ play(resource, options = {}) { if (resource instanceof Broadcast) { if (!this.player.playBroadcast) throw Error('VOICE_PLAY_INTERFACE_NO_BROADCAST'); return this.player.playBroadcast(resource, options); } const type = options.type || 'unknown'; if (type === 'unknown') { return this.player.playUnknown(resource, options); } else if (type === 'converted') { return this.player.playPCMStream(resource, options); } else if (type === 'opus') { return this.player.playOpusStream(resource, options); } else if (type === 'ogg/opus') { if (!(resource instanceof Readable)) throw Error('VOICE_PRISM_DEMUXERS_NEED_STREAM'); return this.player.playOpusStream(resource.pipe(new prism.OggOpusDemuxer())); } else if (type === 'webm/opus') { if (!(resource instanceof Readable)) throw Error('VOICE_PRISM_DEMUXERS_NEED_STREAM'); return this.player.playOpusStream(resource.pipe(new prism.WebmOpusDemuxer())); } throw Error('VOICE_PLAY_INTERFACE_BAD_TYPE'); } static applyToClass(structure) { for (const prop of ['play']) { Object.defineProperty(structure.prototype, prop, Object.getOwnPropertyDescriptor(PlayInterface.prototype, prop)); } } } module.exports = PlayInterface; const Broadcast = require('../VoiceBroadcast');
JavaScript
0.000015
@@ -234,52 +234,8 @@ eam. - 'unknown', 'converted', 'opus', 'broadcast. %0A *
0729b5fc600822208f4b323efbce556fc18370be
Add flag when injular is attached to module
src/attachToModule.js
src/attachToModule.js
import { instantiateDirective } from './ngHelpers'; function injularCompile($compileNode, templateAttrs, childTranscludeFn) { const node = $compileNode[0]; node.$injularTemplate = node.outerHTML; // eslint-disable-next-line no-underscore-dangle, max-len return this._nonInjularCompile && this._nonInjularCompile($compileNode, templateAttrs, childTranscludeFn); } function registerInjularDirective(name, directiveFactory) { // eslint-disable-next-line no-underscore-dangle return this._nonInjularDirective(name, ['$injector', ($injector) => { const directive = instantiateDirective(name, directiveFactory, $injector); if (!directive.template && directive.restrict === 'E') { // eslint-disable-next-line no-underscore-dangle, directive._nonInjularCompile = directive.compile; directive.compile = injularCompile; } return directive; }]); } export default function attachToModule(module, injularData) { /* eslint-disable no-param-reassign, no-underscore-dangle */ module.config(['$compileProvider', ($compileProvider) => { if ('_nonInjularDirective' in $compileProvider) return; $compileProvider._nonInjularDirective = $compileProvider.directive; $compileProvider.directive = registerInjularDirective; }]).run(['$injector', ($injector) => { injularData.$injector = $injector; }]); /* eslint-enable no-param-reassign, no-underscore-dangle */ }
JavaScript
0
@@ -1009,16 +1009,89 @@ ngle */%0A + if (module.$injularAttached) return;%0A module.$injularAttached = true;%0A module
f9fc45b809d88e1259a3df5d6d80903e3dc72140
Fix Code Climate
src/build/buildApp.js
src/build/buildApp.js
import fs from 'fs'; import crypto from 'crypto'; import _ from 'lodash'; import path from 'path'; import ncp from 'ncp'; import shellJs from 'shelljs'; const copy = ncp.ncp; /** * Only picks certain app args to pass to nativefier.json * @param options */ function selectAppArgs(options) { return { name: options.name, companyName: options.companyName, targetUrl: options.targetUrl, counter: options.counter, width: options.width, height: options.height, minWidth: options.minWidth, minHeight: options.minHeight, maxWidth: options.maxWidth, maxHeight: options.maxHeight, showMenuBar: options.showMenuBar, fastQuit: options.fastQuit, userAgent: options.userAgent, nativefierVersion: options.nativefierVersion, ignoreCertificate: options.ignoreCertificate, ignoreGpuBlacklist: options.ignoreGpuBlacklist, enableEs3Apis: options.enableEs3Apis, insecure: options.insecure, flashPluginDir: options.flashPluginDir, diskCacheSize: options.diskCacheSize, fullScreen: options.fullScreen, hideWindowFrame: options.hideWindowFrame, maximize: options.maximize, disableContextMenu: options.disableContextMenu, disableDevTools: options.disableDevTools, zoom: options.zoom, internalUrls: options.internalUrls, crashReporter: options.crashReporter, singleInstance: options.singleInstance, dependencies: options.dependencies, processEnvs: options.processEnvs, }; } function maybeCopyScripts(srcs, dest) { if (!srcs) { return new Promise((resolve) => { resolve(); }); } const promises = srcs.map(src => new Promise((resolve, reject) => { if (!fs.existsSync(src)) { reject('Error copying injection files: file not found'); return; } let destFileName; if (path.extname(src) === '.js') { destFileName = 'inject.js'; } else if (path.extname(src) === '.css') { destFileName = 'inject.css'; } else { resolve(); return; } copy(src, path.join(dest, 'inject', destFileName), (error) => { if (error) { reject(`Error Copying injection files: ${error}`); return; } resolve(); }); })); return new Promise((_resolve, _reject) => { Promise.all(promises) .then(() => { _resolve(); }) .catch((error) => { _reject(error); }); }); } function maybeCopyAssets(srcs, dest) { if (!srcs) { return new Promise((resolve) => { resolve(); }); } const promises = srcs.map(src => new Promise((resolve, reject) => { if (!fs.existsSync(src)) { reject('Error copying assets directories or files: not found'); return; } const destPath = path.join(dest, 'assets/'); if (!fs.existsSync(destPath)) { fs.mkdir(destPath); } copy(src, path.join(destPath, path.basename(src)), (error) => { if (error) { reject(`Error Copying assets directories or files: ${error}`); return; } resolve(); }); })); return new Promise((resolve, reject) => { Promise.all(promises) .then(() => { resolve(); }) .catch((error) => { reject(error); }); }); } function normalizeAppName(appName, url) { // use a simple 3 byte random string to prevent collision const hash = crypto.createHash('md5'); hash.update(url); const postFixHash = hash.digest('hex').substring(0, 6); const normalized = _.kebabCase(appName.toLowerCase()); return `${normalized}-nativefier-${postFixHash}`; } function changeAppPackageJsonName(appPath, name, url) { const packageJsonPath = path.join(appPath, '/package.json'); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath)); packageJson.name = normalizeAppName(name, url); fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson)); } function addAdditionalDependencies(appPath, options) { if (options.dependencies) { const packageJsonPath = path.join(appPath, '/package.json'); const packageJson = JSON.parse(fs.readFileSync(packageJsonPath)); packageJson.dependencies = Object.assign(packageJson.dependencies, options.dependencies); fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson)); } } /** * Allow to start a shell command * * @param {string} cmd * @param {boolean} silent * @param {function} callback */ function shellExec(cmd, silent, callback) { shellJs.exec(cmd, { silent }, (code, stdout, stderr) => { if (code) { callback(JSON.stringify({ code, stdout, stderr })); return; } callback(); }); } /** * Creates a temporary directory and copies the './app folder' inside, * and adds a text file with the configuration for the single page app. * * @param {string} src * @param {string} dest * @param {{}} options * @param callback */ function buildApp(src, dest, options, callback) { const appArgs = selectAppArgs(options); copy(src, dest, (error) => { if (error) { callback(`Error Copying temporary directory: ${error}`); return; } fs.writeFileSync(path.join(dest, '/nativefier.json'), JSON.stringify(appArgs)); maybeCopyScripts(options.inject, dest) .then(() => maybeCopyAssets(options.assets, dest)) .then(() => { changeAppPackageJsonName(dest, appArgs.name, appArgs.targetUrl); addAdditionalDependencies(dest, options); shellExec(`cd ${dest} && npm install`, true, () => {}); callback(); }) .catch(() => { }); }); } export default buildApp;
JavaScript
0.000001
@@ -2226,183 +2226,28 @@ urn -new Promise((_resolve, _reject) =%3E %7B%0A Promise.all(promises)%0A .then(() =%3E %7B%0A _resolve();%0A %7D)%0A .catch((error) =%3E %7B%0A _reject(error);%0A %7D);%0A %7D +Promise.all(promises );%0A%7D @@ -2909,179 +2909,28 @@ urn -new Promise((resolve, reject) =%3E %7B%0A Promise.all(promises)%0A .then(() =%3E %7B%0A resolve();%0A %7D)%0A .catch((error) =%3E %7B%0A reject(error);%0A %7D);%0A %7D +Promise.all(promises );%0A%7D
f6ba3fd260ef7bc4bfaea1d43815e6c60df60fe8
Remove unnecessary setter
resources/assets/js/vuex/actions.js
resources/assets/js/vuex/actions.js
import _ from 'lodash' import RandExp from 'randexp' export const loadRoutes = function ({dispatch}) { this.$api_demo2.load({url: 'routes/index'}) .then((response) => { dispatch('SET_ROUTES_ERROR', false) dispatch('SET_ROUTES', response.data) }) .catch((xhr, status, error) => { let response = {} response.status = xhr.status + ' : ' + error response.data = xhr.responseText dispatch('SET_ROUTES_ERROR', response) }) } export const loadRequests = function ({dispatch}) { // TODO split Firebase and JSON storage. if (ENV.firebaseToken && ENV.firebaseToken) { return } this.$api.ajax('GET', 'requests') .then(function (response) { dispatch('SET_REQUESTS', response.data) }) } export const setRequests = function ({dispatch}, requests) { dispatch('SET_REQUESTS', requests) } export const setCurrentRequest = ({dispatch}, request) => { dispatch('SET_INFO_MODE', 'request') dispatch('SET_CURRENT_ROUTE', null) dispatch('SET_CURRENT_REQUEST', request) } export const setCurrentRequestFromRoute = ({dispatch}, route) => { dispatch('SET_INFO_MODE', 'route') dispatch('SET_RESPONSE', null) dispatch('SET_CURRENT_ROUTE', route) let request = { method: route.methods[0], path: route.path, name: "", body: route.hasOwnProperty('body') ? route.body : "", wheres: route.hasOwnProperty('wheres') ? route.wheres : {}, headers: route.hasOwnProperty('headers') ? route.headers : [], config: { addCRSF: true, } } dispatch('SET_CURRENT_REQUEST', request) } export const deleteRequest = function ({dispatch}, request) { dispatch('DELETE_REQUEST', request) this.$api.ajax('DELETE', 'requests/' + request.id) } export const saveRequest = function ({dispatch}, request, next = () => { }) { dispatch('SET_REQUEST_IS_SAVING', true) this.$api.ajax('POST', 'requests', this.request) .then(function (data) { dispatch('SET_REQUEST_IS_SAVING', false) dispatch('SET_CURRENT_REQUEST', data.data) dispatch('SET_CURRENT_REQUEST', data.data) next() }) } export const updateRequest = function ({dispatch}, request, next = () => { }) { dispatch('SET_REQUEST_IS_SAVING', true) this.$api.ajax('PUT', 'requests/' + request.id, request) .done(function (response) { dispatch('SET_REQUEST_IS_SAVING', false) dispatch('SET_CURRENT_REQUEST', response.data) dispatch('UPDATE_REQUEST', response.data) }) } export const scheduleSending = ({dispatch}, status) => dispatch('SET_SENDING_SCHEDULED', status)
JavaScript
0.000051
@@ -2195,63 +2195,8 @@ ta)%0A - dispatch('SET_CURRENT_REQUEST', data.data)%0A
93176be3b92c539014a0d16cc964a1315f3b438a
set libraryTarget to 'commonjs2'
make-webpack-config.js
make-webpack-config.js
var webpack = require('webpack') var path = require('path') var fs = require('fs') var ExtractTextPlugin = require('extract-text-webpack-plugin') var StatsPlugin = require('stats-webpack-plugin') var loadersByExtension = require('./lib/loaders-by-extension') module.exports = function(opts) { var entry = { main: opts.prerender ? './app/mainApp' : './app/mainApp' } var loaders = { 'jsx': opts.hotComponents ? [ 'react-hot-loader', 'babel-loader?stage=0' ] : 'babel-loader?stage=0', 'js': { loader: 'babel-loader?stage=0', include: path.join(__dirname, 'app') }, 'json': 'json-loader', 'txt': 'raw-loader', 'png|jpg|jpeg|gif|svg': 'url-loader?limit=10000', 'woff|woff2': 'url-loader?limit=100000', 'ttf|eot': 'file-loader', 'wav|mp3': 'file-loader', 'html': 'html-loader', 'md|markdown': [ 'html-loader', 'markdown-loader' ] } var cssLoader = opts.minimize ? 'css-loader' : 'css-loader?localIdentName=[path][name]---[local]---[hash:base64:5]'; var stylesheetLoaders = { 'css': cssLoader, 'less': [ cssLoader, 'less-loader' ], 'styl': [ cssLoader, 'stylus-loader' ], 'scss|sass': [ cssLoader, 'sass-loader' ] } var additionalLoaders = [ // { test: /some-reg-exp$/, loader: 'any-loader' } ] var alias = { } var aliasLoader = { } var externals = [ ] var modulesDirectories = [ 'node_modules' ] var extensions = [ '', '.js', '.jsx', '.json', '.node' ]; var root = path.join(__dirname, 'app') var publicPath = opts.devServer ? 'http://localhost:2992/dist/' : '/dist/' var output = { path: __dirname + '/dist/', filename: 'bundle.js', publicPath: 'http://localhost:2992/', contentBase: __dirname + '/public/' } var excludeFromStats = [ /node_modules[\\\/]react(-router)?[\\\/]/ ] var plugins = [ new webpack.PrefetchPlugin('react'), new webpack.PrefetchPlugin('react/lib/ReactComponentBrowserEnvironment') ] if (opts.prerender) { plugins.push(new StatsPlugin(path.join(__dirname, 'dist', 'stats.prerender.json'), { chunkModules: true, exclude: excludeFromStats })); aliasLoader['react-proxy$'] = 'react-proxy/unavailable'; aliasLoader['react-proxy-loader$'] = 'react-proxy-loader/unavailable'; externals.push( /^react(\/.*)?$/, /^reflux(\/.*)?$/, 'superagent', 'async' ); plugins.push(new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 })); } else { plugins.push(new StatsPlugin(path.join(__dirname, 'dist', 'stats.json'), { chunkModules: true, exclude: excludeFromStats })); } if (opts.commonsChunk) { plugins.push(new webpack.optimize.CommonsChunkPlugin('commons', 'commons.js' + (opts.longTermCaching && !opts.prerender ? '?[chunkhash]' : ''))) } var asyncLoader = { test: require('./app/routes/async').map(function(name) { return path.join(__dirname, 'app', 'routes', name); }), loader: opts.prerender ? 'react-proxy-loader/unavailable' : 'react-proxy-loader' } Object.keys(stylesheetLoaders).forEach(function(ext) { var stylesheetLoader = stylesheetLoaders[ext]; if(Array.isArray(stylesheetLoader)) stylesheetLoader = stylesheetLoader.join('!'); if (opts.prerender) { stylesheetLoaders[ext] = stylesheetLoader.replace(/^css-loader/, 'css-loader/locals'); } else if (opts.separateStylesheet) { stylesheetLoaders[ext] = ExtractTextPlugin.extract('style-loader', stylesheetLoader); } else { stylesheetLoaders[ext] = 'style-loader!' + stylesheetLoader; } }) if (opts.separateStylesheet && !opts.prerender) { plugins.push(new ExtractTextPlugin('[name].css' + (opts.longTermCaching ? '?[contenthash]' : ''))); } if (opts.minimize && !opts.prerender) { plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new webpack.optimize.DedupePlugin() ) } if (opts.minimize) { plugins.push( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: "'production'" } }), new webpack.NoErrorsPlugin() ) } var nodeModules = fs.readdirSync('node_modules').filter(function(x) { return x !== '.bin' }) return { entry: entry, output: output, target: 'atom', externals: nodeModules, module: { loaders: [asyncLoader].concat(loadersByExtension(loaders)).concat(loadersByExtension(stylesheetLoaders)).concat(additionalLoaders) }, devtool: opts.devtool, debug: opts.debug, resolve: { root: root, modulesDirectories: modulesDirectories, extensions: extensions, alias: alias }, plugins: plugins, devServer: { stats: { cached: false, exclude: excludeFromStats } } } }
JavaScript
0.000014
@@ -1788,16 +1788,48 @@ public/' +,%0A libraryTarget: 'commonjs2' %0A %7D%0A%0A
68cb89aa0b535efbf04e80c6dd07e16523759ac4
add windows test conflict
scripts/dataentry.js
scripts/dataentry.js
/** * dataentry.js a dummy input data entry * * Copyright 2014 Nahuel Soldevilla * Released under the MIT license. * * > dt = DataEntry.makeDataEntry() // make new object * > dt.attachType("input") // attach to input element * */ (function( window ) { var // http://www.kipdola.be/en/blog/skerit/120-keycode-array-javascript // A var storing all useful keys for easy access (modified) key = { 8 : 'Backspace', 9 : 'Tab', 13 : 'Enter', 16 : 'Shift', 17 : 'Ctrl', 18 : 'Alt', 19 : 'Pause', 20 : 'Capslock', 27 : 'Esc', 32 : 'Backspace', 33 : 'Pageup', 34 : 'Pagedown', 35 : 'End', 36 : 'Home', 37 : 'Leftarrow', 38 : 'Uparrow', 39 : 'Rightarrow', 40 : 'Downarrow', 45 : 'Insert', 46 : 'Delete', 48 : '0', 49 : '1', 50 : '2', 51 : '3', 52 : '4', 53 : '5', 54 : '6', 55 : '7', 56 : '8', 57 : '9', 65 : 'a', 66 : 'b', 67 : 'c', 68 : 'd', 69 : 'e', 70 : 'f', 71 : 'g', 72 : 'h', 73 : 'i', 74 : 'j', 75 : 'k', 76 : 'l', 77 : 'm', 78 : 'n', 79 : 'o', 80 : 'p', 81 : 'q', 82 : 'r', 83 : 's', 84 : 't', 85 : 'u', 86 : 'v', 87 : 'w', 88 : 'x', 89 : 'y', 90 : 'z', 96 : '0numpad', 97 : '1numpad', 98 : '2numpad', 99 : '3numpad', 100 : '4numpad', 101 : '5numpad', 102 : '6numpad', 103 : '7numpad', 104 : '8numpad', 105 : '9numpad', 106 : 'Multiply', 107 : 'Plus', 109 : 'Minut', 110 : 'Dot', 111 : 'Slash1', 112 : 'F1', 113 : 'F2', 114 : 'F3', 115 : 'F4', 116 : 'F5', 117 : 'F6', 118 : 'F7', 119 : 'F8', 120 : 'F9', 121 : 'F10', 122 : 'F11', 123 : 'F12', 187 : 'equal', 188 : 'Coma', 191 : 'Slash', 220 : 'Backslash' }, // get size of object proerties getSize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }, // perform callback and set timeout typeProcess = function (callback, process_id_obj) { var that = this; process_id_obj.id = setTimeout(function () { callback(); that.time = Math.floor((that.MIN_TIME + Math.random() * (that.MAX_TIME - that.MIN_TIME ) )); typeProcess.apply(that, [callback, process_id_obj]); }, this.time); }; DataEntry = function (time) { if (time) { this.time = time; } }; DataEntry.fn = DataEntry.prototype = { // max time elapsed between keystrokes MAX_TIME: 250, // min time elapsed between keystrokes MIN_TIME : 150, // id of background process process_ids: [], // time to next keystroke time: 0, // get random character type : function () { return String.fromCharCode(Math.floor((Math.random()*getSize(key))+1)); }, // get random char code typeCharCode : function () { return Math.floor((Math.random()*getSize(key))+1); }, // attach input ant start typing attachType: function (inputId) { if (!inputId) { return; } var process_id_obj = {}; that = this; var input = document.getElementById(inputId); typeProcess.apply(this, [function () { input.value = input.value + that.type(); }, process_id_obj]); // save to delete later this.process_ids.push(process_id_obj); }, // stop typing stop: function () { for (var i = 0; i < this.process_ids.length; i++) { clearTimeout(this.process_ids[i].id); } }, // delete content attachDelete: function (inputId) { if (!inputId) { return; } var process_id_obj = {}; var input = document.getElementById(inputId); typeProcess.apply(this, [function () { input.value = input.value.substring(0, input.value.length - 1); }, process_id_obj]); // save to delete later this.process_ids.push(process_id_obj); }, }; DataEntry.makeDataEntry = function (time) { return new DataEntry(time); }; window.DataEntry = DataEntry; }(window)); // vim:set ts=2 sw=2 sts=2 expandtab:
JavaScript
0.000001
@@ -1112,16 +1112,33 @@ : 'z', + 91 : 'windows', 96 : '
a11e0c63be45689a022dc54840f722a502a4522a
Disable variantGrouping experiment
src/featureFlags.js
src/featureFlags.js
import colors from 'picocolors' import log from './util/log' let defaults = { optimizeUniversalDefaults: false, } let featureFlags = { future: ['hoverOnlyWhenSupported', 'respectDefaultRingColorOpacity'], experimental: ['optimizeUniversalDefaults', 'variantGrouping', 'matchVariant'], } export function flagEnabled(config, flag) { if (featureFlags.future.includes(flag)) { return config.future === 'all' || (config?.future?.[flag] ?? defaults[flag] ?? false) } if (featureFlags.experimental.includes(flag)) { return ( config.experimental === 'all' || (config?.experimental?.[flag] ?? defaults[flag] ?? false) ) } return false } function experimentalFlagsEnabled(config) { if (config.experimental === 'all') { return featureFlags.experimental } return Object.keys(config?.experimental ?? {}).filter( (flag) => featureFlags.experimental.includes(flag) && config.experimental[flag] ) } export function issueFlagNotices(config) { if (process.env.JEST_WORKER_ID !== undefined) { return } if (experimentalFlagsEnabled(config).length > 0) { let changes = experimentalFlagsEnabled(config) .map((s) => colors.yellow(s)) .join(', ') log.warn('experimental-flags-enabled', [ `You have enabled experimental features: ${changes}`, 'Experimental features in Tailwind CSS are not covered by semver, may introduce breaking changes, and can change at any time.', ]) } } export default featureFlags
JavaScript
0.000001
@@ -255,40 +255,47 @@ ', ' -variantGrouping', 'matchVariant' +matchVariant' /* , 'variantGrouping' */ %5D,%0A%7D
05a947d0e796eef488d5777096d81fc4dcb7d54c
Replace padding width calculation
src/strand-list-item/strand-list-item.js
src/strand-list-item/strand-list-item.js
/** * @license * Copyright (c) 2015 MediaMath Inc. All rights reserved. * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt */ (function (scope) { scope.ListItem = Polymer({ is: "strand-list-item", behaviors: [ StrandTraits.Resolvable, StrandTraits.DomMutable, StrandTraits.Refable ], properties: { selected: { type: Boolean, value: false, reflectToAttribute: true, notify: true }, highlighted: { type: Boolean, value: false, reflectToAttribute: true, notify: true, }, highlight:{ type:String, value:"", notify:true, observer:"_highlightChanged" }, observeSubtree: { value:true }, observeCharacterData: { value:true }, title: { type:String, value:null, reflectToAttribute: true }, value: { type: String, value: false } }, listeners:{ "added":"_updateTitleHandler", "removed":"_updateTitleHandler", "modified":"_updateTitleHandler", "mouseover":"_updateTitleHandler" }, attached: function () { this.debounce("update-title",this.updateTitle,0); }, _updateTitleHandler: function() { this.debounce("update-title",this.updateTitle,0); }, _highlightChanged: function() { if (this.highlight && this.highlight.length > 0) { var s = this.innerText; Polymer.dom(this).innerHTML = s.replace(new RegExp(this.highlight,"ig"),function(orig) { return '<span class="strand-list-item highlight">'+orig+'</span>'; },'ig'); } else if (this.innerText && this.innerText.trim()){ Polymer.dom(this).innerHTML = this.innerText.trim(); //strip any formatting } }, updateTitle: function() { var m = StrandLib.Measure; var computed = m.textWidth(this, this.textContent); var padding = parseInt(getComputedStyle(this).paddingLeft.split('px')[0]) + parseInt(getComputedStyle(this).paddingRight.split('px')[0]); var actual = m.getBoundingClientRect(this).width - padding; if (computed > actual) { var txt = this.textContent.trim(); if (this.title !== txt) this.title = txt; } else { this.title = null; } } }); })(window.Strand = window.Strand || {});
JavaScript
0.000003
@@ -205,16 +205,51 @@ cope) %7B%0A +%09var Measure = StrandLib.Measure;%0A%0A %09scope.L @@ -1859,149 +1859,8 @@ t);%0A -%09%09%09var padding = parseInt(getComputedStyle(this).paddingLeft.split('px')%5B0%5D) + parseInt(getComputedStyle(this).paddingRight.split('px')%5B0%5D);%0A %09%09%09v @@ -1913,15 +1913,37 @@ h - -padding +Measure.getPaddingWidth(this) ;%0A%09%09
d123bea8c1a4f1c977928fa2cfffe19132f74dab
Change Animated's Flow Type to require useNativeDriver be explicit
Libraries/Animated/src/animations/Animation.js
Libraries/Animated/src/animations/Animation.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; const NativeAnimatedHelper = require('../NativeAnimatedHelper'); import type AnimatedValue from '../nodes/AnimatedValue'; export type EndResult = {finished: boolean}; export type EndCallback = (result: EndResult) => void | Promise<void>; export type AnimationConfig = { isInteraction?: boolean, useNativeDriver?: boolean, onComplete?: ?EndCallback, iterations?: number, }; // Important note: start() and stop() will only be called at most once. // Once an animation has been stopped or finished its course, it will // not be reused. class Animation { __active: boolean; __isInteraction: boolean; __nativeId: number; __onEnd: ?EndCallback; __iterations: number; start( fromValue: number, onUpdate: (value: number) => void, onEnd: ?EndCallback, previousAnimation: ?Animation, animatedValue: AnimatedValue, ): void {} stop(): void { if (this.__nativeId) { NativeAnimatedHelper.API.stopAnimation(this.__nativeId); } } __getNativeAnimationConfig(): any { // Subclasses that have corresponding animation implementation done in native // should override this method throw new Error('This animation type cannot be offloaded to native'); } // Helper function for subclasses to make sure onEnd is only called once. __debouncedOnEnd(result: EndResult): void { const onEnd = this.__onEnd; this.__onEnd = null; onEnd && onEnd(result); } __startNativeAnimation(animatedValue: AnimatedValue): void { NativeAnimatedHelper.API.enableQueue(); animatedValue.__makeNative(); NativeAnimatedHelper.API.disableQueue(); this.__nativeId = NativeAnimatedHelper.generateNewAnimationId(); NativeAnimatedHelper.API.startAnimatingNode( this.__nativeId, animatedValue.__getNativeTag(), this.__getNativeAnimationConfig(), this.__debouncedOnEnd.bind(this), ); } } module.exports = Animation;
JavaScript
0.000001
@@ -537,17 +537,16 @@ veDriver -? : boolea
e18c127ac9c7d2ae47367949131c93afb492ff66
implement 'warning' prop
src/components/datepicker/DatePickerInput.js
src/components/datepicker/DatePickerInput.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box, { omitBoxProps, pickBoxProps } from '../box'; import DayPickerInput from 'react-day-picker/DayPickerInput'; import Icon from '../icon'; import NavigationBar from './NavigationBar'; import WeekDay from './WeekDay'; import { convertModifiersToClassnames } from './utils'; import { IconCalendarSmallOutline } from '@teamleader/ui-icons'; import ValidationText from '../validationText'; import cx from 'classnames'; import omit from 'lodash.omit'; import theme from './theme.css'; class DatePickerInput extends PureComponent { state = { inputHasFocus: false, selectedDate: null, }; static getDerivedStateFromProps(props, state) { if (props.selectedDate !== undefined && props.selectedDate !== state.selectedDate) { return { selectedDate: props.selectedDate, }; } return null; } handleBlur = () => { this.setState({ inputHasFocus: false }, () => this.props.onBlur && this.props.onBlur()); }; handleFocus = () => { this.setState({ inputHasFocus: true }, () => this.props.onFocus && this.props.onFocus()); }; handleInputDateChange = (date, modifiers = {}) => { if (modifiers.disabled) { return; } this.setState({ selectedDay: date }, () => this.props.onChange(date)); }; renderDayPickerInput = () => { const { className, dayPickerProps, disabled, inputProps, modifiers, readOnly, size, ...others } = this.props; const { selectedDate } = this.state; const dayPickerClassNames = cx(theme['date-picker'], theme[`is-${size}`], className); const propsWithoutBoxProps = omitBoxProps(others); const restProps = omit(propsWithoutBoxProps, ['helpText', 'onBlur', 'onChange', 'onFocus', 'inputProps']); return ( <DayPickerInput classNames={theme} dayPickerProps={{ className: dayPickerClassNames, classNames: theme, modifiers: convertModifiersToClassnames(modifiers, theme), selectedDays: selectedDate, navbarElement: <NavigationBar size={size} />, weekdayElement: <WeekDay size={size} />, ...dayPickerProps, }} onDayChange={this.handleInputDateChange} hideOnDayClick={false} inputProps={{ disabled: disabled || readOnly, onBlur: this.handleBlur, onFocus: this.handleFocus, ...inputProps, }} {...restProps} /> ); }; renderIcon = () => { const { inverse } = this.props; return ( <Icon className={theme['input-icon']} color={inverse ? 'teal' : 'neutral'} tint={inverse ? 'light' : 'darkest'} marginHorizontal={2} > <IconCalendarSmallOutline /> </Icon> ); }; render() { const { bold, disabled, error, helpText, inverse, readOnly, size, ...others } = this.props; const { inputHasFocus } = this.state; const boxProps = pickBoxProps(others); const classNames = cx(theme['date-picker-input'], theme[`is-${size}`], { [theme['is-bold']]: bold, [theme['is-disabled']]: disabled, [theme['is-inverse']]: inverse, [theme['is-read-only']]: readOnly, [theme['has-error']]: error, [theme['has-focus']]: inputHasFocus, }); return ( <Box className={classNames} {...boxProps}> <div className={theme['input-wrapper']}> {this.renderIcon()} {this.renderDayPickerInput()} </div> <ValidationText error={error} help={helpText} inverse={inverse} /> </Box> ); } } DatePickerInput.propTypes = { bold: PropTypes.bool, className: PropTypes.string, dayPickerProps: PropTypes.object, disabled: PropTypes.bool, /** The text string/element to use as error message below the input. */ error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), helpText: PropTypes.string, inputProps: PropTypes.object, inverse: PropTypes.bool, modifiers: PropTypes.object, /** Callback function that is fired when blurring the input field. */ onBlur: PropTypes.func, onChange: PropTypes.func, /** Callback function that is fired when focussing the input field. */ onFocus: PropTypes.func, readOnly: PropTypes.bool, selectedDate: PropTypes.instanceOf(Date), size: PropTypes.oneOf(['small', 'medium', 'large']), }; DatePickerInput.defaultProps = { bold: false, disabled: false, inverse: false, readOnly: false, size: 'medium', }; export default DatePickerInput;
JavaScript
0.998896
@@ -2891,32 +2891,41 @@ readOnly, size, + warning, ...others %7D = t @@ -2927,32 +2927,32 @@ %7D = this.props;%0A - const %7B inpu @@ -3324,24 +3324,63 @@ utHasFocus,%0A + %5Btheme%5B'has-warning'%5D%5D: warning,%0A %7D);%0A%0A @@ -3643,16 +3643,34 @@ inverse%7D + warning=%7Bwarning%7D /%3E%0A @@ -4402,16 +4402,16 @@ (Date),%0A - size: @@ -4457,16 +4457,148 @@ rge'%5D),%0A + /** The text to use as warning message below the input. */%0A warning: PropTypes.oneOfType(%5BPropTypes.string, PropTypes.element%5D),%0A %7D;%0A%0ADate
6daddf8e7ea1c0b7d48cf6e5b785e343092a4ee2
Change wording.
commons/CitationModal.js
commons/CitationModal.js
import { $$, Component } from '../dom' import { Form, FormRow, Modal, MultiSelect } from '../ui' export default class CitationModal extends Component { getInitialState () { const { mode, node } = this.props const value = mode === 'edit' ? node.references : [] return { value } } render () { const { document, mode } = this.props const { value } = this.state const confirmLabel = mode === 'edit' ? 'Update' : 'Create' const title = mode === 'edit' ? 'Edit Citation' : 'Create Citation' const root = document.root const referencesList = root.resolve('references') const disableConfirm = value.length === 0 const modalProps = { title, cancelLabel: 'Cancel', confirmLabel, disableConfirm, size: 'large' } return $$(Modal, modalProps, $$(Form, {}, $$(FormRow, {}, $$(MultiSelect, { options: referencesList.map(ref => { return { value: ref.id, label: ref.content } }), value, label: 'Add Reference', placeholder: 'Please select one or more references', onchange: this._updateReferencess }).ref('references') ) ) ) } _updateReferencess () { const value = this.refs.references.val() this.extendState({ value }) } }
JavaScript
0.000001
@@ -1019,11 +1019,14 @@ l: ' -Add +Select Ref
3184bfa7bd52cc6d9231d1956a45136ba3d4b600
Fix 'file not found' when loading translation files.
app/js/translations.js
app/js/translations.js
const i18next = require('i18next'); const i18nextXHRBackend = require('i18next-xhr-backend'); const jqueryI18next = require('jquery-i18next'); i18next .use(i18nextXHRBackend) .init({ fallbackLng: 'en-US', debug: false, ns: ['deimos-issuer'], defaultNS: 'deimos-issuer', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { jqueryI18next.init(i18next, $); $('body').localize(); $('#language').change(function() { i18next.changeLanguage($('#language').val(), function() { ipcRenderer.send('language-change', $('#language').val()); $('body').localize(); }); }); }); function loadTranslations() { const language = remote.getGlobal('settings').language; $('#language').val(language); $('#language').trigger('change'); }
JavaScript
0
@@ -177,16 +177,51 @@ .init(%7B%0A + whitelist: %5B'en-US', 'pt-BR'%5D,%0A fall
a8f4e4e72c2197b852f9328f19e4b68a48400f97
fix alias pointing to self
addon/index.js
addon/index.js
import Ember from 'ember'; import WidgetCollection from 'ember-eureka/widget-collection'; import QueryParametrableWidgetMixin from 'eureka-mixin-query-parametrable-widget'; export default WidgetCollection.extend(QueryParametrableWidgetMixin, { /** set the queryParam (used for the QueryParametrableWidgetMixin), * to the widget's `config.filter.queryParam` */ 'config.queryParam': Ember.computed.alias('config.filter.queryParam'), modelRoute: Ember.computed.alias('modelRoute'), /** Make the filterTerm a queryParam if configured in `config` */ filterTerm: Ember.computed.alias('queryParam'), /** if true, display the input filter */ filterEnabled: Ember.computed.bool('config.filter'), emptyPlaceholder: Ember.computed.alias('config.emptyPlaceholder'), /** update the `routeModel.query` from `filterTerm` */ updateQuery: function() { var filterTerm = this.get('filterTerm'); var query = this.getWithDefault('routeModel.query.raw'); if (filterTerm) { query['title[$iregex]'] = '^'+filterTerm; } else { query['title[$iregex]'] = undefined; filterTerm = null; } this.set('routeModel.query.raw', query); }, label: function() { var _label = this.get('config.label'); if (_label === 'auto') { return this.get('resource'); } return _label; }.property('config.label', 'resource'), queryConfig: function() { var query = this.get('config.query'); if (query) { query = JSON.parse(query); } else { query = {}; } return query; }.property('config.query'), /** update the collection from the `routeModel.query` */ collection: function() { var queryConfig = this.get('queryConfig'); var routeQuery = this.get('routeModel.query.raw'); Ember.setProperties(routeQuery, queryConfig); return this.get('store').find(routeQuery); }.property('routeModel.query.hasChanged', 'queryConfig', 'store'), /** update the query when the user hit the enter key */ keyPress: function(e) { if (e.keyCode === 13) { this.updateQuery(); } }, actions: { clear: function() { this.set('filterTerm', null); this.updateQuery(); } } });
JavaScript
0.000002
@@ -451,61 +451,8 @@ ),%0A%0A - modelRoute: Ember.computed.alias('modelRoute'),%0A%0A
4dbbeacbc26c74a254b4a2056ced599602060d7f
Simplify timeSince calculation
client/actions/show-heartbeat/index.js
client/actions/show-heartbeat/index.js
import { Action, registerAction } from '../utils'; const VERSION = 55; // Increase when changed. // how much time should elapse between heartbeats? const HEARTBEAT_THROTTLE = 1000 * 60 * 60 * 24; // 24 hours export default class ShowHeartbeatAction extends Action { constructor(normandy, recipe) { super(normandy, recipe); // 'local' storage // (namespaced to recipe.id - only this heartbeat can access) this.storage = normandy.createStorage(recipe.id); // 'global' storage // (constant namespace - all heartbeats can access) this.heartbeatStorage = normandy.createStorage('normandy-heartbeat'); } /** * Calculates the number of milliseconds since the last heartbeat from any recipe * was shown. Returns a boolean indicating if a heartbeat has been shown recently. */ async heartbeatShownRecently() { const lastShown = await this.heartbeatStorage.getItem('lastShown'); let timeSince = Infinity; // If no heartbeat has ever been shown, lastShown will be falsey. if (lastShown) { timeSince = new Date() - lastShown; } // Return a boolean indicating if a heartbeat // has shown within the last HEARTBEAT_THROTTLE ms return timeSince < HEARTBEAT_THROTTLE; } /** * Checks when this survey was last shown, * and returns a boolean indicating if the * user has seen this survey already or not. */ async surveyHasShown() { const lastShown = await this.storage.getItem('lastShown'); // If no survey has been shown, lastShown will be falsey. return !!lastShown; } async execute() { const { surveyId, message, engagementButtonLabel, thanksMessage, postAnswerUrl, learnMoreMessage, learnMoreUrl, } = this.recipe.arguments; if (!this.normandy.testing && ( await this.heartbeatShownRecently() || await this.surveyHasShown() )) { return; } this.location = await this.normandy.location(); this.client = await this.normandy.client(); let userId; let heartbeatSurveyId = surveyId; // should user ID stuff be sent to telemetry? const { includeTelemetryUUID } = this.recipe.arguments; if (includeTelemetryUUID) { // get the already-defined UUID from normandy userId = this.normandy.userId; // if a userId exists, if (userId) { // alter the survey ID to include that UUID heartbeatSurveyId = `${surveyId}::${userId}`; } } // A bit redundant but the action argument names shouldn't necessarily rely // on the argument names showHeartbeat takes. const heartbeatData = { surveyId: heartbeatSurveyId, message, engagementButtonLabel, thanksMessage, postAnswerUrl: this.annotatePostAnswerUrl({ url: postAnswerUrl, userId, }), learnMoreMessage, learnMoreUrl, flowId: this.normandy.uuid(), surveyVersion: this.recipe.revision_id, }; if (this.normandy.testing) { heartbeatData.testing = 1; } await this.normandy.showHeartbeat(heartbeatData); this.setLastShownDate(); // and save the 'global' record that a heartbeat just played this.setLastHeartbeatDate(); } setLastShownDate() { // Returns a promise, but there's nothing to do if it fails. this.storage.setItem('lastShown', Date.now()); } setLastHeartbeatDate() { this.heartbeatStorage.setItem('lastShown', Date.now()); } async getLastShownDate() { const lastShown = await this.storage.getItem('lastShown'); return Number.isNaN(lastShown) ? null : lastShown; } async getLastHeartbeatDate() { const lastShown = await this.heartbeatStorage.getItem('lastShown'); return Number.isNaN(lastShown) ? null : lastShown; } /** * Gathers recipe action/message information, and formats the content into * URL-safe query params. This is used by this.annotatePostAnswerUrl to * inject Google Analytics params into the post-answer URL. * * @return {Object} Hash containing utm_ queries to append to post-answer URL */ getGAParams() { let message = this.recipe.arguments.message || ''; // remove spaces message = message.replace(/\s+/g, ''); // escape what we can message = encodeURIComponent(message); // use a fake URL object to get a legit URL-ified URL const fakeUrl = new URL('http://mozilla.com'); fakeUrl.searchParams.set('message', message); // pluck the (now encoded) message message = fakeUrl.search.replace('?message=', ''); return { utm_source: 'firefox', utm_medium: this.recipe.action, // action name utm_campaign: message, // 'shortenedmesssagetext' }; } annotatePostAnswerUrl({ url, userId }) { // Don't bother with empty URLs. if (!url) { return url; } const args = { source: 'heartbeat', surveyversion: VERSION, updateChannel: this.client.channel, fxVersion: this.client.version, isDefaultBrowser: this.client.isDefaultBrowser ? 1 : 0, searchEngine: this.client.searchEngine, syncSetup: this.client.syncSetup ? 1 : 0, // Google Analytics parameters ...this.getGAParams(), }; // if a userId is given, // we'll include it with the data passed through // to SurveyGizmo (via query params) if (userId) { args.userId = userId; } // Append testing parameter if in testing mode. if (this.normandy.testing) { args.testing = 1; } const annotatedUrl = new URL(url); for (const key in args) { if (!args.hasOwnProperty(key)) { continue; } annotatedUrl.searchParams.set(key, args[key]); } return annotatedUrl.href; } } registerAction('show-heartbeat', ShowHeartbeatAction);
JavaScript
0.00036
@@ -921,18 +921,20 @@ ');%0A -le +cons t timeSi @@ -943,127 +943,19 @@ e = -Infinity;%0A%0A // If no heartbeat has ever been shown, lastShown will be falsey.%0A if (lastShown) %7B%0A timeSince = +lastShown ? new @@ -973,23 +973,28 @@ astShown -;%0A %7D + : Infinity; %0A%0A //
8216df917229c4e210f530339ecd6c7c239861b3
update routes.js
config/routes.js
config/routes.js
var routes = function(config, pages) { var tags; tags = config.tags; routes = []; // tags tags.forEach(function(tag) { routes.push({ data: { tag: tag }, template: "tag.jade", target: "tags/" + tag + ".html" }); }); // articles pages.forEach(function(page) { routes.push({ data: { page: page }, template: "page.jade", target: "" + page.path + ".html" }); }); // feed routes.push({ data: { pages: pages }, template: "atom.jade", target: "atom.xml" }); // index.json routes.push({ data: { pages: pages }, template: "index.json.jade", target: "index.json" }); return routes; }; module.exports = routes;
JavaScript
0.000002
@@ -507,13 +507,8 @@ get: - %22%22 + pag
3f646f13dde68f0314936c26c8a1074ab616bb89
Add option to change the default country code
src/components/views/auth/CountryDropdown.js
src/components/views/auth/CountryDropdown.js
/* Copyright 2017 Vector Creations Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import sdk from '../../../index'; import { COUNTRIES } from '../../../phonenumber'; const COUNTRIES_BY_ISO2 = {}; for (const c of COUNTRIES) { COUNTRIES_BY_ISO2[c.iso2] = c; } function countryMatchesSearchQuery(query, country) { // Remove '+' if present (when searching for a prefix) if (query[0] === '+') { query = query.slice(1); } if (country.name.toUpperCase().indexOf(query.toUpperCase()) == 0) return true; if (country.iso2 == query.toUpperCase()) return true; if (country.prefix.indexOf(query) !== -1) return true; return false; } export default class CountryDropdown extends React.Component { constructor(props) { super(props); this._onSearchChange = this._onSearchChange.bind(this); this._onOptionChange = this._onOptionChange.bind(this); this._getShortOption = this._getShortOption.bind(this); this.state = { searchQuery: '', }; } componentWillMount() { if (!this.props.value) { // If no value is given, we start with the first // country selected, but our parent component // doesn't know this, therefore we do this. this.props.onOptionChange(COUNTRIES[0]); } } _onSearchChange(search) { this.setState({ searchQuery: search, }); } _onOptionChange(iso2) { this.props.onOptionChange(COUNTRIES_BY_ISO2[iso2]); } _flagImgForIso2(iso2) { return <img src={require(`../../../../res/img/flags/${iso2}.png`)} />; } _getShortOption(iso2) { if (!this.props.isSmall) { return undefined; } let countryPrefix; if (this.props.showPrefix) { countryPrefix = '+' + COUNTRIES_BY_ISO2[iso2].prefix; } return <span className="mx_CountryDropdown_shortOption"> { this._flagImgForIso2(iso2) } { countryPrefix } </span>; } render() { const Dropdown = sdk.getComponent('elements.Dropdown'); let displayedCountries; if (this.state.searchQuery) { displayedCountries = COUNTRIES.filter( countryMatchesSearchQuery.bind(this, this.state.searchQuery), ); if ( this.state.searchQuery.length == 2 && COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()] ) { // exact ISO2 country name match: make the first result the matches ISO2 const matched = COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()]; displayedCountries = displayedCountries.filter((c) => { return c.iso2 != matched.iso2; }); displayedCountries.unshift(matched); } } else { displayedCountries = COUNTRIES; } const options = displayedCountries.map((country) => { return <div className="mx_CountryDropdown_option" key={country.iso2}> { this._flagImgForIso2(country.iso2) } { country.name } (+{ country.prefix }) </div>; }); // default value here too, otherwise we need to handle null / undefined // values between mounting and the initial value propgating const value = this.props.value || COUNTRIES[0].iso2; return <Dropdown className={this.props.className + " mx_CountryDropdown"} onOptionChange={this._onOptionChange} onSearchChange={this._onSearchChange} menuWidth={298} getShortOption={this._getShortOption} value={value} searchEnabled={true} disabled={this.props.disabled} > { options } </Dropdown>; } } CountryDropdown.propTypes = { className: PropTypes.string, isSmall: PropTypes.bool, // if isSmall, show +44 in the selected value showPrefix: PropTypes.bool, onOptionChange: PropTypes.func.isRequired, value: PropTypes.string, disabled: PropTypes.bool, };
JavaScript
0.000001
@@ -709,16 +709,60 @@ number'; +%0Aimport SdkConfig from %22../../../SdkConfig%22; %0A%0Aconst @@ -1551,24 +1551,345 @@ ind(this);%0A%0A + let defaultCountry = COUNTRIES%5B0%5D;%0A if (SdkConfig.get()%5B%22defaultCountryCode%22%5D) %7B%0A const country = COUNTRIES.find(c =%3E c.iso2 === SdkConfig.get()%5B%22defaultCountryCode%22%5D);%0A if (country) defaultCountry = country;%0A %7D%0A console.log(defaultCountry);%0A console.log(props);%0A this @@ -1895,24 +1895,24 @@ s.state = %7B%0A - @@ -1928,16 +1928,44 @@ ry: '',%0A + defaultCountry,%0A @@ -2089,20 +2089,22 @@ ith the -firs +defaul t%0A @@ -2249,28 +2249,41 @@ nChange( -COUNTRIES%5B0%5D +this.state.defaultCountry );%0A @@ -4404,28 +4404,41 @@ alue %7C%7C -COUNTRIES%5B0%5D +this.state.defaultCountry .iso2;%0A%0A
f98b2f74a13ef8d610900d7feb1f9f4e218662dc
Stop Using Promise#finally
src/network/fetchRelayQuery.js
src/network/fetchRelayQuery.js
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule fetchRelayQuery * @typechecks * @flow */ 'use strict'; var Promise = require('Promise'); var RelayNetworkLayer = require('RelayNetworkLayer'); var RelayProfiler = require('RelayProfiler'); var RelayQueryRequest = require('RelayQueryRequest'); import type RelayQuery from 'RelayQuery'; var resolveImmediate = require('resolveImmediate'); var queue: ?Array<RelayQueryRequest> = null; /** * @internal * * Schedules the supplied `query` to be sent to the server. * * This is a low-level transport API; application code should use higher-level * interfaces exposed by RelayContainer for retrieving data transparently via * queries defined on components. */ function fetchRelayQuery(query: RelayQuery.Root): Promise { if (!queue) { queue = []; var currentQueue = queue; resolveImmediate(() => { queue = null; profileQueue(currentQueue); processQueue(currentQueue); }); } var request = new RelayQueryRequest(query); queue.push(request); return request.getPromise(); } function processQueue(currentQueue: Array<RelayQueryRequest>): void { RelayNetworkLayer.sendQueries(currentQueue); } /** * Profiles time from request to receiving the first server response. */ function profileQueue(currentQueue: Array<RelayQueryRequest>): void { // TODO #8783781: remove aggregate `fetchRelayQuery` profiler var firstResultProfiler = RelayProfiler.profile('fetchRelayQuery'); currentQueue.forEach(query => { var profiler = RelayProfiler.profile('fetchRelayQuery.query'); query.getPromise().finally(() => { profiler.stop(); if (firstResultProfiler) { firstResultProfiler.stop(); firstResultProfiler = null; } }); }); } module.exports = fetchRelayQuery;
JavaScript
0.000001
@@ -373,19 +373,21 @@ rict';%0A%0A -var +const Promise @@ -405,27 +405,29 @@ 'Promise');%0A -var +const RelayNetwor @@ -461,27 +461,29 @@ orkLayer');%0A -var +const RelayProfil @@ -513,19 +513,21 @@ iler');%0A -var +const RelayQu @@ -612,19 +612,21 @@ uery';%0A%0A -var +const resolve @@ -667,19 +667,19 @@ ate');%0A%0A -var +let queue: @@ -1087,19 +1087,21 @@ %5B%5D;%0A -var +const current @@ -1246,19 +1246,21 @@ ;%0A %7D%0A -var +const request @@ -1683,19 +1683,19 @@ filer%0A -var +let firstRe @@ -1793,11 +1793,13 @@ -var +const pro @@ -1862,35 +1862,25 @@ -query.getPromise().finally( +const onSettle = () = @@ -2020,24 +2020,72 @@ %7D%0A %7D +;%0A query.getPromise().done(onSettle, onSettle );%0A %7D);%0A%7D%0A%0A
3064cdd3712d2014b0e340dc04faa1efa34b209d
Update attachments.js
client/components/cards/attachments.js
client/components/cards/attachments.js
Template.attachmentsGalery.events({ 'click .js-add-attachment': Popup.open('cardAttachments'), 'click .js-confirm-delete': Popup.afterConfirm( 'attachmentDelete', function() { Attachments.remove(this._id); Popup.close(); }, ), // If we let this event bubble, FlowRouter will handle it and empty the page // content, see #101. 'click .js-download'(event) { event.stopPropagation(); }, 'click .js-add-cover'() { Cards.findOne(this.cardId).setCover(this._id); }, 'click .js-remove-cover'() { Cards.findOne(this.cardId).unsetCover(); }, 'click .js-preview-image'(event) { Popup.open('previewAttachedImage').call(this, event); // when multiple thumbnails, if click one then another very fast, // we might get a wrong width from previous img. // when popup reused, onRendered() won't be called, so we cannot get there. // here make sure to get correct size when this img fully loaded. const img = $('img.preview-large-image')[0]; if (!img) return; const rePosPopup = () => { const w = img.width; const h = img.height; // if the image is too large, we resize & center the popup. if (w > 300) { $('div.pop-over').css({ width: w + 20, position: 'absolute', left: (window.innerWidth - w) / 2, top: (window.innerHeight - h) / 2, }); } }; const url = $(event.currentTarget).attr('src'); if (img.src === url && img.complete) rePosPopup(); else img.onload = rePosPopup; }, }); Template.previewAttachedImagePopup.events({ 'click .js-large-image-clicked'() { Popup.close(); }, }); Template.cardAttachmentsPopup.events({ 'change .js-attach-file'(event) { const card = this; const processFile = f => { Utils.processUploadedAttachment(card, f, attachment => { if (attachment && attachment._id && attachment.isImage()) { card.setCover(attachment._id); } Popup.close(); }); }; FS.Utility.eachFile(event, f => { if ( MAX_IMAGE_PIXEL > 0 && typeof f.type === 'string' && f.type.match(/^image/) ) { // is image const reader = new FileReader(); reader.onload = function(e) { const dataurl = e && e.target && e.target.result; if (dataurl !== undefined) { Utils.shrinkImage({ dataurl, maxSize: MAX_IMAGE_PIXEL, ratio: COMPRESS_RATIO, toBlob: true, callback(blob) { if (blob === false) { processFile(f); } else { blob.name = f.name; processFile(blob); } }, }); } else { // couldn't process it let other function handle it? processFile(f); } }; reader.readAsDataURL(f); } else { processFile(f); } }); }, 'click .js-computer-upload'(event, templateInstance) { templateInstance.find('.js-attach-file').click(); event.preventDefault(); }, 'click .js-upload-clipboard-image': Popup.open('previewClipboardImage'), }); const MAX_IMAGE_PIXEL = Utils.MAX_IMAGE_PIXEL; const COMPRESS_RATIO = Utils.IMAGE_COMPRESS_RATIO; let pastedResults = null; Template.previewClipboardImagePopup.onRendered(() => { // we can paste image from clipboard const handle = results => { if (results.dataURL.startsWith('data:image/')) { const direct = results => { $('img.preview-clipboard-image').attr('src', results.dataURL); pastedResults = results; }; if (MAX_IMAGE_PIXEL) { // if has size limitation on image we shrink it before uploading Utils.shrinkImage({ dataurl: results.dataURL, maxSize: MAX_IMAGE_PIXEL, ratio: COMPRESS_RATIO, callback(changed) { if (changed !== false && !!changed) { results.dataURL = changed; } direct(results); }, }); } } }; $(document.body).pasteImageReader(handle); // we can also drag & drop image file to it $(document.body).dropImageReader(handle); }); Template.previewClipboardImagePopup.events({ 'click .js-upload-pasted-image'() { const results = pastedResults; if (results && results.file) { window.oPasted = pastedResults; const card = this; const file = new FS.File(results.file); if (!results.name) { // if no filename, it's from clipboard. then we give it a name, with ext name from MIME type if (typeof results.file.type === 'string') { file.name(results.file.type.replace('image/', 'clipboard.')); } } file.updatedAt(new Date()); file.boardId = card.boardId; file.cardId = card._id; file.userId = Meteor.userId(); const attachment = Attachments.insert(file); if (attachment && attachment._id && attachment.isImage()) { card.setCover(attachment._id); } pastedResults = null; $(document.body).pasteImageReader(() => {}); Popup.close(); } }, });
JavaScript
0
@@ -4104,32 +4104,73 @@ %7D,%0A %7D);%0A + %7D else %7B%0A direct(results);%0A %7D%0A %7D%0A
18afebe15e431e8413dcc7ebdb1c00c80c15b7f0
remove manual controllerAs logic (#9462)
src/core/services/compiler/compiler.js
src/core/services/compiler/compiler.js
angular .module('material.core') .service('$mdCompiler', mdCompilerService); function mdCompilerService($q, $templateRequest, $injector, $compile, $controller) { /* jshint validthis: true */ /* * @ngdoc service * @name $mdCompiler * @module material.core * @description * The $mdCompiler service is an abstraction of angular's compiler, that allows the developer * to easily compile an element with a templateUrl, controller, and locals. * * @usage * <hljs lang="js"> * $mdCompiler.compile({ * templateUrl: 'modal.html', * controller: 'ModalCtrl', * locals: { * modal: myModalInstance; * } * }).then(function(compileData) { * compileData.element; // modal.html's template in an element * compileData.link(myScope); //attach controller & scope to element * }); * </hljs> */ /* * @ngdoc method * @name $mdCompiler#compile * @description A helper to compile an HTML template/templateUrl with a given controller, * locals, and scope. * @param {object} options An options object, with the following properties: * * - `controller` - `{(string=|function()=}` Controller fn that should be associated with * newly created scope or the name of a registered controller if passed as a string. * - `controllerAs` - `{string=}` A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` - `{string=}` An html template as a string. * - `templateUrl` - `{string=}` A path to an html template. * - `transformTemplate` - `{function(template)=}` A function which transforms the template after * it is loaded. It will be given the template string as a parameter, and should * return a a new string representing the transformed template. * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the compiler * will wait for them all to be resolved, or if one is rejected before the controller is * instantiated `compile()` will fail.. * * `key` - `{string}`: a name of a dependency to be injected into the controller. * * `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is injected and the return value is treated as the * dependency. If the result is a promise, it is resolved before its value is * injected into the controller. * * @returns {object=} promise A promise, which will be resolved with a `compileData` object. * `compileData` has the following properties: * * - `element` - `{element}`: an uncompiled element matching the provided template. * - `link` - `{function(scope)}`: A link function, which, when called, will compile * the element and instantiate the provided controller (if given). * - `locals` - `{object}`: The locals which will be passed into the controller once `link` is * called. If `bindToController` is true, they will be coppied to the ctrl instead * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in. */ this.compile = function(options) { var templateUrl = options.templateUrl; var template = options.template || ''; var controller = options.controller; var controllerAs = options.controllerAs; var resolve = angular.extend({}, options.resolve || {}); var locals = angular.extend({}, options.locals || {}); var transformTemplate = options.transformTemplate || angular.identity; var bindToController = options.bindToController; // Take resolve values and invoke them. // Resolves can either be a string (value: 'MyRegisteredAngularConst'), // or an invokable 'factory' of sorts: (value: function ValueGetter($dependency) {}) angular.forEach(resolve, function(value, key) { if (angular.isString(value)) { resolve[key] = $injector.get(value); } else { resolve[key] = $injector.invoke(value); } }); //Add the locals, which are just straight values to inject //eg locals: { three: 3 }, will inject three into the controller angular.extend(resolve, locals); if (templateUrl) { resolve.$template = $templateRequest(templateUrl) .then(function(response) { return response; }); } else { resolve.$template = $q.when(template); } // Wait for all the resolves to finish if they are promises return $q.all(resolve).then(function(locals) { var compiledData; var template = transformTemplate(locals.$template, options); var element = options.element || angular.element('<div>').html(template.trim()).contents(); var linkFn = $compile(element); // Return a linking function that can be used later when the element is ready return compiledData = { locals: locals, element: element, link: function link(scope) { locals.$scope = scope; //Instantiate controller if it exists, because we have scope if (controller) { var invokeCtrl = $controller(controller, locals, true); if (bindToController) { angular.extend(invokeCtrl.instance, locals); } var ctrl = invokeCtrl(); //See angular-route source for this logic element.data('$ngControllerController', ctrl); element.children().data('$ngControllerController', ctrl); if (controllerAs) { scope[controllerAs] = ctrl; } // Publish reference to this controller compiledData.controller = ctrl; } return linkFn(scope); } }; }); }; }
JavaScript
0
@@ -5343,16 +5343,30 @@ ls, true +, controllerAs );%0A @@ -5694,97 +5694,8 @@ );%0A%0A - if (controllerAs) %7B%0A scope%5BcontrollerAs%5D = ctrl;%0A %7D%0A%0A
cfb10193df8d55d1b3692d17360904e8db88732f
refactor functions to arrow
src/frontconsole.js
src/frontconsole.js
const FrontConsole = (userConfig, userTasks) => { let consoleDOM = {}; let consoleState = {}; const defaultConfig = { shortcutActivator: "ctrl", //options: "ctrl", "ctrl+shift", "ctrl+alt" shortcutKeyCode: 192 } const config = Object.assign( defaultConfig, userConfig ) const defaultTasks = { "echo": {//to be switched by backend command job: (params) => { console.log(params[0]); }, desc: "Returns provided parameter" }, "add": {//just for show job: (params) => { console.log(params[0] + params[1]); }, desc: "Simply adds to numbers passed as parameters" }, "clear": {//acually useful clientside command job: () => { console.log(`Clear the console`); }, desc: "Clears console" }, "help": {//acually useful clientside command job: () => displayHelp(), desc: "This help" }, //todo: "history" based on localstorage } const tasks = Object.assign( defaultTasks, userTasks ) const displayHelp = () => { Object.keys(tasks).forEach((key)=>{ const name = key; const desc = tasks[key].desc; console.log(`${name}: ${desc? desc : ""}`) }) } const keyDownHandler = function(event) { onKeyDown(event); } const onKeyDown = function(event){ let shortcutActivatorEnabled = false; switch (config.shortcutActivator){ case "ctrl": if (event.ctrlKey && !event.altKey && !event.shiftKey){ shortcutActivatorEnabled = true; } break; case "ctrl+shift": if (event.ctrlKey && !event.altKey && event.shiftKey){ shortcutActivatorEnabled = true; } break; case "ctrl+alt": if (event.ctrlKey && event.altKey && !event.shiftKey){ shortcutActivatorEnabled = true; } break; } if (shortcutActivatorEnabled && event.keyCode === config.shortcutKeyCode){ console.log("open!"); if(consoleDOM.ctrlEl.style.display === "none"){ consoleDOM.ctrlEl.style.display = "block"; } else { consoleDOM.ctrlEl.style.display = "none"; } } } const createDOMElements = () => { //Create & store CLI elements consoleDOM.ctrlEl = document.createElement("div"); //CLI control (outer frame) consoleDOM.outputEl = document.createElement("div"); //Div holding console output consoleDOM.inputEl = document.createElement("input"); //Input control consoleDOM.busyEl = document.createElement("div"); //Busy animation //Add classes consoleDOM.ctrlEl.className = "frontconsole"; consoleDOM.outputEl.className = "frontconsole-output"; consoleDOM.inputEl.className = "frontconsole-input"; consoleDOM.busyEl.className = "frontconsole-busy"; //Add attribute consoleDOM.inputEl.setAttribute("spellcheck", "false"); //Assemble them consoleDOM.ctrlEl.appendChild(consoleDOM.outputEl); consoleDOM.ctrlEl.appendChild(consoleDOM.inputEl); consoleDOM.ctrlEl.appendChild(consoleDOM.busyEl); //Hide ctrl & add to DOM consoleDOM.ctrlEl.style.display = "none"; document.body.appendChild(consoleDOM.ctrlEl); } const setBusy = (param) => { consoleState.busy = param; if (consoleState.busy){ consoleDOM.busyEl.style.display = "block"; } else { consoleDOM.busyEl.style.display = "none"; } } const setFocus = () => { consoleDOM.inputEl.focus(); } const instantiate = () => { createDOMElements(); setBusy(false); setFocus(); document.addEventListener('keydown', keyDownHandler); } instantiate(); return { config, tasks, consoleDOM } }
JavaScript
0.999349
@@ -1255,31 +1255,26 @@ ndler = -function (event) + =%3E %7B%0A o @@ -1319,23 +1319,19 @@ n = -function (event) + =%3E %7B%0A
bfdae5ebb7723acb8846d03eaac002148c26e669
Update Toggle component to put the className on label and not on input
packages/components/components/toggle/Toggle.js
packages/components/components/toggle/Toggle.js
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import Icon from '../icon/Icon'; const label = (key) => { const I18N = { on: c('Toggle button').t`On`, off: c('Toggle button').t`Off` }; return ( <span className="pm-toggle-label-text"> <Icon name={key} alt={I18N[key]} className="pm-toggle-label-img" /> </span> ); }; const Toggle = (props) => { return ( <> <input {...props} type="checkbox" className="pm-toggle-checkbox" /> <label htmlFor={props.id} className="pm-toggle-label"> {label('on')} {label('off')} </label> </> ); }; Toggle.propTypes = { id: PropTypes.string.isRequired, checked: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired }; Toggle.defaultProps = { id: 'toggle', checked: false }; export default Toggle;
JavaScript
0
@@ -430,21 +430,42 @@ ggle = ( -props +%7B id, className, ...rest %7D ) =%3E %7B%0A @@ -510,21 +510,20 @@ put %7B... -props +rest %7D type=%22 @@ -598,14 +598,8 @@ or=%7B -props. id%7D @@ -600,33 +600,34 @@ =%7Bid%7D className= -%22 +%7B%60 pm-toggle-label%22 @@ -625,17 +625,31 @@ le-label -%22 + $%7BclassName%7D%60%7D %3E%0A @@ -884,16 +884,49 @@ Required +,%0A className: PropTypes.string %0A%7D;%0A%0ATog @@ -964,16 +964,35 @@ oggle',%0A + className: '',%0A chec
c4965d2622dc1b3caee6ec3ee821f79470ee8af6
fix history problem in production environment
src/stores/configureStore.prod.js
src/stores/configureStore.prod.js
'use strict'; import { compose, createStore, combineReducers } from 'redux'; import { syncReduxAndRouter, routeReducer } from 'redux-simple-router' import createHistory from 'history/lib/createBrowserHistory'; import reducers from '../reducers'; const finalCreateStore = compose( )(createStore); function configureStore(initialState) { let reducersWithRoutes = combineReducers(Object.assign({}, reducers, { routing: routeReducer })); let store = finalCreateStore(reducersWithRoutes); let history = createHistory(); syncReduxAndRouter(history, store); return {store, history}; } export default configureStore;
JavaScript
0.000008
@@ -191,24 +191,241 @@ eate -BrowserHistory'; +HashHistory';%0A//import createHistory from 'history/lib/createBrowserHistory';%0A/* To use browser history, you have to config your web server%0A * https://github.com/rackt/react-router/blob/master/docs/guides/basics/Histories.md%0A *%0A */ %0A%0Aim
83854034a8b7a4340efeab5100aed1ab7984bc17
Fix admin firebase URL
source/js/modules/admin/admin-ctrl.js
source/js/modules/admin/admin-ctrl.js
/** * Admin controller definition * @scope Controllers */ define(['./module'], function (controllers) { 'use strict'; controllers.controller('AdminController', ['$scope', 'linkStorage', '$firebase', function AdminController($scope, linkStorage, $firebase) { var fireRef = new Firebase('https://shining-fire-3337.firebaseio.com/'); $scope.newLink = ''; $scope.$watch('links', function () { }, true); $scope.addLink = function () { var newLink = $scope.newLink.trim(); if (!newLink.length) { return; } $scope.links.$add({ url: newLink }); $scope.newLink = ''; }; $scope.editLink = function (id) { $scope.editedLink = $scope.links[id]; }; $scope.doneEditing = function (id) { var link = $scope.links[id]; link.url = link.url.trim(); $scope.links.$save(); if (!link.url) { $scope.removeLink(id); } $scope.editedLink = null; }; $scope.removeLink = function (id) { $scope.links.$remove(id); }; $scope.links = $firebase(fireRef); } ]); });
JavaScript
0
@@ -338,16 +338,21 @@ eio.com/ +links ');%0A%0A
4ac61084a9796cf8e27dd1564b7049c306394f21
update config
config/server.js
config/server.js
'use strict'; const path = require('path'); const express = require('express'); const viewEngine = require('ejs-locals'); const app = express(); // Server Config ========================================== app.engine('ejs', viewEngine); app.set('views', path.join(__dirname, '../views')); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, '../statics'))); const humanRoute = require('../routes/human.js'); const movieRoute = require('../routes/movie.js'); // ======================================================== app.use('/human', humanRoute); app.use('/movie', movieRoute); app.use(function (err, req, res, next) { console.log(err); res.status(err.status || 500); res.end(); }); // Config for development ===================================================== if ( app.get('env') === 'development' ) { app.set('port', 3000); } // Config for development ===================================================== if ( app.get('env') === 'production' ) { app.set('port', 80); } module.exports = app;
JavaScript
0.000001
@@ -869,14 +869,36 @@ rt', + (process.env.PORT %7C%7C 3000) +) ;%0A%7D%0A @@ -1042,12 +1042,34 @@ rt', + (process.env.PORT %7C%7C 80) +) ;%0A%7D%0A
80aab9a60ec4146746c16ee411c1e427816bc47f
Fix update and delete domain dispatch position
src/ui/scripts/actions/domains.js
src/ui/scripts/actions/domains.js
import api from '../utils/api' export const SET_DOMAINS_VALUE = Symbol() export const SET_DOMAINS_FETCHING = Symbol() export const SET_DOMAINS_ERROR = Symbol() export const RESET_DOMAINS = Symbol() export const setDomainsValue = (payload) => ({ type: SET_DOMAINS_VALUE, payload }) export const setDomainsFetching = (payload) => ({ type: SET_DOMAINS_FETCHING, payload }) export const setDomainsError = (payload) => ({ type: SET_DOMAINS_ERROR, payload }) export const resetDomains = () => ({ type: RESET_DOMAINS }) export const fetchDomains = (props) => async (dispatch) => { dispatch(setDomainsFetching(true)) dispatch(setDomainsError()) try { const data = await api('/domains', { method: 'get', props }) dispatch(setDomainsValue(data)) } catch (err) { dispatch(setDomainsError(err)) } finally { dispatch(setDomainsFetching(false)) } } export const updateDomain = (props, domainId, state) => async (dispatch) => { dispatch(setDomainsFetching(true)) dispatch(setDomainsError()) try { await api(`/domains/${ domainId }`, { method: 'put', body: JSON.stringify(state), props }) dispatch(fetchDomains(props)) } catch (err) { dispatch(setDomainsError(err)) } finally { dispatch(setDomainsFetching(false)) } } export const deleteDomain = (props, domainId, state) => async (dispatch) => { dispatch(setDomainsFetching(true)) dispatch(setDomainsError()) try { await api(`/domains/${ domainId }`, { method: 'delete', body: JSON.stringify(state), props }) dispatch(fetchDomains(props)) } catch (err) { dispatch(setDomainsError(err)) } finally { dispatch(setDomainsFetching(false)) } }
JavaScript
0
@@ -1136,41 +1136,8 @@ %7D)%0A%0A -%09%09dispatch(fetchDomains(props))%0A%0A %09%7D c @@ -1182,37 +1182,26 @@ or(err))%0A%0A%09%7D - finally %7B %0A%0A -%09 %09dispatch(se @@ -1202,38 +1202,28 @@ tch( -s +f et +ch Domains -Fetching(false))%0A%0A%09%7D +(props)) %0A%0A%7D%0A @@ -1488,41 +1488,8 @@ %7D)%0A%0A -%09%09dispatch(fetchDomains(props))%0A%0A %09%7D c @@ -1534,37 +1534,26 @@ or(err))%0A%0A%09%7D - finally %7B %0A%0A -%09 %09dispatch(se @@ -1554,37 +1554,27 @@ tch( -s +f et +ch Domains -Fetching(false))%0A%0A%09%7D +(props)) %0A%0A%7D
1b91401f0b71cee0aa4a65a3347a90c7a47947a9
Update gerrit_api.js
contents/gerrit_api.js
contents/gerrit_api.js
// TODO(sungguk): Make |GerritQuery| as singleton. /** * The GerritQuery sends and receives Gerrit data by using Gerrit REST APIs. * @constructor */ function GerritQuery() {} GerritQuery.prototype = { getChangeList: function(query) { // is:open+reviewer:self+owner:self console.log("Query:", query); return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); // |api_endpoint| would be a gerrit url like a https://gpro.lgsvl.com/ var api_endpoint = localStorage["api_endpoint"]; console.log(api_endpoint + '/changes/?o=MESSAGES&q=' + query); xhr.open("GET", api_endpoint + '/changes/?o=MESSAGES&q=' + query); xhr.send(); // call to reject() is ignored once resolve() has been invoked xhr.onload = function() { try { resolve(JSON.parse(xhr.responseText.substr(5))); } catch (e) { reject(new TypeError(e.message)); } } xhr.onloadend = function() { reject(new Error("Network error")); } }); } };
JavaScript
0.000001
@@ -1041,15 +1041,767 @@ %7D);%0A + %7D,%0A getChange: function(change_id) %7B%0A return new Promise(function(resolve, reject) %7B%0A var xhr = new XMLHttpRequest();%0A%0A // %7Capi_endpoint%7C would be a gerrit url like a https://gpro.lgsvl.com/%0A var api_endpoint = localStorage%5B%22api_endpoint%22%5D;%0A%09 console.log(api_endpoint + '/changes/' + change_id);%0A xhr.open(%22GET%22, api_endpoint + '/changes/' + change_id);%0A xhr.send();%0A // call to reject() is ignored once resolve() has been invoked%0A xhr.onload = function() %7B%0A try %7B%0A resolve(JSON.parse(xhr.responseText.substr(5)));%0A %7D catch (e) %7B%0A reject(new TypeError(e.message));%0A %7D%0A %7D%0A xhr.onloadend = function() %7B%0A reject(new Error(%22Network error%22));%0A %7D%0A %7D);%0A %7D%0A%7D;%0A
aa9fdc1a91c1b1930282d31cd391a4c2aa26f340
Fix step numbers
src/foam/u2/wizard/StepWizardletStepsView.js
src/foam/u2/wizard/StepWizardletStepsView.js
/** * @license * Copyright 2020 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.wizard', name: 'StepWizardletStepsView', extends: 'foam.u2.View', css: ` ^item { margin-bottom: 24px; } ^step-number-and-title { display: flex; align-items: center; } ^step-number-and-title > .circle { display: inline-block; margin-right: 24px; vertical-align: middle; min-width: 24px; line-height: 26px !important; } ^sub-item { padding-left: calc(24px + 24px + 4px); padding-top: 2px; padding-bottom: 8px; color: /*%GREY2%*/ #9ba1a6; } ^sub-item:hover { cursor: pointer; color: /*%GREY1%*/ #5e6061 !important; } ^sub-item:first-child { padding-top: 16px; } ^title { display: inline-block; margin: 0; vertical-align: middle; text-transform: uppercase; } `, imports: [ 'theme' ], requires: [ 'foam.u2.detail.AbstractSectionedDetailView', 'foam.u2.tag.CircleIndicator', 'foam.u2.wizard.WizardPosition', 'foam.u2.wizard.WizardletIndicator' ], messages: [ { name: 'PART_LABEL', message: 'Part ' } ], methods: [ function initE() { var self = this; this .add(this.slot(function ( data$wizardlets, data$wizardPosition, data$availabilityInvalidate ) { let elem = this.E(); let afterCurrent = false; // Fixes the sidebar number if a wizardlet is skipped let wSkipped = 0; for ( let w = 0 ; w < data$wizardlets.length ; w++ ) { let wizardlet = this.data.wizardlets[w]; let isCurrent = wizardlet === this.data.currentWizardlet; if ( this.data.countAvailableSections(w) < 1 || ! wizardlet.isAvailable || ! wizardlet.isVisible ) { wSkipped++; continue; } let baseCircleIndicator = { size: 24, borderThickness: 2, label: '' + (1 + w - wSkipped), }; elem = elem .start() .addClass(self.myClass('item')) .start().addClass(self.myClass('step-number-and-title')) // Render circle indicator .start(this.CircleIndicator, this.configureIndicator( wizardlet, isCurrent, 1 + 2 - wSkipped )) .addClass('circle') .end() // Render title .start('p').addClass(self.myClass('title')) .translate(wizardlet.capability.id+'.name', wizardlet.capability.name) .style({ 'color': isCurrent ? this.theme.black : this.theme.grey2 }) .end() .end(); // Get section index to highlight current section let wi = data$wizardPosition.wizardletIndex; let si = data$wizardPosition.sectionIndex; // Render section labels let sections = this.data.sections[w]; for ( let s = 0 ; s < sections.length ; s++ ) { let pos = this.WizardPosition.create({ wizardletIndex: w, sectionIndex: s, }) let section = sections[s]; let isCurrentSection = isCurrent && si === s; let isBeforeCurrentSection = w < wi || isCurrent && s < si; let allowedToSkip = self.data.canSkipTo(pos); let slot = section.isAvailable$.map(function (isAvailable) { return isAvailable ? self.renderSectionLabel( self.E().addClass(self.myClass('sub-item')), section, s+1, isCurrentSection ).on('click', () => { if ( isCurrentSection ) return; if ( allowedToSkip ) { self.data.skipTo(pos); } return; }) : self.E('span'); }) elem.add(slot); } elem = elem .end(); if ( isCurrent ) afterCurrent = true; } return elem; })) }, function renderSectionLabel(elem, section, index, isCurrent) { let title = section.title; if ( ! title || ! foam.Function.isInstance(title) && ! title.trim() ) title = this.PART_LABEL + index; title = foam.Function.isInstance(title) ? foam.core.ExpressionSlot.create({ obj$: section.data$, code: title }) : title; return elem .style({ 'color': isCurrent ? this.theme.black : this.theme.grey2 }) .translate(title, title); }, function configureIndicator(wizardlet, isCurrent, number) { var args = { size: 24, borderThickness: 2, }; if ( wizardlet.indicator == this.WizardletIndicator.COMPLETED ) { args = { ...args, borderColor: this.theme.approval3, backgroundColor: this.theme.approval3, borderColorHover: this.theme.approval3, icon: this.theme.glyphs.checkmark.getDataUrl({ fill: this.theme.white }), }; } else { args = { ...args, borderColor: this.theme.grey2, borderColorHover: this.theme.grey2, label: '' + number }; } if ( isCurrent ) { args = { ...args, borderColor: this.theme.black, borderColorHover: this.theme.black }; } return args; } ] });
JavaScript
0.001305
@@ -2065,167 +2065,8 @@ %7D%0A%0A - let baseCircleIndicator = %7B%0A size: 24,%0A borderThickness: 2,%0A label: '' + (1 + w - wSkipped),%0A %7D;%0A @@ -2393,13 +2393,14 @@ nt, +( 1 + -2 +w - w @@ -2402,24 +2402,25 @@ w - wSkipped +) %0A
1200d5e12fe4673f8e9e582915bd9d99839cf78b
Throw an error if the Stuffr API has not been initialized before use
app/stuffrapi.js
app/stuffrapi.js
/* stuffrapi.js Abstraction for working with Stuffr's backend REST API. An API object is exported for use in programs. To use, call the setupApi function at some point before it in your code, then whereever you need to call the Stuffr backend API you can just "import stuffrApi from 'stuffrapi'" to access it. For more complicated setups or if you prefer to manage the API object yourself, use the createStuffrApi function, which returns a new instance of the StuffrApi class. ********************************************************************/ import HttpStatus from 'http-status' import log from 'loglevel' // TODO: do not import loglevel but take a log object on createStuffrApi class StuffrApi { constructor (baseUrl) { if (baseUrl.endsWith('/')) { // Strip trailing slash baseUrl = baseUrl.replace(/\/$/, '') } this.urlBase = baseUrl } // GET request to /things async getThings (callback) { log.info('StuffrApi request for getThings') return await this._request('/things', {callback}) } // POST request to /things async addThing (parameters, callback) { log.info('StuffrApi request for addThing') return await this._request('/things', {parameters, callback}) } // PUT request to /things/<id> async updateThing (thingId, thingData, callback) { log.info(`StuffrApi request for updateThing <${thingId}>`) return await this._request(`/things/${thingId}`, {method: 'PUT', parameters: thingData, callback}) } // DELETE request to /things/<id> async deleteThing (thingId, callback) { log.info(`StuffrApi request for deleteThing <${thingId}>`) return await this._request(`/things/${thingId}`, {method: 'DELETE', callback}) } // Makes request to the server specified in baseUrl async _request (path, {method, parameters, callback} = {}) { const headers = new Headers() const body = JSON.stringify(parameters) const fullUrl = this.urlBase + path log.trace(`StuffrApi generic request to ${fullUrl}`) // Determine method if not given in parameters // Default method is GET, POST if paramater data is given if (!method) { if (parameters) { method = 'POST' } else { method = 'GET' } } if (method === 'POST' || method === 'PUT') { headers.append('Content-Type', 'application/json') } headers.append('Accept', 'application/json') let response try { response = await fetch(fullUrl, {method, headers, body}) } catch (error) { // Throw a more useful error message than the default log.error(`Error fetching ${fullUrl}: ${error}`) throw new Error(`Unable to fetch ${fullUrl}`) } if (!response.ok) { throw new Error(`HTTP response ${response.status} '${response.statusText}' fetching ${fullUrl}`) } let returnValue if (response.status === HttpStatus.NO_CONTENT) { // 204 means request was successful but did not return any data returnValue = null } else { returnValue = await response.json() } if (callback !== undefined) { callback(returnValue) } return returnValue } } // Factory function for creating StuffrApi objects export function createStuffrApi (baseUrl) { return new StuffrApi(baseUrl) } // TODO: replace null with dummy object that throws "not initialized" error let defaultApi = null export {defaultApi as default} export function setupApi (baseUrl) { defaultApi = createStuffrApi(baseUrl) }
JavaScript
0
@@ -3324,102 +3324,296 @@ %0A// -TODO: replace null with dummy object that throws %22not initialized%22 error%0Alet defaultApi = null +Dummy object to throw an error if the API was used before initalization%0Aconst dummyApi = %7B%0A get (target, name) %7B%0A const errorMsg = 'You must call setupApi before using API functions'%0A log.error(errorMsg)%0A throw new Error(errorMsg)%0A %7D%0A%7D%0A%0Alet defaultApi = new Proxy(%7B%7D, dummyApi) %0Aexp
fc2158257d9f224a08e38bcbf19963550d03bfe4
remove period
src/foam/nanos/u2/navigation/SignUp.js
src/foam/nanos/u2/navigation/SignUp.js
foam.CLASS({ package: 'foam.nanos.u2.navigation', name: 'SignUp', documentation: `Model used for registering/creating an user. Hidden properties create the different functionalities for this view (Ex. coming in with a signUp token)`, imports: [ 'appConfig', 'auth', 'notify', 'stack', 'user' ], requires: [ 'foam.nanos.auth.Address', 'foam.nanos.auth.Country', 'foam.nanos.auth.Phone', 'foam.nanos.auth.User' ], messages: [ { name: 'TITLE', message: 'Create a free account' }, { name: 'FOOTER_TXT', message: 'Already have an account?' }, { name: 'FOOTER_LINK', message: 'Sign in' } ], properties: [ { name: 'dao_', hidden: true }, { class: 'String', name: 'group_', documentation: `Group this user is going to be apart of.`, hidden: true }, { class: 'Boolean', name: 'isLoading_', documentation: `Condition to synchronize code execution and user response.`, hidden: true }, { class: 'String', name: 'token_', documentation: `Input to associate new user with something.`, hidden: true }, { class: 'Boolean', name: 'disableEmail_', documentation: `Set this to true to disable the email input field.`, hidden: true }, { class: 'Boolean', name: 'disableCompanyName_', documentation: `Set this to true to disable the Company Name input field.`, hidden: true }, { class: 'StringArray', name: 'countryChoices_', documentation: `Set this to the list of countries (Country.NAME) we want our signing up user to be able to select.`, hidden: true }, { class: 'String', name: 'firstName', gridColumns: 6, view: { class: 'foam.u2.TextField', placeholder: 'Jane' }, required: true }, { class: 'String', name: 'lastName', gridColumns: 6, view: { class: 'foam.u2.TextField', placeholder: 'Doe' }, required: true }, { class: 'String', name: 'department', label: 'Your Job Title', view: { class: 'foam.u2.TextField', placeholder: 'Staff accountant' }, validationPredicates: [ { args: ['department'], predicateFactory: function(e) { return e.NEQ(foam.nanos.u2.navigation.SignUp.DEPARTMENT, ''); }, errorString: 'Please select a Job Title.' } ], required: true }, { class: 'FObjectProperty', of: 'foam.nanos.auth.Phone', name: 'phone', label: '', factory: function() { return this.Phone.create(); }, view: { class: 'foam.u2.detail.VerticalDetailView' }, required: true }, { class: 'String', name: 'organization', label: 'Company Name', view: { class: 'foam.u2.TextField', placeholder: 'ABC Company' }, visibilityExpression: function(disableCompanyName_) { return disableCompanyName_ ? foam.u2.Visibility.DISABLED : foam.u2.Visibility.RW; }, required: true }, { class: 'Reference', targetDAOKey: 'countryDAO', name: 'countryId', label: 'Country', of: 'foam.nanos.auth.Country', documentation: 'Country address.', view: function(_, X) { var E = foam.mlang.Expressions.create(); choices = X.data.slot(function(countryChoices_) { if ( ! countryChoices_ || countryChoices_.length == 0 ) return X.countryDAO; return X.countryDAO.where(E.IN(X.data.Country.ID, countryChoices_)); }); return foam.u2.view.ChoiceView.create({ placeholder: 'Select your country', objToChoice: function(a) { return [a.id, a.name]; }, dao$: choices }); }, required: true, }, { class: 'EMail', name: 'email', view: { class: 'foam.u2.TextField', placeholder: 'example@example.com' }, visibilityExpression: function(disableEmail_) { return disableEmail_ ? foam.u2.Visibility.DISABLED : foam.u2.Visibility.RW; }, required: true }, { class: 'Password', name: 'desiredPassword', label: 'Password', view: { class: 'foam.u2.view.PasswordView', passwordIcon: true }, minLength: 6 } ], methods: [ { name: 'footerLink', code: function(topBarShow_, param) { window.history.replaceState(null, null, window.location.origin); this.stack.push({ class: 'foam.u2.view.LoginView', mode_: 'SignIn', topBarShow_: topBarShow_, param: param }, this); } }, { name: 'subfooterLink', code: function() { return; } }, { name: 'updateUser', code: function(x) { this.finalRedirectionCall(); } }, { name: 'finalRedirectionCall', code: function() { if ( this.user.emailVerified ) { // When a link was sent to user to SignUp, they will have already verified thier email, // thus thier user.emailVerified should be true and they can simply login from here. window.history.replaceState(null, null, window.location.origin); location.reload(); } else { // logout once we have finished updating documents. this.auth.logout(); this.stack.push({ class: 'foam.nanos.auth.ResendVerificationEmail' }); } } } ], actions: [ { name: 'login', label: 'Get Started', isEnabled: function(errors_, isLoading_) { return ! errors_ && ! isLoading_; }, code: function(x) { this.isLoading_ = true; this.dao_ .put(this.User.create({ firstName: this.firstName, lastName: this.lastName, organization: this.organization, email: this.email, desiredPassword: this.desiredPassword, signUpToken: this.token_, address: this.Address.create({ countryId: this.countryId }), welcomeEmailSent: true, department: this.department, phone: this.Phone.create({ number: this.phone }), group: this.group_ })) .then((user) => { this.user.copyFrom(user); this.updateUser(x); }).catch((err) => { this.notify(err.message || 'There was a problem creating your account.', 'error'); }) .finally(() => { this.isLoading_ = false; }); } } ] });
JavaScript
0.000187
@@ -2533,17 +2533,16 @@ ob Title -. '%0A
1916cc22ece6f1fa780f4ced7af3d8dce2e704f5
update testing env scripts
scripts/setup-env.js
scripts/setup-env.js
const fs = require('fs-extra') const path = require('path') main().catch(swallow) async function main() { const depsPath = path.join(__dirname, '../deps') const destPath = path.join(__dirname, '../node_modules') const stat = await fs.stat(depsPath).catch(swallow) if (stat && stat.isDirectory()) { const depsFiles = await fs.readdir(depsPath) await Promise.all( depsFiles.map(name => fs.remove(path.join(destPath, name)).catch(swallow)) ) fs.copy(path.join(depsPath), destPath).catch(swallow) } } function swallow() { return null }
JavaScript
0.000004
@@ -77,16 +77,44 @@ allow)%0A%0A +// set-up local testing env%0A async fu @@ -245,18 +245,90 @@ )%0A -const stat +if (await isDirectory(depsPath)) %7B%0A const depsFiles = %5B%5D%0A const rawDepsFiles = a @@ -335,20 +335,23 @@ wait fs. -stat +readdir (depsPat @@ -356,55 +356,77 @@ ath) -.catch(swallow)%0A if (stat && stat.isDirectory( +%0A for (const name of rawDepsFiles) %7B%0A if (name.startsWith('@' )) %7B @@ -426,33 +426,35 @@ '@')) %7B%0A + + const -dep +n sFiles = awa @@ -463,33 +463,208 @@ fs.readdir( -depsPath) +path.join(depsPath, name))%0A for (const nsName of nsFiles) %7B%0A depsFiles.push(path.join(name, nsName))%0A %7D%0A %7D else %7B%0A depsFiles.push(name)%0A %7D%0A %7D %0A await P @@ -699,16 +699,22 @@ map( +async name =%3E fs.r @@ -713,43 +713,99 @@ =%3E -fs.remove(path.join(destPath, name) +%7B%0A const destPkgPath = path.join(destPath, name)%0A await fs.remove(destPkgPath ).ca @@ -820,19 +820,77 @@ low) -) %0A -)%0A + await fs.ensureDir(destPkgPath).catch(swallow)%0A await fs. @@ -916,16 +916,22 @@ Path +, name ), destP ath) @@ -926,16 +926,19 @@ ), destP +kgP ath).cat @@ -951,17 +951,180 @@ llow)%0A -%7D + %7D)%0A )%0A %7D%0A%7D%0A%0Aasync function isDirectory(dirPath) %7B%0A const dirStat = await fs.stat(dirPath).catch(swallow)%0A return Boolean(dirStat && dirStat.isDirectory()) %0A%7D%0A%0Afunc
3656892aaff972a99ab58c8d4f5b8d5ec5c7ca3f
Correct file overview JsDoc for seekstate.js
static/script/devices/media/seekstate.js
static/script/devices/media/seekstate.js
/** * @fileOverview Requirejs module containing CE-HTML media wrapper * * @preserve Copyright (c) 2013 British Broadcasting Corporation * (http://www.bbc.co.uk) and TAL Contributors (1) * * (1) TAL Contributors are listed in the AUTHORS file and at * https://github.com/fmtvp/TAL/AUTHORS - please extend this file, * not this notice. * * @license 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. * * All rights reserved * Please contact us for an alternative licence */ require.def('antie/devices/media/seekstate', [ 'antie/class', 'antie/events/mediaevent' ], function(Class, MediaEvent){ 'use strict'; var State = { None : 0, Seeking : 1, Playing : 2 }; var SeekState = Class.extend({ init :function(eventHandlingCallback) { this._eventHandlingCallback = eventHandlingCallback; this._currentTime = 0; this._state = State.None; }, seekTo: function(time) { if (time === this._currentTime) { return; } this._state = State.Seeking; this._currentTime = time; this._eventHandlingCallback(new MediaEvent("seeking")); }, playing: function() { if (this._state === State.Seeking) { this._eventHandlingCallback(new MediaEvent("seeked")); } this._state = State.Playing; } }); return SeekState; } );
JavaScript
0
@@ -45,12 +45,47 @@ ning + a helper to track seek state for%0A * CE -- HTML @@ -95,15 +95,17 @@ dia -wrapp +modifi er +. %0A *%0A
23f6af65befdbe8b5c36da27d301c8b90001ee5e
Allow RenderedMap to locate and render a map from a list of maps
app/views/map.js
app/views/map.js
import * as React from 'react/addons' import * as Reflux from 'reflux' import * as _ from 'lodash' let cx = React.addons.classSet let RenderedMap = React.createClass({ findMap(mapId) { let map = this.props.map; if (map) { this.setState({ map: { width: map.get('width'), height: map.get('height'), countries: map.get('countries'), spaces: map.get('spaces'), } }) } }, componentWillReceiveProps(nextProps) { this.findMap(nextProps.mapId) }, componentWillMount() { this.componentWillReceiveProps(this.props) }, getInitialState() { return { maps: [], map: { spaces: [], countries: [], width: 0, height: 0, }, } }, onClickTerritory(ev) { console.log(ev.target.attributes['data-id'].value); }, render() { console.log('RenderedMap.props', this.props) let spaces = React.createElement('defs', {id: 'all-spaces'}, _.map(this.state.map.spaces, (space) => { // todo: clean up this logic, if possible let vectorPath = space.path; let paths = []; let cantUsePath = false; let args = { className: cx({ space: true, 'supply-center': Boolean(space.supply), [`space-type-${space.type}`]: true, }), id: `space-${space.id}`, key: space.id, } if (_.isNumber(vectorPath)) { // it's referencing another path, so we use a <use>. cantUsePath = true; args.dangerouslySetInnerHTML = {__html: `<use xlink:href="#space-${vectorPath}" />`} } else if (_.isArray(vectorPath)) { // it has multiple paths; probably islands. paths = _.map(vectorPath, (path, index) => React.createElement('path', {d: path, key: index})) } else { // it has only a single path paths = [React.createElement('path', {d: vectorPath, key: 0})] } return React.createElement('g', args, cantUsePath ? null : paths) })) let patterns = React.createElement('defs', null, React.createElement('pattern', { id: 'diagonalHatch', key: 'diagonalHatch', patternUnits: 'userSpaceOnUse', width: '32', height: '32', }, React.createElement('path', {className: 'fill', d: 'M 0,0 l 32,0 0,32 -32,0 0,-32'}), React.createElement('path', {className: 'stripes', d: 'M -8,8 l 16,-16 M 0,32 l 32,-32 M 24,40 l 16,-16'}))) let countries = _.map(this.state.map.countries, (country) => React.createElement('g', { className: 'country', id: country.name.toLowerCase(), key: country.name, fill: country.vacantColor, }, _.map(country.startSpaces, (spaceId) => { return React.createElement('g', { key: `${country.name}-${spaceId}`, id: `${country.name}-${spaceId}`, onClick: this.onClickTerritory, className: 'territory accessible-territory', dangerouslySetInnerHTML: {__html: `<use data-id='${spaceId}' xlink:href="#space-${spaceId}" />`}, }) })) ) // todo: perhaps find a better way to render the spaces let occupiedSpaces = _(this.state.map.countries) .pluck('startSpaces') .flatten() .map((spaceId) => _.find(this.state.map.spaces, {id: spaceId}).territory) .flatten() .compact() .union(_.flatten(this.state.map.countries, 'startSpaces')) .value() let seaSpaceIds = _(this.state.map.spaces) .filter({type: 'sea'}) .pluck('id') .value() let seaSpaces = React.createElement('g', { className: 'ocean', key: 'Ocean', }, _.map(seaSpaceIds, (spaceId) => React.createElement('g', { id: `sea-${spaceId}`, key: `sea-${spaceId}`, onClick: this.onClickTerritory, className: 'territory accessible-territory sea-territory', dangerouslySetInnerHTML: {__html: `<use data-id='${spaceId}' xlink:href="#space-${spaceId}" />`}, })) ) let emptySpaces = _(this.state.map.spaces) .reject((space) => _.contains(occupiedSpaces, space.id)) .reject((space) => _.contains(seaSpaceIds, space.id)) .value() let otherSpaces = React.createElement('g', { className: 'country empty-country', id: 'vacant', key: 'Vacant', }, _.map(emptySpaces, (space) => { let isTraversable = (space.moveTo.land.length > 0 || space.moveTo.sea.length > 0) return React.createElement('g', { id: `empty-${space.id}`, key: `empty-${space.id}`, onClick: this.onClickTerritory, className: cx({ territory: true, 'accessible-territory': isTraversable, 'inaccessible-territory': !isTraversable, 'sea-territory': (space.type === 'sea'), }), fill: isTraversable ? undefined : 'url(#diagonalHatch)', dangerouslySetInnerHTML: {__html: `<use data-id='${space.id}' xlink:href="#space-${space.id}" />`}, } ) })) return React.createElement('svg', { className: 'map', viewBox: `0 0 ${this.state.map.width} ${this.state.map.height}`, }, spaces, patterns, seaSpaces, React.createElement('g', {className: 'countries'}, countries, otherSpaces )) }, }) export default RenderedMap
JavaScript
0
@@ -175,17 +175,84 @@ Map( -mapId +props) %7B%0A%09%09let map = props.map;%0A%09%09if (!map && props.mapId && props.maps ) %7B%0A +%09 %09%09le @@ -260,26 +260,127 @@ map +Id = -this.props.map; +_.isObject(props.mapId) ? props.mapId.id : props.mapId;%0A%09%09%09map = _.find(props.maps, (map) =%3E map.id === mapId)%0A%09%09%7D %0A%09%09i @@ -635,22 +635,16 @@ extProps -.mapId )%0A%09%7D,%0A%09c
a5efa820dd9bb04232dde7a8f6bfafd223f7f52a
fix typing error on initial check
appengine/app.js
appengine/app.js
'use strict' const express = require('express') const admin = require('firebase-admin') const util = require('util') const request = require('request-promise') const scheduler = require('firebase-scheduler') // Prepare Firebase // ---------------- const serviceAccount = require('./firebase-admin-key.json') const config = require('./config.json') const isDev = process.env.DEV == 'true' console.log(`DEV MODE=${isDev}`) admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: config.databaseURL }) function now() { return (new Date()).getTime() } // Process Requests // ---------------- const app = express() app.get('/', (req, res) => { res.status(200).send('Hello, World!').end() }) function promiseDelay(ms, x) { return new Promise(function (resolve) { if (ms > 0) { setTimeout(function () { resolve(x) }, ms) } else { // Immediate resolve(x) } }) } function processScheduled(id, key, value) { console.log(`Processing item={id: ${id}, key: ${key}, value: ${util.inspect(value)}}`) // Get the scheduled item payload, // then execute the query // then remove remove it from the list of pending items. return admin.database().ref(`/scheduler/${id}/all/${key}`).once('value') .then(x => x.val()) .then(x => { const delta = x.time.scheduledTS - now() console.log(`Waiting for item: ${id}, delta: ${delta}`) return promiseDelay(delta, x) }) .then(x => { console.log(`Running item: ${id}, query: ${util.inspect(x.query)}`) return request(x.query) }) .then(() => admin.database().ref(`/scheduler/${id}/pending/${key}`).remove() ) } function makeResponse(res, id, processed) { res.status(200) res.setHeader('Content-Type', 'application/json') res.send(JSON.stringify({ scheduler: id, lastRun: 0, processedCount: processed.length })) return res } function pendings(schedulerRef, maxDeltaSeconds) { const time = now() + 1 + maxDeltaSeconds * 1000 const key = scheduler.scheduleID(time, true) console.log(`Retrieving all pending jobs up to time: ${time}, key: ${key}`) return schedulerRef .orderByKey() .endAt(key) .once('value') } app.get('/check/:duration/:id', (req, res) => { // Allowed only from a cron job or in developement mode. if (!isDev && req.get('X-Appengine-Cron') != true) { res.status(403) res.send('Forbidden') return res } const duration = parseInt(req.params['duration']) const id = req.params['id'] const schedulerRef = admin.database().ref(`/scheduler/${id}/pending`) pendings(schedulerRef, duration) .then(dataSnapshot => { const r = [] console.log(`Scheduling ${dataSnapshot.numChildren()} items`) dataSnapshot.forEach(x => r.push(processScheduled(id, x.key, x.val())) && false) return Promise.all(r) }) .then(xs => makeResponse(res, id, xs)) .catch(x => res.send(x).status(500).end()) }) // Start the server // ---------------- const PORT = process.env.PORT || 8080 app.listen(PORT, () => { console.log(`App listening on http://localhost:${PORT}`) console.log('Press Ctrl+C to quit.') })
JavaScript
0.000001
@@ -2277,17 +2277,16 @@ s) =%3E %7B%0A -%0A // All @@ -2382,21 +2382,24 @@ ron') != - += ' true +' ) %7B%0A
1a649a6ac36100c7a28234a0492464d4ad605e22
Handle in-app-purchase less fatally on non-Darwin (#12511)
lib/browser/api/in-app-purchase.js
lib/browser/api/in-app-purchase.js
'use strict' if (process.platform !== 'darwin') { throw new Error('The inAppPurchase module can only be used on macOS') } const {EventEmitter} = require('events') const {inAppPurchase, InAppPurchase} = process.atomBinding('in_app_purchase') // inAppPurchase is an EventEmitter. Object.setPrototypeOf(InAppPurchase.prototype, EventEmitter.prototype) EventEmitter.call(inAppPurchase) module.exports = inAppPurchase
JavaScript
0
@@ -32,9 +32,9 @@ orm -! += == ' @@ -50,81 +50,8 @@ %7B%0A -throw new Error('The inAppPurchase module can only be used on macOS')%0A%7D%0A%0A cons @@ -87,16 +87,18 @@ vents')%0A + const %7Bi @@ -168,16 +168,18 @@ hase')%0A%0A + // inApp @@ -207,16 +207,18 @@ mitter.%0A + Object.s @@ -280,16 +280,18 @@ totype)%0A + EventEmi @@ -316,16 +316,18 @@ chase)%0A%0A + module.e @@ -349,8 +349,247 @@ urchase%0A +%7D else %7B%0A module.exports = %7B%0A purchaseProduct: (productID, quantity, callback) =%3E %7B%0A throw new Error('The inAppPurchase module can only be used on macOS')%0A %7D,%0A canMakePayments: () =%3E false,%0A getReceiptURL: () =%3E ''%0A %7D%0A%7D%0A
1efcd816189ef58aad4a044848f1d33a897762db
extend callback with general callbacks
lib/callbacks/databaseCallbacks.js
lib/callbacks/databaseCallbacks.js
/* * cushion-cli * https://github.com/stefanjudis/cushion-cli * * Copyright (c) 2012 stefan judis * Licensed under the MIT license. */ var databaseCallbacks = module.exports = {}; var cli = require('../cliRunner'); databaseCallbacks.exists = function(error, response) { if (error) { databaseCallbacks.handleError(error); } else { if (response === true) { console.log('Database already exists.'); } else { console.log('Database doesn\'t exist yet.'); } cli.prompt(); } }; /** * [create description] * @param {[type]} error [description] * @param {[type]} response [description] * @return {[type]} [description] */ databaseCallbacks.create = function(error, response) { if (error) { databaseCallbacks.showError(error); } else { if (response === true) { console.log('Database created.'); } else { console.log('Database couldn\'t be created'); } } cli.prompt(); }; /** * [destroy description] * @param {[type]} error [description] * @param {[type]} response [description] * @return {[type]} [description] */ databaseCallbacks.destroy = function(error, response) { if (error) { databaseCallbacks.handleError(error); } else { if (response === true) { console.log('Database deleted.\nSwitched to connection level'); cli.level = 'connection'; cli.prompt(); } else { console.log('Database couldn\'t be deleted'); cli.prompt(); } } }; /** * [allDocuments description] * @param {[type]} error [description] * @param {[type]} info [description] * @param {[type]} allDocs [description] */ databaseCallbacks.allDocuments = function(error, info, allDocs) { var columnWidth = 28, displayKey; if (error) { databaseCallbacks.handleError(error); } else { console.log('This databases exists of ' + info.total + ' documents.'); console.log('Displayed result has an offset of ' + info.offset + '.\n'); // iterate over allDocs object console.log(' id | revision hash '); Object.keys(allDocs).forEach(function(key) { console.log(' ----------------------------------------------------------'); displayKey = key; if (displayKey.length <= columnWidth) { while (displayKey.length < columnWidth) { displayKey = displayKey + ' '; } } else { displayKey = displayKey.substr(0, columnWidth); } console.log(displayKey + ' | ' + allDocs[key]); }); cli.prompt(); } }; /** * [view description] * @param {[type]} error [description] * @param {[type]} info [description] * @param {[type]} rows [description] * @return {[type]} [description] */ databaseCallbacks.view = function(error, info, rows) { var keys, row; if (error) { databaseCallbacks.handleError(error); } else { console.log('This databases exists of ' + info.total + ' documents.'); console.log('Displayed result has an offset of ' + info.offset + '.\n'); keys = Object.keys(rows[0]); rows.forEach(function(entry) { console.log('----------------------------'); keys.forEach(function(key) { if (key === 'value') { console.log('(' + key + ') ->'); console.log(entry[key]); } else { console.log('(' + key + ') -> ' + entry[key]); } }); }); cli.prompt(); } }; /** * [showError description] * @param {[type]} error [description] * @return {[type]} [description] */ databaseCallbacks.handleError = function(error) { console.log('ERROR: ' + error.error + '\nREASON: ' + error.reason); cli.prompt(); }; databaseCallbacks.info = databaseCallbacks.simpleCallback;
JavaScript
0.000001
@@ -182,42 +182,227 @@ = %7B%7D -;%0Avar cli = require('../cliRunner' +,%0A generalCallbacks = require('./generalCallbacks'),%0A cli = require('../cliRunner'),%0A extend = require('node.extend');%0A%0A%0A// extend level commands with general commands%0Aextend(databaseCallbacks, generalCallbacks );%0A%0A
e37375a30589e196c463853be2d75a8999afca86
update oauth2
Resource-Authorization-Server/config/oauth2.js
Resource-Authorization-Server/config/oauth2.js
'use strict'; var oauth2orize = require('oauth2orize'); var passport = require('passport'); var crypto = require('crypto'); var bcrypt = require('bcrypt'); var Client = require('../models/Client'); var AccessToken = require('../models/AccessToken'); var uuid = require('./uuid'); var server = oauth2orize.createServer(); var algorithm = 'aes-256-ctr'; var password = 'administrator'; function encrypt(text) { var cipher = crypto.createCipher(algorithm, password) var crypted = cipher.update(text, 'utf8', 'hex') crypted += cipher.final('hex'); return crypted; } server.serializeClient(function(client, done) { return done(null, client.clientId); }); server.deserializeClient(function(id, done) { Client.find({ clientId: id }, function(err, client) { if (err) return done(err); return done(null, client); }); }); //Implicit grant server.grant(oauth2orize.grant.token(function(client, user, ares, done) { var token = uuid.uid(256); var tokenHash = encrypt(token); var tokenExpired = new Date(new Date().getTime() + (3600 * 1000)) var accessToken = new AccessToken({ token: token, tokenExpired: tokenExpired, userId: user.username, clientId: client.clienId }); accessToken.save(function(err) { if (err) return done(err) return done(null, token, { expires_in: tokenExpired.toISOString(), access_token: tokenHash }); }); })); // user authorization endpoint exports.authorization = [ function(req, res, next) { if (req.user) next(); else res.redirect('/oauth/authorization'); }, server.authorization(function(clientId, redirectURI, done) { Client.findOne({ clientId: clientId }, function(err, client) { if (err) return done(err) return done(null, client, redirectURI); }) }), function(req, res) { res.render('decision', { transactionID: req.oauth2.transactionID, user: req.user, client: req.oauth2.client }); } ]; // user decision endpoint exports.decision = [ function(req, res, next) { if (req.user) next(); else res.redirect('/oauth/authorization'); }, server.decision() ];
JavaScript
0
@@ -146,24 +146,57 @@ ('bcrypt');%0A +var _ = require('underscore')._;%0A var Client = @@ -960,24 +960,25 @@ es, done) %7B%0A +%0A var token @@ -1095,18 +1095,521 @@ * 1000)) +; %0A%0A + var clientId = %7B%7D;%0A%0A _.each(client, function(c) %7B%0A clientId = c.clientId;%0A %7D);%0A%0A AccessToken.findOne(%7B%0A clientId: clientId%0A %7D, function(err, accessToken) %7B%0A if (err) return done(err);%0A%0A if (accessToken) %7B%0A accessToken.token = token;%0A accessToken.tokenExpired = tokenExpired;%0A accessToken.save();%0A%0A return done(null, token, %7B%0A expires_in: tokenExpired.toISOString(),%0A access_token: tokenHash%0A %7D);%0A%0A %7D else %7B%0A%0A console.log(clientId);%0A%0A var ac @@ -1638,24 +1638,28 @@ Token(%7B%0A + + token: token @@ -1660,24 +1660,28 @@ token,%0A + + tokenExpired @@ -1696,16 +1696,20 @@ xpired,%0A + user @@ -1727,24 +1727,28 @@ ername,%0A + + clientId: cl @@ -1755,24 +1755,26 @@ ient -.clienId%0A +Id%0A %7D);%0A%0A + ac @@ -1800,32 +1800,36 @@ tion(err) %7B%0A + + if (err) return @@ -1838,24 +1838,28 @@ ne(err)%0A + + return done( @@ -1875,24 +1875,28 @@ en, %7B%0A + + expires_in: @@ -1925,24 +1925,28 @@ ng(),%0A + access_token @@ -1953,24 +1953,28 @@ : tokenHash%0A + %7D);%0A %7D) @@ -1971,19 +1971,36 @@ %7D);%0A -%7D); + %7D);%0A %7D%0A %7D);%0A %0A%7D));%0A%0A/
74fdb9a1b31739b240208b6f4abae5c11aedec93
remove refreshToken store
lib/entitlement/passport-config.js
lib/entitlement/passport-config.js
"use strict"; var async = require('async'); var express = require('express'); var passport = require('passport'); var _ = require('underscore'); var request = require('request'); var url = require('url'); var crypto = require('crypto'); var util = require('util'); var GitHubStrategy = require('passport-github').Strategy; var config = require('config'); module.exports = function() { passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(_id, done) { require('../couchdb').regDB.users.doc(_id).open(function(err, user) { require('../models/gravatar')(user); done(err, user); }); }); var strategy = new GitHubStrategy({ clientID: config.Auth.clientID, clientSecret: config.Auth.clientSecret, callbackURL: config.Auth.callbackURL, passReqToCallback: true, scope: ['user:email'] }, function(req, accessToken, refreshToken, profile, done) { var user = parseGithubProfile(profile); user.secret = { accessToken: accessToken, refreshToken: refreshToken }; var userAddress = url.resolve(config.Couch.address, '/_users/' + encodeURIComponent(user._id)); request(userAddress, { json: true }, function(err, res, body) { if (err) return done(err); // create default passwd with accessToke and refreshToken var md5 = crypto.createHash('md5'); accessToken && md5.update(accessToken, 'utf8'); var gPass = md5.digest('hex'); if (res.statusCode == 200) { // verify the user auth var p = url.parse(config.Couch.address); p.auth = encodeURIComponent(user.username) + ':' + gPass; // try verify request(url.format(p), function(err, res, body) { if (err) return done(err); if (res.statusCode == 401) { // the same user if (user.github == body.github) { // user has change password return strategy.res.render('/login', { message: 'You had change the password, please enter new password to login' }); } else { return done(new Error("username had already been taken")); } } else if (res.statusCode == 200) { req.session.auth = { accessToken: accessToken }; return done(null, user); } else { return done(new Error("request to registry failed with statusCode: " + res.statusCode)); } }); } else if (res.statusCode == 404) { // create user var json = createUserDoc(_.defaults(user, { password: gPass })); request({ method: 'PUT', url: userAddress, body: JSON.stringify(json), auth: null }, function(err, res, body) { if (err) return done(err); req.session.auth = { accessToken: accessToken, refershToken: refershToken }; return done(null, user); }); } else { return done(new Error('request to registry failed with statusCode:' + res.statusCode)); } }); }); // use github strategy passport.use(strategy); }; function sha(s) { return crypto.createHash("sha1").update(s).digest("hex"); }; function parseGithubProfile(profile) { return { _id: 'org.couchdb.user:' + profile.username, username: profile.username, displayName: profile.displayName, email: profile.emails[0].value, github: profile.profileUrl, blog: profile._json.blog, company: profile._json.company, location: profile._json.location }; } function createUserDoc(user) { var salt = crypto.randomBytes(30).toString('hex'); var username = user.username; var email = user.email; var password = user.password; return _.defaults({ name: username, salt: salt, password_sha: sha(password + salt), email: email, _id: 'org.couchdb.user:' + username, type: 'user', roles: [], date: new Date().toISOString() }, user); };
JavaScript
0.000001
@@ -3982,68 +3982,8 @@ oken -,%0A refershToken: refershToken %0A
c6d51c0686f0e95873d8016cf87079a40f49788f
add warnings about obsolete namespaces
lib/jose-backward-compatibility.js
lib/jose-backward-compatibility.js
// this file exists for backward compatibility only JoseJWE.Utils = Jose.Utils; JoseJWE.WebCryptographer = Jose.WebCryptographer;
JavaScript
0.000001
@@ -50,34 +50,232 @@ ly%0A%0A -JoseJWE.Utils = Jose.Utils +console.warn(%22JoseJWE.Utils namespace is obsolete and it'll be removed in future releases%22);%0AJoseJWE.Utils = Jose.Utils;%0A%0Aconsole.warn(%22JoseJWE.WebCryptographer namespace is obsolete and it'll be removed in future releases%22) ;%0AJo
45451fb1546100c70cef6e1ed9f322915c9090ab
删除initProjConfig时创建.data文件夹的操作
lib/module/initProject/initProj.js
lib/module/initProject/initProj.js
var fs = require('fs'), mod = require('../../mod.js'), notice = mod.notice, util = mod.util, _conf = mod.conf, ProjConfig = mod.load('ProjConfig'); var _exampleRoot = mod.dirname+'/../template/', _projTpls = {}, _projnameReg = /\{@projRoot\}/g; // 初始化所有的配置方案 fs.readdirSync(_exampleRoot).forEach(function(v){ if (v == '..' || v=='.') return; var planRoot = _exampleRoot + v+'/', confFile = planRoot + _conf.MainConfigFile; if (!fs.existsSync(confFile)) { notice.warn('deploy', 'The plan('+v+') do not has projconf file'); return; } _projTpls[v] = {}; readDir(planRoot, '', _projTpls[v]); }); // 必须检查 default是否存在 if (!_projTpls['default']) notice.error('deploy', 'Do not has `default` plan'); function readDir(root, path, projTpl){ fs.readdirSync(root).forEach(function(v){ if (v == '..' || v=='.') return; if (fs.statSync(root+v).isFile()) { projTpl[path+v] = fs.readFileSync(root+v); } else { readDir(root+v+'/', path+v+'/', projTpl); } }); } module.exports = function(projName, plan){ var root = _conf.DocumentRoot + projName +'/', confFile = root+_conf.ProjConfigFile; if (!fs.existsSync(confFile)) { if (!plan || !_projTpls[plan]) { notice.warn('deploy', 'The plan('+plan+') switch to `default`'); plan = _projTpls['default']; } else { plan = _projTpls[plan]; } try { util.eachObject(plan, function(i, v){ if (_projnameReg.test(v.toString())) v = v.toString().replace(_projnameReg, projName); util.writeFile(root+i, v); }); // 创建可能遗漏的目录 var path = root+_conf.SourcePath; if (!fs.existsSync(path)) util.mkdirs(path); path = root+_conf.DynamicDataPath; if (!fs.existsSync(path)) util.mkdirs(path); // 初始化项目 if (ProjConfig.reload(projName, true)) notice.log('Object Init', 'Object create success'); } catch(err) { notice.error('', err); } } else { notice.warn('Object Init', 'Object is exists', root); } };
JavaScript
0
@@ -1121,37 +1121,39 @@ File;%0A%09if (! -fs.e +util.fileE xists -Sync (confFile)) @@ -1618,16 +1618,19 @@ th);%0A%09%09%09 +// path = r @@ -1651,32 +1651,35 @@ micDataPath;%0A%09%09%09 +// if (!fs.existsSy
f8e6284e54eb58fb4877c479e74c01dda40ec2ef
Add back 'X is typing' (though it doesn't work properly with threads)
ditto/static/flux-chat/js/stores/WhosTypingStore.js
ditto/static/flux-chat/js/stores/WhosTypingStore.js
var ChatAppDispatcher = require('../dispatcher/ChatAppDispatcher'); var ChatConstants = require('../constants/ChatConstants'); var EventEmitter = require('events').EventEmitter; var assign = require('object-assign'); var ThreadStore = require('../stores/ThreadStore'); var ActionTypes = ChatConstants.ActionTypes; var CHANGE_EVENT = 'change'; var _whosTyping = {}; function _removeAuthor (recipient, author) { var whosTyping = _whosTyping[recipient]; whosTyping.splice(whosTyping.indexOf(author), 1); } var WhosTypingStore = assign({}, EventEmitter.prototype, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, getForCurrentThread: function(user) { var threadID = ThreadStore.getCurrentID(); return _whosTyping[threadID]; } }); WhosTypingStore.dispatchToken = ChatAppDispatcher.register(function(action) { switch(action.type) { // TODO need to make this work with threading // case ActionTypes.RECEIVE_START_TYPING: // var whosTyping = _whosTyping[action.threadID]; // if (!whosTyping) { // whosTyping = []; // _whosTyping[action.threadID] = whosTyping; // } // whosTyping.push(action.user); // WhosTypingStore.emitChange(); // break; // case ActionTypes.RECEIVE_STOP_TYPING: // _removeAuthor(action.threadID, action.user); // WhosTypingStore.emitChange(); // break; default: // do nothing } }); module.exports = WhosTypingStore;
JavaScript
0
@@ -885,9 +885,14 @@ ) %7B%0A -%09 + var @@ -940,37 +940,289 @@ - return _whosTyping%5BthreadID +// chatstates doesn't know about threads so we don't know when someone%0A // is typing in a particular thread. (prob easy to modify chatstates js to pass%0A // %3Cthread%3E in the message?)%0A let key = threadID.split(':').slice(0, 2).join(':');%0A return _whosTyping%5Bkey %5D;%0A @@ -1392,27 +1392,24 @@ reading%0A%0A - // case Action @@ -1435,27 +1435,24 @@ _TYPING:%0A - // var who @@ -1490,27 +1490,24 @@ readID%5D;%0A - // if (!wh @@ -1517,27 +1517,24 @@ yping) %7B%0A - // who @@ -1546,27 +1546,24 @@ ng = %5B%5D;%0A - // _wh @@ -1609,19 +1609,16 @@ %0A - // %7D%0A / @@ -1613,21 +1613,16 @@ %7D%0A - // who @@ -1644,34 +1644,73 @@ tion.user);%0A -// + console.log('typing', _whosTyping);%0A WhosTypingS @@ -1723,35 +1723,32 @@ mitChange();%0A - // break;%0A%0A @@ -1747,19 +1747,16 @@ ak;%0A%0A - // case Ac @@ -1785,27 +1785,24 @@ _TYPING:%0A - // _remove @@ -1839,26 +1839,65 @@ .user);%0A -// + console.log('typing', _whosTyping);%0A WhosTyp @@ -1922,19 +1922,16 @@ e();%0A - // bre
f1cfd96e63ed0368440cac2a53ead4b9352abcbe
Enable ServiceWorker back
_js/main/components/register-service-worker.js
_js/main/components/register-service-worker.js
/* VARS */ var humane = require('../libs/humane');// http://wavded.github.io/humane-js/ // enables debug logging in the browser script and Service Worker var isDebugEnabled = localStorage.debug || location.search.indexOf('debug') !== -1; /* LOGGING */ function log() { if (!isDebugEnabled) return; console.log.apply(console, addMessagePrefix('PAGE:', arguments)); } function logError() { if (!isDebugEnabled) return; console.error.apply(console, addMessagePrefix('PAGE:', arguments)); } function addMessagePrefix(prefix, args) { var res = Array.prototype.slice.apply(args); res.unshift(prefix); return res; } /* REGISTER WORKER */ //if ('serviceWorker' in navigator) { // let swPath = `/service-worker.js`; // navigator.serviceWorker.register( // swPath // ).then(function (registration) { // sendMessageToWorker({'---isDebugEnabled---': isDebugEnabled});// send debug state info // log(`Service Worker "${swPath}" registration successful with scope: ${registration.scope}`); // }).catch(function (error) { // // registration failed // logError(`Registration of Service Worker "${swPath}" failed with error`, error); // }); //} /*--- MESSAGING ---*/ // https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/post-message function sendMessageToWorker(message) { return new Promise(function (resolve, reject) { var messageChannel = new MessageChannel(); messageChannel.port1.onmessage = function (event) { if (event.data.error) { reject(event.data.error); } else { logError(`An error occured getting a message from SW`, event.data.error); resolve(event.data); } }; if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage( message, [messageChannel.port2] ); } else { logError(`Message sending to SW failed: navigator.serviceWorker.controller is`, navigator.serviceWorker.controller); } }).then(()=> { }, (err)=> { logError(`Message sending to SW failed with error`, err); }); } if ('serviceWorker' in navigator) { navigator.serviceWorker.addEventListener('message', function (event) { if (event.data['---notification---'] !== undefined) { humane.log(event.data['---notification---'], { addnCls: 'humane-libnotify-info', timeout: 5000, clickToClose: true }); } }); }
JavaScript
0
@@ -657,18 +657,16 @@ RKER */%0A -// if ('ser @@ -689,26 +689,24 @@ avigator) %7B%0A -// let swPa @@ -732,18 +732,16 @@ er.js%60;%0A -// navi @@ -770,18 +770,16 @@ gister(%0A -// @@ -785,18 +785,16 @@ swPath%0A -// ).th @@ -818,26 +818,24 @@ stration) %7B%0A -// send @@ -917,18 +917,16 @@ te info%0A -// @@ -1018,18 +1018,16 @@ ope%7D%60);%0A -// %7D).c @@ -1050,18 +1050,16 @@ rror) %7B%0A -// @@ -1081,18 +1081,16 @@ failed%0A -// @@ -1174,18 +1174,16 @@ r);%0A -// %7D);%0A //%7D%0A @@ -1178,18 +1178,16 @@ %7D);%0A -// %7D%0A%0A/*---
41a1cd954c14f7168a73f1dfe7f1d2f71ffa1ecf
Set query fix
erpnext/accounts/doctype/accounting_dimension/accounting_dimension.js
erpnext/accounts/doctype/accounting_dimension/accounting_dimension.js
// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.ui.form.on('Accounting Dimension', { refresh: function(frm) { if (!frm.is_new()) { frm.add_custom_button(__('Show {0}', [frm.doc.document_type]), function () { frappe.set_route("List", frm.doc.document_type); }); frm.set_query('document_type', () => { return { filters: { name: ['not in', ['Accounting Dimension', 'Project', 'Cost Center']] } }; }); let button = frm.doc.disabled ? "Enable" : "Disable"; frm.add_custom_button(__(button), function() { frm.set_value('disabled', 1 - frm.doc.disabled); frappe.call({ method: "erpnext.accounts.doctype.accounting_dimension.accounting_dimension.disable_dimension", args: { doc: frm.doc }, freeze: true, callback: function(r) { let message = frm.doc.disabled ? "Dimension Disabled" : "Dimension Enabled"; frm.save(); frappe.show_alert({message:__(message), indicator:'green'}); } }); }); } }, document_type: function(frm) { frm.set_value('label', frm.doc.document_type); frm.set_value('fieldname', frappe.model.scrub(frm.doc.document_type)); if (frm.is_new()){ let row = frappe.model.add_child(frm.doc, "Accounting Dimension Detail", "dimension_defaults"); row.reference_document = frm.doc.document_type; frm.refresh_fields("dimension_defaults"); } frappe.db.get_value('Accounting Dimension', {'document_type': frm.doc.document_type}, 'document_type', (r) => { if (r && r.document_type) { frm.set_df_property('document_type', 'description', "Document type is already set as dimension"); } }); }, }); frappe.ui.form.on('Accounting Dimension Detail', { dimension_defaults_add: function(frm, cdt, cdn) { let row = locals[cdt][cdn]; row.reference_document = frm.doc.document_type; } });
JavaScript
0.000434
@@ -190,173 +190,8 @@ ) %7B%0A -%09%09if (!frm.is_new()) %7B%0A%09%09%09frm.add_custom_button(__('Show %7B0%7D', %5Bfrm.doc.document_type%5D), function () %7B%0A%09%09%09%09frappe.set_route(%22List%22, frm.doc.document_type);%0A%09%09%09%7D);%0A%0A%09 %09%09fr @@ -230,17 +230,16 @@ =%3E %7B%0A%09%09%09 -%09 return %7B @@ -239,17 +239,16 @@ eturn %7B%0A -%09 %09%09%09%09filt @@ -250,25 +250,24 @@ %09filters: %7B%0A -%09 %09%09%09%09%09name: %5B @@ -329,23 +329,215 @@ ter' +, 'Accounting Dimension Detail' %5D%5D%0A%09%09 +%09%09%7D%0A %09%09%09%7D +; %0A%09%09 -%09%09%7D +%7D);%0A%0A%09%09if (!frm.is_new()) %7B%0A%09%09%09frm.add_custom_button(__('Show %7B0%7D', %5Bfrm.doc.document_type%5D), function () %7B%0A%09%09%09%09frappe.set_route(%22List%22, frm.doc.document_type) ;%0A%09%09