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
2bf39adf2efd7afdf156678e64efd25443951343
Improve style of the test suite
test/getCommands.spec.js
test/getCommands.spec.js
const path = require('path'); const expect = require('chai').expect; const getCommands = require('../src/getCommands'); const findPlugins = require('../src/findPlugins'); const mock = require('mock-require'); const mockFs = require('mock-fs'); const commands = require('./fixtures/commands'); const testPluginPath = path.join(process.cwd(), 'node_modules', 'rnpm-plugin-test'); const testPluginPath2 = path.join(process.cwd(), 'node_modules', 'rnpm-plugin-test-2'); const pjsonPath = path.join(__dirname, '..', 'package.json'); const pjson = { dependencies: { [path.basename(testPluginPath)]: '*', }, }; describe('getCommands', () => { beforeEach(() => { mock(pjsonPath, pjson); }); it('list of the commands should be a non-empty array', () => { mock(testPluginPath, commands.single); expect(getCommands()).to.be.not.empty; expect(getCommands()).to.be.an('array'); }); it('should export one command', () => { mock(testPluginPath, commands.single); expect(getCommands().length).to.be.equal(1); }); it('should export multiple commands', () => { mock(testPluginPath, commands.multiple); expect(getCommands().length).to.be.equal(2); }); it('should export unique list of commands by name', () => { mock(pjsonPath, { dependencies: { [path.basename(testPluginPath)]: '*', [path.basename(testPluginPath2)]: '*', }, }); mock(testPluginPath, commands.single); mock(testPluginPath2, commands.single); expect(getCommands().length).to.be.equal(1); }); it('should get commands specified by project plugins', () => { mockFs({ testDir: {} }); process.chdir('testDir'); mock(testPluginPath, commands.single); mock(path.join(process.cwd(), 'package.json'), pjson); mock( path.join(process.cwd(), 'node_modules', 'rnpm-plugin-test'), commands.multiple ); expect(getCommands().length).to.be.equal(2); process.chdir('../'); }); afterEach(mock.stopAll); });
JavaScript
0.000001
@@ -1648,40 +1648,8 @@ %7D);%0A -%0A process.chdir('testDir');%0A%0A @@ -1696,16 +1696,23 @@ mock( +%0A path.joi @@ -1727,16 +1727,27 @@ s.cwd(), + 'testDir', 'packag @@ -1755,22 +1755,33 @@ .json'), +%0A pjson +%0A );%0A m @@ -1807,32 +1807,43 @@ n(process.cwd(), + 'testDir', 'node_modules', @@ -1892,24 +1892,55 @@ ple%0A );%0A%0A + process.chdir('testDir');%0A%0A expect(g @@ -1999,24 +1999,46 @@ dir('../');%0A + mockFs.restore();%0A %7D);%0A%0A aft
afd1b15205049c3a7eeef84b3991479a6effa43e
Fix tests for getCommands
test/getCommands.spec.js
test/getCommands.spec.js
const path = require('path'); const expect = require('chai').expect; const getCommands = require('../src/getCommands'); const findPlugins = require('../src/findPlugins'); const mock = require('mock-require'); const mockFs = require('mock-fs'); const sinon = require('sinon'); const commands = require('./fixtures/commands'); const testPluginPath = path.join(process.cwd(), 'node_modules', 'rnpm-plugin-test'); const testPluginPath2 = path.join(process.cwd(), 'node_modules', 'rnpm-plugin-test-2'); const pjsonPath = path.join(__dirname, '..', 'package.json'); const pjson = { dependencies: { [path.basename(testPluginPath)]: '*', }, }; describe('getCommands', () => { beforeEach(() => { mock(pjsonPath, pjson); }); it('list of the commands should be a non-empty array', () => { mock(testPluginPath, commands.single); expect(getCommands()).to.be.not.empty; expect(getCommands()).to.be.an('array'); }); it('should export one command', () => { mock(testPluginPath, commands.single); expect(getCommands().length).to.be.equal(1); }); it('should export multiple commands', () => { mock(testPluginPath, commands.multiple); expect(getCommands().length).to.be.equal(2); }); it('should export unique list of commands by name', () => { mock(pjsonPath, { dependencies: { [path.basename(testPluginPath)]: '*', [path.basename(testPluginPath2)]: '*', }, }); mock(testPluginPath, commands.single); mock(testPluginPath2, commands.single); expect(getCommands().length).to.be.equal(1); }); it('should get commands specified by project plugins', () => { mockFs({ testDir: {} }); mock(testPluginPath, commands.single); mock( path.join(process.cwd(), 'testDir', 'package.json'), pjson ); mock( path.join(process.cwd(), 'testDir', 'node_modules', 'rnpm-plugin-test'), commands.multiple ); const testCwd = path.join(process.cwd(), 'testDir'); const stub = sinon.stub(process, 'cwd').returns(testCwd); expect(getCommands().length).to.be.equal(2); stub.restore(); mockFs.restore(); }); afterEach(mock.stopAll); });
JavaScript
0.000002
@@ -317,36 +317,38 @@ mmands');%0Aconst -t +n est +ed PluginPath = pat @@ -412,20 +412,22 @@ ;%0Aconst -t +n est +ed PluginPa @@ -492,24 +492,177 @@ n-test-2');%0A +const flatPluginPath = path.join(process.cwd(), '..', 'rnpm-plugin-test');%0Aconst flatPluginPath2 = path.join(process.cwd(), '..', 'rnpm-plugin-test-2');%0A const pjsonP @@ -757,36 +757,38 @@ %5Bpath.basename( -t +n est +ed PluginPath)%5D: '* @@ -881,16 +881,104 @@ pjson);%0A + mock(nestedPluginPath, commands.single);%0A mock(flatPluginPath, commands.single);%0A %7D);%0A%0A @@ -1045,51 +1045,8 @@ %3E %7B%0A - mock(testPluginPath, commands.single);%0A @@ -1182,51 +1182,8 @@ %3E %7B%0A - mock(testPluginPath, commands.single);%0A @@ -1283,35 +1283,82 @@ ) =%3E %7B%0A mock( -tes +nestedPluginPath, commands.multiple);%0A mock(fla tPluginPath, com @@ -1370,24 +1370,25 @@ .multiple);%0A +%0A expect(g @@ -1552,36 +1552,38 @@ %5Bpath.basename( -t +n est +ed PluginPath)%5D: '* @@ -1608,20 +1608,22 @@ asename( -t +n est +ed PluginPa @@ -1652,36 +1652,38 @@ %7D);%0A mock( -t +n est +ed PluginPath, comm @@ -1668,32 +1668,33 @@ nestedPluginPath +2 , commands.singl @@ -1698,35 +1698,35 @@ ngle);%0A mock( -tes +fla tPluginPath2, co @@ -1896,51 +1896,8 @@ %7D);%0A - mock(testPluginPath, commands.single);%0A @@ -2099,16 +2099,126 @@ e%0A ); +%0A mock(%0A path.join(process.cwd(), 'testDir', '..', 'rnpm-plugin-test'),%0A commands.multiple%0A ); %0A%0A co
36e2b977da9ad4f1bdf7ab12d3365fa18b116e39
fix filtering events by venue. part of #692
lib/Filtering.js
lib/Filtering.js
var Predicates = { string: function(param) { return { merge: function(other) { return other; }, without: function(predicate) { return false; }, get: function() { return param; }, param: function() { return param; }, query: function() { return param; }, equals: function(other) { return param === other.get(); } }; }, id: function(param) { if (param == 'all') return false; return Predicates.string(param); }, ids: function(param) { var make = function(ids) { return { merge: function(other) { return make(_.union(ids, other.get())); }, without: function(predicate) { ids = _.difference(ids, predicate.get()); if (ids.length === 0) return false; return make(ids); }, get: function() { return ids; }, param: function() { return ids.join(','); }, query: function() { return ids; }, equals: function(other) { var otherIds = other.get(); return ( ids.length === otherIds.length && _.intersection(ids, otherIds).length === ids.length ); } }; }; return make(_.uniq(param.split(','))); }, require: function(param) { if (!param) return false; return { merge: function(other) { return other; }, without: function(predicate) { return false; }, get: function() { return true; }, param: function() { return '1'; }, query: function() { return true; }, equals: function(other) { return true; } }; }, flag: function(param) { if (param === undefined) return false; var state = !!parseInt(param, 2); // boolean return { merge: function(other) { return other; }, without: function(predicate) { return false; }, get: function() { return state; }, param: function() { return state ? 1 : 0; }, query: function() { return state; }, equals: function(other) { return other.get() === state; } }; }, date: function(param) { if (!param) return undefined; var date = moment(param); // Param is ISO date or moment() object if (!date.isValid()) return undefined; date.startOf('day'); return { merge: function(other) { return other; }, without: function(predicate) { return false; }, get: function() { return moment(date); }, param: function() { return date.format('YYYY-MM-DD'); }, query: function() { return date.toDate(); }, equals: function(other) { return date.isSame(other.get()); } }; }, }; CoursePredicates = { region: Predicates.id, search: Predicates.string, group: Predicates.string, categories: Predicates.ids, upcomingEvent: Predicates.require, needsMentor: Predicates.require, needsHost: Predicates.require, internal: Predicates.flag }; EventPredicates = { course: Predicates.id, region: Predicates.id, search: Predicates.string, categories: Predicates.ids, group: Predicates.id, groups: Predicates.ids, location: Predicates.string, room: Predicates.string, start: Predicates.date, after: Predicates.date, end: Predicates.date, internal: Predicates.flag, }; VenuePredicates = { region: Predicates.id, }; Filtering = function(availablePredicates) { var self = {}; var predicates = {}; var settledPredicates = {}; var dep = new Tracker.Dependency(); self.clear = function() { predicates = {}; return this; }; self.get = function(name) { if (Tracker.active) dep.depend(); if (!settledPredicates[name]) return undefined; return settledPredicates[name].get(); }; self.add = function(name, param) { if (!availablePredicates[name]) throw "No predicate "+name; var toAdd = availablePredicates[name](param); if (toAdd === undefined) return; // Filter construction failed, leave as-is if (predicates[name]) { predicates[name] = predicates[name].merge(toAdd); } else { predicates[name] = toAdd; } if (!predicates[name]) delete predicates[name]; return self; }; self.read = function(list) { for (var name in list) { if (availablePredicates[name]) { self.add(name, list[name]); } } return this; }; self.remove = function(name, param) { var toRemove = availablePredicates[name](param); if (predicates[name]) { predicates[name] = predicates[name].without(toRemove); } if (!predicates[name]) delete predicates[name]; return self; }; self.disable = function(name) { delete predicates[name]; return self; }; self.done = function() { var settled = settledPredicates; settledPredicates = _.clone(predicates); // Now find out whether the predicates changed var settlingNames = Object.keys(predicates); var settledNames = Object.keys(settled); var same = settlingNames.length === settledNames.length && _.intersection(settlingNames, settledNames).length === settlingNames.length; if (same) { // Look closer for (var name in predicates) { same = predicates[name].equals(settled[name]); if (!same) break; } } if (!same) dep.changed(); return self; }; self.toParams = function() { if (Tracker.active) dep.depend(); var params = {}; for (var name in settledPredicates) { params[name] = settledPredicates[name].param(); } return params; }; self.toQuery = function() { if (Tracker.active) dep.depend(); var query = {}; for (var name in settledPredicates) { query[name] = settledPredicates[name].query(); } return query; }; return self; };
JavaScript
0.000001
@@ -2806,16 +2806,13 @@ s,%0A%09 -location +venue : P @@ -5288,8 +5288,9 @@ self;%0A%7D; +%0A
d21e70e4dd4e35f0e65d74078f4f557159d6abd9
Use jQuery oembed all to render OEmbed content
posts/client/item/item.js
posts/client/item/item.js
import Oembed from 'oembed-all'; Template.postItem.onRendered(function () { // Get reference to template instance const instance = this; // Get Post ID from template instance const postId = instance.data.post._id; // Select post DOM element const postElement = document.querySelector(`#${postId}`); // Render post element OEmbed content const oembed = new Oembed(postElement); });
JavaScript
0
@@ -223,22 +223,32 @@ ;%0A%0A // -Select +Get reference to post DO @@ -283,30 +283,18 @@ t = -document.querySelector +instance.$ (%60#$ @@ -322,21 +322,8 @@ der -post element OEmb @@ -339,34 +339,8 @@ t%0A -const oembed = new Oembed( post @@ -346,15 +346,23 @@ tElement +.oembed( );%0A%7D);%0A
180df034f4c45d1efbb79537a087e53b84020497
I am an idiot
server/controllers/fb.js
server/controllers/fb.js
import fetch from 'isomorphic-fetch'; const VERIFY_TOKEN = process.env.VERIFY_TOKEN const PAGE_TOKEN = process.env.PAGE_TOKEN const MESSAGES_PATH = 'https://graph.facebook.com/v2.6/me/messages' export function verify (req, res) { console.log('Request query:', req.query) if (req.query['hub.verify_token'] === VERIFY_TOKEN) { res.send(req.query['hub.challenge']); return; } res.send('oops!'); } export function listen (req, res) { const events = req.body.entry[0].messaging console.log('EVENTS!', events) let promises = events .filter(e => { return (e.sender && e.sender.id) && (e.message && e.message.text) }) .map(e => { return textMessage({ id: e.sender.id, text: e.message.text }) }) Promise.all(promises) .then(() => res.sendStatus(200)) .catch(err => { console.log('ERROR!', err); res.sendStatus(500); }) } function textMessage(id, text) { const message = { recipient: { id }, message: { text } } const json = JSON.stringify(message); console.log('Attempting to send message:', message) console.log('To path: ', `${MESSAGES_PATH}?access_token=${PAGE_TOKEN}`) return fetch(`${MESSAGES_PATH}?access_token=${PAGE_TOKEN}`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: json });
JavaScript
0.998675
@@ -29,17 +29,47 @@ c-fetch' -; +%0Aimport Promise from 'bluebird' %0A%0Aconst @@ -1416,10 +1416,12 @@ on%0A %7D); +%0A%7D %0A%0A
b0c3859699cfcbe2eb059d9f02532cc1b8d3af0a
Fix a test
test/commands/register.js
test/commands/register.js
var Q = require('q'); var expect = require('expect.js'); var helpers = require('../helpers'); var register = helpers.command('register'); var fakeRepositoryFactory = function (canonicalDir, pkgMeta) { function FakeRepository() { } FakeRepository.prototype.fetch = function () { return Q.fcall(function () { return [canonicalDir, pkgMeta]; }); }; FakeRepository.prototype.getRegistryClient = function () { return { register: function (name, url, cb) { cb(null, { name: name, url: url }); } }; }; return FakeRepository; }; var register = helpers.command('register'); var registerFactory = function (canonicalDir, pkgMeta) { return helpers.command('register', { '../core/PackageRepository': fakeRepositoryFactory( canonicalDir, pkgMeta ) }); }; describe('bower register', function () { var mainPackage = new helpers.TempDir({ 'bower.json': { name: 'package' } }); it('correctly reads arguments', function () { expect(register.readOptions(['jquery', 'url'])) .to.eql(['jquery', 'url']); }); it('errors if name is not provided', function () { return helpers.run(register).fail(function (reason) { expect(reason.message).to.be('Usage: bower register <name> <url>'); expect(reason.code).to.be('EINVFORMAT'); }); }); it('errors if url is not provided', function () { return helpers.run(register, ['some-name']) .fail(function (reason) { expect(reason.message).to.be('Usage: bower register <name> <url>'); expect(reason.code).to.be('EINVFORMAT'); }); }); it('errors if trying to register private package', function () { mainPackage.prepare({ 'bower.json': { private: true } }); var register = registerFactory(mainPackage.path, mainPackage.meta()); return helpers.run(register, ['some-name', 'git://fake-url.git']) .fail(function (reason) { expect(reason.message).to.be('The package you are trying to register is marked as private'); expect(reason.code).to.be('EPRIV'); }); }); it('should call registry client with name and url', function () { mainPackage.prepare(); var register = registerFactory(mainPackage.path, mainPackage.meta()); return helpers.run(register, ['some-name', 'git://fake-url.git']) .spread(function (result) { expect(result).to.eql({ // Result from register action on stub name: 'some-name', url: 'git://fake-url.git' }); }); }); it('should call registry client with name and github source', function () { mainPackage.prepare(); var register = registerFactory(mainPackage.path, mainPackage.meta()); return helpers.run(register, ['some-name', 'some-name/repo']) .spread(function (result) { expect(result).to.eql({ // Result from register action on stub name: 'some-name', url: '[email protected]:some-name/repo.git' }); }); }); it('should support single-char github names', function () { mainPackage.prepare(); var register = registerFactory(mainPackage.path, mainPackage.meta()); return helpers.run(register, ['some-name', 'a/b']) .spread(function (result) { expect(result).to.eql({ // Result from register action on stub name: 'some-name', url: '[email protected]:a/b.git' }); }); }); it('should confirm in interactive mode', function () { mainPackage.prepare(); var register = registerFactory(mainPackage.path, mainPackage.meta()); var promise = helpers.run(register, ['some-name', 'git://fake-url.git', { interactive: true }] ); return helpers.expectEvent(promise.logger, 'confirm') .spread(function (e) { expect(e.type).to.be('confirm'); expect(e.message).to.be('Registering a package will make it installable via the registry (https://registry.bower.io, continue?'); expect(e.default).to.be(true); }); }); it('should skip confirming when forcing', function () { mainPackage.prepare(); var register = registerFactory(mainPackage.path, mainPackage.meta()); return helpers.run(register, ['some-name', 'git://fake-url.git', { interactive: true, force: true } ] ); }); });
JavaScript
0.999999
@@ -4259,16 +4259,17 @@ bower.io +) , contin
9758163842b91c0ebe4ab91fae6c6515a7d5a4a1
Fix bug in s3 syncing.
lib/Site-sync.js
lib/Site-sync.js
var request = require('superagent'), mkdirp = require('mkdirp'), fs = require('fs'), path = require('path'), async = require('async'), knox = require('knox'), hashFile = require('hash_file'), crypto = require('crypto'); var Page = require('./Page'), Site = require('./Site'), File = require('./File'), fsUtil = require('./fs-util'), listBucket = require('./listBucket'); Site.prototype.syncS3 = function(callback) { if (!this.settings.s3key || !this.settings.s3secret || !this.settings.s3bucket) return new Error('S3 settings not found.'); var site = this, rootUrl = this.root.url, s3List = {}; var client = knox.createClient({ key: this.settings.s3key, secret: this.settings.s3secret, bucket: this.settings.s3bucket, region: this.settings.s3region || 'us-standard', // We have to set secure to false, when the bucket name has .'s in it // because Amazon doesn't like it secure: this.settings.s3bucket.indexOf('.') == -1 }); var util = { escapeRegex: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }, getPageHtml: function(page, callback) { request .get(page.href()) .buffer() .end(function(err, res) { if (err) return callback(err); var regex = new RegExp(util.escapeRegex(page.site.url), 'g'); var html = res.text.replace(regex, ''); return callback(null, html); }); }, listFiles: function(callback) { console.log('Getting S3 bucket list'); listBucket(client, function(err, results) { results.forEach(function(result) { s3List[result.Key] = result.ETag; }); callback(); }); }, hash: function(object, callback) { if (object.file) { hashFile(object.file, callback); } else { callback(null, crypto.createHash('md5').update(object.string).digest('hex')); } }, deleteS3: function(uri, callback) { client.deleteFile(uri, function(err, res) { console.log('Deleted', uri); callback(err); }); }, put: function(object, remoteUri, callback) { var done = function() { delete s3List[remoteUri]; process.nextTick(callback); }; var s3Options = { 'x-amz-acl': 'public-read' }; util.hash(object, function(err, hash) { if (err) throw err; // Skip the file if the hashes match (note that Amazon // puts quotes around their ETags, so we have to do the same) if (s3List[remoteUri] && s3List[remoteUri] == '"' + hash + '"') { done(); } else { console.log('Uploading', remoteUri); if (object.file) { client.putFile(object.file, remoteUri, s3Options, done); } else { s3Options['Content-Type'] = 'text/html'; client.putBuffer(object.string, remoteUri, s3Options, done); } } }); }, putHtml: function(page, callback) { var remoteUri = path.join(path.relative(rootUrl, page.url), 'index.html'); util.getPageHtml(page, function(err, html) { util.put({ string: html }, remoteUri, callback); }); }, addToQueue: function(task) { if (task instanceof Page) { pageQueue.push(task); } else { queue.push(task); } }, uploadAssets: function() { util.addToQueue({directory: site.getUri('assets')}); queue.drain = function(err) { var toDelete = []; for (var uri in s3List) toDelete.push(uri); async.eachLimit(toDelete, 10, util.deleteS3, function() { if (callback) callback(); }); }; }, queuePages: function(page) { if (!page) page = site.root; util.addToQueue(page); for (var i = 0; i < page.children.length; i++) util.queuePages(page.children[i]); } }; var pageQueue = async.queue(function(page, done) { page.files.forEach(util.addToQueue); util.putHtml(page, done); }, 10); var queue = async.queue(function(task, done) { var url; if (task instanceof File) { url = path.relative(rootUrl, task.getUrl()); util.put({ file: task.uri }, url, function(err) { done(err); }); } else if (task.file) { url = path.relative(site.getUri(), task.file); util.put(task, url, done); } else { fsUtil.recursiveDirectoryList(task.directory, function(err, found) { found.files.forEach(function(file) { util.addToQueue({file: file}); }); done(); }); } }, 10); // When the page queue has drained, check if there are any thumbnails left // to be rendered: pageQueue.drain = function(err) { // TODO: make thumbnails queue site specific if(site.thumbnails.queueLength > 0) { console.log('Waiting for thumbnails to finish exporting...'); site.thumbnails.on('done', util.uploadAssets); } else { util.uploadAssets(); } }; util.listFiles(util.queuePages); };
JavaScript
0
@@ -3883,16 +3883,11 @@ ask. -getUrl() +url );%0A%09
f54afb86f022f56640e15559af7f8784a2e49a85
fix sorting; improve display more
shootout.js
shootout.js
var competition = require('./the_competitors.js'), valid = require('testdata-valid-email'), invalid = require('testdata-invalid-email'); var maxscore = 0; function verify_one(X) { var result = { errors: [] }, score = 0; maxscore = 0; valid.map( function(V) { if ( X.test(V)) { ++score; } else { result.errors.push(V); } ++maxscore; } ); invalid.map( function(I) { if (!X.test(I)) { ++score; } else { result.errors.push(I); } ++maxscore; } ); result.name = X.name; result.score = score; return result; } function verify(shortForm) { var result = competition.map( verify_one ); if (shortForm || true) { for (var i in result) { delete result[i].errors; } } return result; } var res = verify(); res.sort(function(X,Y) { return X.score < Y.score; }); console.log('Of a possible ' + maxscore.toString() + ':'); res.map(function(X) { console.log(' ' + X.name + ': ' + X.score); });
JavaScript
0
@@ -794,21 +794,16 @@ verify() -;%0Ares .sort(fu @@ -840,16 +840,49 @@ Y.score +? 1 : (X.score %3E Y.score? -1 : 0) ; %7D);%0A%0Ac @@ -988,28 +988,27 @@ + X. -nam +scor e + ' -: ' + X. -scor +nam e);%0A
5cfba21cbb3b506820c60cce0d1fcb8c721fcd8f
Reset counters in test to make it more readable
test/local-state-test.js
test/local-state-test.js
var tape = require("tape"), jsdom = require("jsdom"), d3 = Object.assign(require("../"), require("d3-selection")); /************************************* ************ Components ************* *************************************/ // Local state. var spinnerCreated = 0, spinnerDestroyed = 0, spinnerTimerState = "", spinnerText = "", spinnerSetState, spinner = d3.component("div") .create(function (selection, setState){ spinnerSetState = setState; spinnerCreated++; spinnerTimerState = "running"; setState({ timer: spinnerTimerState }); }) .render(function (selection, props, state){ spinnerText = "Timer is " + state.timer; selection.text(spinnerText); }) .destroy(function(state){ spinnerDestroyed++; }); // For checking the default value of the state argument. var stateValue, stateValueCheck = d3.component("div") .render(function (selection, props, state){ stateValue = state; }); /************************************* ************** Tests **************** *************************************/ tape("Local state.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); // Create. div.call(spinner); test.equal(spinnerCreated, 1); test.equal(spinnerDestroyed, 0); test.equal(spinnerTimerState, "running"); test.equal(spinnerText, "Timer is running"); test.equal(div.html(), "<div>Timer is running</div>"); // Re-render on setState(). spinnerSetState({ timer: "running well"}); test.equal(spinnerText, "Timer is running well"); test.equal(div.html(), "<div>Timer is running well</div>"); test.equal(spinnerCreated, 1); test.equal(spinnerDestroyed, 0); // Destroy. div.call(spinner, []); test.equal(spinnerCreated, 1); test.equal(spinnerDestroyed, 1); test.equal(spinnerText, "Timer is running well"); test.equal(div.html(), ""); test.end(); }); tape("State value default.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(stateValueCheck); test.equal(typeof stateValue, "object"); test.equal(Object.keys(stateValue).length, 0); test.end(); });
JavaScript
0
@@ -270,20 +270,16 @@ rCreated - = 0 ,%0A sp @@ -296,12 +296,8 @@ oyed - = 0 ,%0A @@ -1268,16 +1268,57 @@ Create.%0A + spinnerCreated = spinnerDestroyed = 0;%0A div.ca @@ -1577,16 +1577,57 @@ tate().%0A + spinnerCreated = spinnerDestroyed = 0;%0A spinne @@ -1798,33 +1798,33 @@ spinnerCreated, -1 +0 );%0A test.equal( @@ -1860,16 +1860,57 @@ estroy.%0A + spinnerCreated = spinnerDestroyed = 0;%0A div.ca @@ -1947,33 +1947,33 @@ spinnerCreated, -1 +0 );%0A test.equal(
e09bfd2da1e9fa8c0e0f92b0c17996e1e282b87b
Update bits-oder-functions.js
js/bits-oder-functions.js
js/bits-oder-functions.js
//////////////////////////////////////////////////////////////////////////////////////////////////////////// function oid() { //Get Token Balance $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens"); //Load Wallet $(".walletToast").remove(); if (localStorage.getItem('bits-user-name') == null) { console.log("Not logged in") } else { Materialize.toast('Unlock wallet <span class="right" style="color:yellow;" onclick="unlockWallet()">Unlock</span>', null, 'walletToast') } if (window.location.hash != undefined) { //check if hash is oid var type = window.location.hash.substr(1); // split the hash var fields = type.split('='); var htpe = fields[0]; var hval = fields[1]; if (htpe == "oid") { //get the shop and the oder details var shop = getBitsWinOpt('s') // oid $(".otitle").html(""); $(".otitle").append("Your Order"); $(".of").html(""); //var uid = JSON.parseInt(hval) var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name")); od.onsuccess = function (event) { try { var odData = JSON.parse(event.target.result); for (var ii = 0; ii < odData.length; ++ii) { var xx = odData[ii].items var xid = odData[ii].id //makeOrder(products) // match oid to url id var urloid = getBitsOpt("oid") if (urloid == xid) { makeOrder(JSON.parse(xx), odData[ii].location) } else { console.log("no match") } } } catch (err) {} }; od.onerror = function () {}; //makeOrder(hval) } else { console.log("we dont know this hash") } } else {} } function unlockWallet() { walletFunctions(90).then(function (e) { loadGdrive(); $(".walletToast").remove(); }) } function getUserOders(f) { doFetch({ action: 'getAllOrders', uid: localStorage.getItem("bits-user-name") }).then(function (e) { if (e.status == "ok") { xx = e.data; //var earnedPoints = 0; for (var ii in allTokens) { allTokens[ii].totalEarned = 0; } for (var ii in xx) { var items = xx[ii].points; try { var typeofCoin = JSON.parse(items).coin; } catch (err) { console.log(err); continue; } try { var purchasePoints = JSON.parse(items).purchase; if (purchasePoints == undefined) { var purchasePoints = 0; } } catch (err) { console.log('this order does not have any purchase rewards', err); var purchasePoints = 0; } try { var deliveryPoints = JSON.parse(items).delivery; if (deliveryPoints == undefined) { var deliveryPoints = 0; } } catch (err) { console.log('this order does not have any delivery rewards', err); var deliveryPoints = 0; } try { allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints; } catch (err) { console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin); continue; } console.log(typeofCoin, purchasePoints, deliveryPoints); }; var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name")); setdb.onsuccess = function () { oid(); } setTimeout(function () { updateEarnedTokens(f) }, 1500); } else { swal("Cancelled", "an error occcured", "error"); } }) } // var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name")); // function updateEarnedTokens(f) { $('.coinlist').html(''); var at = allTokens['allContracts']; var i = 0; var tCe = 0; tBal = 0; for(var i in at) { if(!(location.origin+'/').includes(allTokens[at[i]].webpage)){ continue; } try{ var rate = allTokens[at[i]].rate; var coinName = allTokens[at[i]].name; //if i have 1000 kobos //var koboBalance = 1000; // console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES'); var koboRate = Math.floor(rate * baseX); var qq = rate * baseX; var xx = qq.toFixed(2); var coinId = at[i]; var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals)); if (tA > 0) { //only display the coin if the user has a balance $('.coinlist').append('<span><div class="coinImg" style=" position: absolute ;margin-top: 5px;"><img src="/bitsAssets/images/currencies/' + coinName + '.png" alt="" style=" padding-left: 12px; height:30px;"></div><a href="" class="" class="" onclick=""><span style=" padding-left: 42px; text-transform: capitalize; ">' + coinName + '</span><span class="coin-' + coinId + '-bal" style=" float:right; line-height: 3.3;position: absolute;right: 15px;"></span></a></span>') $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5)); } $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd); tBal = tBal + (tA * allTokens[coinId].rate * baseX); }catch(e){ console.log(e) } i++; } $('.balance-coins').html('').append(numberify(tBal,2) + ' ' + baseCd); } //Check Bal Interval var checkBal = window.setInterval(function () { if ($("#checkBal")[0].innerHTML == "") { updateEarnedTokens() } else { clearInterval(checkBal); } }, 7000);
JavaScript
0.000001
@@ -4825,16 +4825,26 @@ n at) %7B%0A +%0Atry%7B%0A if(!(loc @@ -4916,21 +4916,16 @@ e;%0A %7D%0A -try%7B%0A
ac865c37ea378fd32841b174d138a8f9d52564b6
Copy progress is broken * tell yui compressor to not remove the comment with the Velocity code when minifying the JavaScript
xwiki-platform-core/xwiki-platform-web/src/main/webapp/resources/uicomponents/job/job.js
xwiki-platform-core/xwiki-platform-web/src/main/webapp/resources/uicomponents/job/job.js
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* #set ($jsExtension = '.min') #if (!$services.debug.minify) #set ($jsExtension = '') #end */ require.config({ paths: { JobRunner: '$!services.webjars.url("org.xwiki.platform:xwiki-platform-job-webjar", "jobRunner$jsExtension")' } }); require(['jquery', 'xwiki-meta', 'JobRunner'], function($, xm, JobRunner) { 'use strict'; var updateProgress = function(jobUI, job) { var percent = Math.floor((job.progress.offset || 0) * 100); jobUI.find('.ui-progress-bar').css('width', percent + '%'); var jobLog = job.log.items || []; if (jobLog.size() > 0) { jobUI.find('.ui-progress-message').html(jobLog[jobLog.size() - 1].renderedMessage); } }; var updateQuestion = function(jobUI, job, answerCallback) { var jobQuestion = jobUI.find('.ui-question'); if (typeof answerCallback === 'function') { // Display the question var displayerURL = "${request.contextPath}/job/wiki/" + xm.wiki + "/question/" + job.id.join('/'); // Remember the answer callback jobQuestion.data('answerCallback', answerCallback); $.ajax(displayerURL).done($.proxy(updateQuestionContent, jobQuestion)); } else { jobQuestion.empty(); } }; var updateQuestionContent = function(data) { var jobQuestion = $(this); // Replace the question div content with the data from the request jobQuestion.html(data); // Indicate that a new question has been loaded jobQuestion.trigger('job:question:loaded'); }; var updateLog = function(jobUI, job) { var jobLog = job.log.items || []; var jobLogUI = jobUI.find('.log'); if (job.log.offset === 0) { jobLogUI.html(''); } jobLogUI.find('.log-item-loading').removeClass('log-item-loading'); $.each(jobLog, function(index, item) { var classNames = ['log-item', 'log-item-' + item.level]; if (job.state !== 'FINISHED' && index === jobLog.size() - 1) { classNames.push('log-item-loading'); } $(document.createElement('li')).addClass(classNames.join(' ')).html(item.renderedMessage).appendTo(jobLogUI); }) }; var resolveAnswerProperties = function(properties, questionForm) { if (typeof properties === 'function') { return properties.bind(questionForm)(); } return properties; } var createAnswerProperties = function(questionForm) { // Create request parameters var properties = {}; // Add form inputs (either data based on input elements based) var dataProperties = questionForm.data('job-answer-properties'); if (dataProperties) { addCustomProperties(properties, resolveAnswerProperties(dataProperties, questionForm)); } else { addFormInputs(properties, questionForm); } // Add extra values var dataPropertiesExtra = questionForm.data('job-answer-properties-extra'); if (dataPropertiesExtra) { addCustomProperties(properties, resolveAnswerProperties(dataPropertiesExtra, questionForm)); } return properties; } var addCustomProperties = function(properties, extra) { $.each(extra, function(key, value) { properties['qproperty_' + key] = value; }); }; var addFormInputs = function(properties, questionForm) { questionForm.serializeArray().each(function(entry) { var propertyValue = properties[entry.name]; if (propertyValue) { if (Array.isArray(propertyValue)) { propertyValue.push(entry.value); } else { propertyValue = [propertyValue, entry.value]; } } else { propertyValue = entry.value; } properties[entry.name] = propertyValue; }); }; var onQuestionAnswer = function(event) { // Disable standard form behavior event.preventDefault(); var button = $(this); var questionForm = button.parents('.form-question'); // Disable other buttons questionForm.find('btAnswerConfirm').prop('disabled', true); questionForm.find('btAnswerCancel').prop('disabled', true); if (questionForm.length) { var questionUI = questionForm.parents('.ui-question'); if (questionUI.length) { var answerCallback = questionUI.data('answerCallback'); if (typeof answerCallback === 'function') { var createAnswerRequest = questionForm.data('job-answer-createRequest'); if (createAnswerRequest) { answerCallback(createAnswerRequest); } else { var properties = createAnswerProperties(questionForm); var answeringNotification = "$escapetool.javascript($services.localization.render('job.question.notification.answering'))"; // Set cancel marker if needed if (button.hasClass('btAnswerCancel')) { properties.cancel = 'true'; answeringNotification = "$escapetool.javascript($services.localization.render('job.question.notification.canceling'))"; } var notif = new XWiki.widgets.Notification( answeringNotification, 'inprogress' ); // Send the answer answerCallback(properties).done(new function() { notif.hide(); }); } } } } }; var updateStatus = function(job, answerCallback) { var jobUI = $(this); updateProgress(jobUI, job); updateQuestion(jobUI, job, answerCallback); updateLog(jobUI, job); }; var notifyJobDone = function(job) { var jobUI = $(this); jobUI.find('.ui-progress').replaceWith(job.message); }; var notifyConnectionFailure = function() { }; $('.job-status').has('.ui-progress').each(function() { var jobStatus = $(this); var url = jobStatus.attr('data-url'); if (url !== '') { var jobLog = jobStatus.find('.log'); var runnerConfig = {}; runnerConfig.createStatusRequest = function() { return { url: url, data: { 'logOffset': jobLog.find('.log-item').size() } }; }; // Handle various question related actions var jobQuestion = jobStatus.find('.ui-question'); if (jobQuestion.length) { jobQuestion.on('click', '.btAnswerConfirm', onQuestionAnswer); jobQuestion.on('click', '.btAnswerCancel', onQuestionAnswer); runnerConfig.createAnswerRequest = function(jobId, data) { if (typeof data === 'function') { return data(); } else { var answerURL = '${request.contextPath}/job/question/' + jobId.join('/'); return { url: answerURL, data: data }; } }; } new JobRunner(runnerConfig).resume() .progress($.proxy(updateStatus, this)) .done($.proxy(notifyJobDone, this)) .fail($.proxy(notifyConnectionFailure, this)); } }); });
JavaScript
0
@@ -889,16 +889,17 @@ .%0A */%0A/* +! %0A#set ($
a3fe38912ad35a469b5114e3536bbde155738f41
Remove change in web config
server/config/servers/web.js
server/config/servers/web.js
'use strict' var os = require('os') exports.default = { servers: { web: function (api) { return { enabled: true, // HTTP or HTTPS? secure: false, // Passed to https.createServer if secure=true. Should contain SSL certificates serverOptions: {}, // Should we redirect all traffic to the first host in this array if hte request header doesn't match? // i.e.: [ 'https://www.site.com' ] allowedRequestHosts: process.env.ALLOWED_HOSTS ? process.env.ALLOWED_HOSTS.split(',') : [], // Port or Socket Path port: process.env.PORT || 5000, // Which IP to listen on (use '0.0.0.0' for all '::' for all on ipv4 and ipv6) // Set to `null` when listening to socket bindIP: '0.0.0.0', // Any additional headers you want actionhero to respond with httpHeaders: { 'X-Powered-By': api.config.general.serverName, 'Access-Control-Allow-Origin': 'http://192.168.0.105:9966', 'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE', 'Access-Control-Allow-Headers': 'Content-Type, X-SB-CSRF-Token, Language', 'Access-Control-Allow-Credentials': 'true' }, // Route that actions will be served from secondary route against this route will be treated as actions, // IE: /api/?action=test == /api/test/ urlPathForActions: 'api', // Route that static files will be served from // path (relative to your project root) to serve static content from // set to `null` to disable the file server entirely urlPathForFiles: 'public', // When visiting the root URL, should visitors see 'api' or 'file'? // Visitors can always visit /api and /public as normal rootEndpointType: 'file', // simple routing also adds an 'all' route which matches /api/:action for all actions simpleRouting: false, // queryRouting allows an action to be defined via a URL param, ie: /api?action=:action queryRouting: false, // The header which will be returned for all flat file served from /public defined in seconds flatFileCacheDuration: 60, // Add an etag header to requested flat files which acts as fingerprint that changes when the file is updated; // Client will revalidate the fingerprint at latest after flatFileCacheDuration and reload it if the etag (and therfore the file) changed // or continue to use the cached file if it's still valid enableEtag: true, // How many times should we try to boot the server? // This might happen if the port is in use by another process or the socketfile is claimed bootAttempts: 1, // Settings for determining the id of an http(s) request (browser-fingerprint) fingerprintOptions: { cookieKey: 'sessionID', toSetCookie: true, onlyStaticElements: false, settings: { path: '/', expires: 3600000 } }, // Options to be applied to incoming file uploads. // More options and details at https://github.com/felixge/node-formidable formOptions: { uploadDir: os.tmpdir(), keepExtensions: false, maxFieldsSize: 1024 * 1024 * 100 }, // Should we pad JSON responses with whitespace to make them more human-readable? // set to null to disable padding: 2, // Options to configure metadata in responses metadataOptions: { serverInformation: true, requesterInformation: true }, // When true, returnErrorCodes will modify the response header for http(s) clients if connection.error is not null. // You can also set connection.rawConnection.responseHttpCode to specify a code per request. returnErrorCodes: true, // should this node server attempt to gzip responses if the client can accept them? // this will slow down the performance of actionhero, and if you need this funcionality, it is recommended that you do this upstream with nginx or your load balancer compress: false, // options to pass to the query parser // learn more about the options @ https://github.com/hapijs/qs queryParseOptions: {} } } } } exports.staging = { servers: { web: function (api) { return { padding: null, httpHeaders: { 'X-Powered-By': api.config.general.serverName, 'Access-Control-Allow-Origin': 'http://sb.87.252.173.51.xip.io', 'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE', 'Access-Control-Allow-Headers': 'Content-Type, X-SB-CSRF-Token', 'Access-Control-Allow-Credentials': 'true' } } } } } exports.production = { servers: { web: function (api) { return { padding: null, httpHeaders: { 'X-Powered-By': api.config.general.serverName, 'Access-Control-Allow-Origin': 'https://smartbirds.org', 'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE', 'Access-Control-Allow-Headers': 'Content-Type, X-SB-CSRF-Token', 'Access-Control-Allow-Credentials': 'true' }, metadataOptions: { serverInformation: false, requesterInformation: false } } } } } exports.test = { servers: { web: function (api) { return { secure: false, port: 1000 + (process.pid % 64535), matchExtensionMime: true, metadataOptions: { serverInformation: true, requesterInformation: true } } } } }
JavaScript
0.000001
@@ -985,21 +985,17 @@ p:// -192.168.0.105 +localhost :996
090c26360cc19a818d75e8fc9ad9478521529d87
Return array of activity IDs; cleanup
server/methods/activities.js
server/methods/activities.js
Meteor.methods({ 'getResidentLatestActivityByType': function (residentId, activityTypeId) { /* Get the resident's most recent activity by type */ var query = { activityTypeId: activityTypeId, residentIds: residentId }; // Set up sort by activity date, in descending order var sort = {sort: {activityDate: -1}}; // Get resident latest activity by type var residentLatestActivityByType = Activities.findOne(query, sort); // Return activity, if exists if (residentLatestActivityByType) { return residentLatestActivityByType; } }, 'getAllResidentsLatestActivitiesByType': function () { /* Return an array of Activity IDs where each activity type has at most one entry per resident containing the most recent activity of that type/resident */ // Get all resident IDs var residentIds = Meteor.call('getAllResidentIds'); // Get all Activity Type IDs var activityTypeIds = Meteor.call('getAllActivityTypeIds'); // Placeholder for residents latest activity var residentsLatestActivitiesByType = []; // Iterate through resident IDs residentIds.forEach(function (residentId) { // for each resident ID // Iterate through activity types console.log(residentId); activityTypeIds.forEach(function (activityTypeId) { // Get a reference to Resident ID (as array-like object apparently) var residentIdObject = this; // Convert the resident ID array-like object to an array var residentIdArray = Array.prototype.slice.call(residentIdObject); // Convert the resident ID array to a string var residentId = residentIdArray.join(""); // TODO: see if there is a simple way to accept a callback argument as string // for each activity type, // get resident latest activity var residentLatestActivityByType = Meteor.call('getResidentLatestActivityByType', residentId, activityTypeId); // append activity ID to residentsLatestActivitiesByType residentsLatestActivitiesByType.push(residentLatestActivityByType); }, residentId); }); console.log(residentsLatestActivitiesByType); return residentsLatestActivitiesByType } });
JavaScript
0.000008
@@ -621,26 +621,27 @@ atestActivit -ie +yId sByType': fu @@ -1086,26 +1086,27 @@ atestActivit -ie +yId sByType = %5B%5D @@ -1266,39 +1266,8 @@ pes%0A - console.log(residentId);%0A @@ -1869,32 +1869,34 @@ ntLatestActivity +Id ByType = Meteor. @@ -2012,34 +2012,35 @@ ntsLatestActivit -ie +yId sByType%0A @@ -2057,26 +2057,27 @@ atestActivit -ie +yId sByType.push @@ -2099,22 +2099,28 @@ Activity +Id ByType +._id );%0A @@ -2148,57 +2148,8 @@ %7D);%0A - console.log(residentsLatestActivitiesByType); %0A @@ -2178,18 +2178,19 @@ tActivit -ie +yId sByType%0A
df74b647eb9838edb0b3d094e715fcad103fda2e
indent well code
js/jquery.customSelect.js
js/jquery.customSelect.js
/* Alessandro Minoccheri V 1.0.0 15-02-2014 */ (function ($) { $.fn.extend({ customSelect: function (argumentOptions) { var defaults = { width : 100, height : 19, image : "select.jpg", textAlign : "left", textIndent : "10" } var options = $.extend(defaults, argumentOptions); return this.each(function () { var o = options; var obj = $(this); var ul = $("ul", obj); var li = $("li", ul); var span = $("span", obj); var active = -1; var numberOfLiElement = ul.find('li').length; var $document = $(document); unbind = function(){ ul.unbind("mouseleave"); $document.unbind("keyup"); $document.unbind("click"); } var input= '<input type="text" value="' + span.text() + '" name="' + obj.attr('id') + '" style="display:none"/>'; obj.append(input); obj.css("background", "url(img/" + o.image + ") no-repeat"); obj.css("width", o.width); obj.css("height", o.height); span.css("text-align", o.textAlign); span.css("margin-left", o.textIndent + "px"); ul.css('width', o.width); li.css('width', o.width); obj.click(function(){ ul.css("opacity", "1"); ul.css("display", "block"); ul.bind("mouseleave", function(){ time = setTimeout(function() { ul.animate({ opacity: 0 }, 500, function() { unbind(); ul.css("display", "none"); }); }, 400); }); $document.bind("keyup", function(e){ if (e.keyCode == 40) { if(active < numberOfLiElement - 1){ active++; ul.find('li').removeClass('active'); ul.find('li:eq(' + active + ')').addClass('active'); } } if (e.keyCode == 38) { if(active > 0){ active--; ul.find('li').removeClass('active'); ul.find('li:eq(' + active + ')').addClass('active'); } } }); time2 = setTimeout(function() { $document.bind("click", function(){ ul.animate({ opacity: 0 }, 500, function() { unbind(); ul.css("display", "none"); }); }); }, 400); }); li.on("click",function(){ unbind(); span.text($(this).text()); $('input[name="' + obj.attr('id') + '"]').attr("value", $(this).text()); ul.animate({ opacity: 0 }, 500, function() { ul.css("display", "none"); }); }); }); } }); })(jQuery);
JavaScript
0.000057
@@ -400,16 +400,21 @@ var o +%09%09%09%09%09 = option @@ -428,16 +428,20 @@ var obj +%09%09%09%09 = $(this @@ -454,16 +454,21 @@ %09var ul +%09%09%09%09%09 = $(%22ul%22 @@ -486,16 +486,21 @@ %09var li +%09%09%09%09%09 = $(%22li%22 @@ -519,16 +519,20 @@ ar span +%09%09%09%09 = $(%22spa @@ -556,16 +556,20 @@ active +%09%09%09%09 = -1;%0A%09%09 @@ -592,16 +592,17 @@ Element +%09 = ul.fin @@ -635,16 +635,19 @@ ocument +%09%09%09 = $(docu @@ -1567,24 +1567,25 @@ %09%09%0A%09%09%09%09%09%7D);%0A +%0A %09%09%09%09%09$docume
e2e2cf278af7ecbe1af65d93f193ee3c9f3a39dd
fix upgrade bar
js/saiku/views/Upgrade.js
js/saiku/views/Upgrade.js
/* * Copyright 2012 OSBI 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. */ /** * The global toolbar */ var Upgrade = Backbone.View.extend({ tagName: "div", events: { }, initialize: function(a, b) { this.workspace = a.workspace; }, daydiff: function(first, second) { return Math.round((second-first)/(1000*60*60*24)); }, render: function() { var self = this; var license = new License(); if(Settings.BIPLUGIN5){ license.fetch_license('api/api/license', function (opt) { if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){ $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>Notice:"+Saiku.session.get("notice")+"</div>"); } if (opt.status !== 'error' && opt.data.get("licenseType") != "trial") { return this; } else if(opt.status !== 'error' && opt.data.get("licenseType") === "trial"){ var yourEpoch = parseFloat(opt.data.get("expiration")); var yourDate = new Date(yourEpoch); self.remainingdays = self.daydiff(new Date(), yourDate); $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. <a href='http://www.meteorite.bi/saiku-pricing'>Buy licenses online.</a></div>"); return self; } else { $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>You are using Saiku Community Edition, please consider upgrading to <a target='_blank' href='http://meteorite.bi'>Saiku Enterprise</a>, or entering a <a href='http://meteorite.bi/products/saiku/sponsorship'>sponsorship agreement with us</a> to support development. " + "<a href='http://meteorite.bi/products/saiku/community'>Or contribute by joining our community and helping other users!</a></div></div>"); return self; } }); } else { license.fetch_license('api/license/', function (opt) { if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){ $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>Notice:"+Saiku.session.get("notice")+"</div>"); } if (opt.status !== 'error' && opt.data.get("licenseType") != "trial") { return this; } else if(opt.status !== 'error' && opt.data.get("licenseType") === "trial"){ var yourEpoch = parseFloat(opt.data.get("expiration")); var yourDate = new Date(yourEpoch); self.remainingdays = self.daydiff(new Date(), yourDate); $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. <a href='http://www.meteorite.bi/saiku-pricing'>Buy licenses online.</a></div>"); return self; } else { $(self.workspace.el).find('.upgrade').append("<div><div id='uphead' class='upgradeheader'>You are using Saiku Community Edition, please consider upgrading to <a target='_blank' href='http://meteorite.bi'>Saiku Enterprise</a>, or entering a <a href='http://meteorite.bi/products/saiku/sponsorship'>sponsorship agreement with us</a> to support development. " + "<a href='http://meteorite.bi/products/saiku/community'>Or contribute by joining our community and helping other users!</a></div></div>"); return self; } }); } }, call: function(e) { } });
JavaScript
0
@@ -975,69 +975,8 @@ 5)%7B%0A -%09%09%09license.fetch_license('api/api/license', function (opt) %7B%0A %09%09%09%09 @@ -1255,71 +1255,103 @@ if ( -opt.status !== 'error' && opt.data.get(%22 +Settings.LICENSE.licenseType != %22trial%22 && Settings.LICENSE. licen -s +c eType -%22) != %22 -trial +Open Source License %22) %7B @@ -1383,82 +1383,122 @@ %09%09%09%09 -else if(opt.status !== 'error' && opt.data.get(%22 +if (Settings.LICENSE.licenseType === %22trial%22 && Settings.LICENSE. licen -s +c eType -%22) === %22 -trial +Open Source%22 +%0A%09%09%09%09%09%22 License %22) + %7B%0A%09%09 @@ -2499,31 +2499,24 @@ self;%0A%09%09%09%09%7D%0A -%09%09%09%7D);%0A %09%09%7D%0A%09%09else %7B @@ -2520,66 +2520,8 @@ e %7B%0A -%09%09%09license.fetch_license('api/license/', function (opt) %7B%0A %09%09%09%09 @@ -2800,71 +2800,103 @@ if ( -opt.status !== 'error' && opt.data.get(%22 +Settings.LICENSE.licenseType != %22trial%22 && Settings.LICENSE. licen -s +c eType -%22) != %22 -trial +Open Source License %22) %7B @@ -2927,83 +2927,121 @@ %0A%09%09%09 -%09else if(opt.status !== 'error' && opt.data.get(%22 +if (Settings.LICENSE.licenseType === %22trial%22 && Settings.LICENSE. licen -s +c eType -%22) === %22 -trial +Open Source%22 +%0A%09%09%09%09%22 License %22) + %7B%0A%09%09 @@ -4050,15 +4050,8 @@ %09%09%7D%0A -%09%09%09%7D);%0A %09%09%7D%0A
a6e43dc64d00425bc1794f0f87a725a2b4e36817
Fix for Zero Search Radius
js/tasks/LayerInfoTask.js
js/tasks/LayerInfoTask.js
/*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */ /* | Copyright 2015 ESRI (UK) Limited | | 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. */ /** * Execute the Query Task to a Layer */ define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"], function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) { var taskOutput = function LayerInfoTask(props) { this.properties = props; this.getLayerInfo = function () { var _this = this, result = new Deferred(), featureLayer; // Need to also get the symbology for each layer featureLayer = new FeatureLayer(_this.properties.serviceUrl); featureLayer.on("error", function (err) { result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId }); }); featureLayer.on("load", function (data) { var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity }; if (props.layerRenderer !== undefined && props.layerRenderer !== null) { layerInf.renderer = jsonUtils.fromJson(props.layerRenderer); } else { layerInf.renderer = data.layer.renderer; } _this.queryLayer(data.layer.maxRecordCount).then(function (res) { result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl }); }); }); return result.promise; }; this.getUnits = function (distanceUnits) { switch (distanceUnits) { case "m": return Units.MILES; case "km": return Units.KILOMETERS case "me": return Units.METERS default: return Units.MILES; } }; this.queryLayer = function (maxRecords) { var _this = this, result = new Deferred(), query, queryTask; // Use the current location and buffer the point to create a search radius query = new Query(); queryTask = new QueryTask(_this.properties.serviceUrl); query.where = "1=1"; // Get everything query.geometry = new Circle({ center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y], geodesic: true, radius: _this.properties.searchRadius, radiusUnit: _this.getUnits(_this.properties.distanceUnits) }); query.outFields = ["*"]; query.returnGeometry = true; query.outSpatialReference = _this.properties.currentPoint.spatialReference; query.num = maxRecords || 1000; queryTask.execute(query, function (features) { result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId}); }, function (error) { result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId }); }); return result.promise; }; this.execute = function () { return this.getLayerInfo(); }; }; return taskOutput; });
JavaScript
0
@@ -2647,24 +2647,25 @@ s.KILOMETERS +; %0A%0A @@ -2720,16 +2720,17 @@ s.METERS +; %0A%0A @@ -2939,278 +2939,90 @@ Task -;%0A%0A // Use the current location and buffer the point to create a search radius%0A query = new Query();%0A queryTask = new QueryTask(_this.properties.serviceUrl);%0A%0A query.where = %221=1%22; // Get everything %0A query.geometry +, geom;%0A%0A if (_this.properties.searchRadius %3E 0) %7B%0A geom = n @@ -3033,16 +3033,20 @@ ircle(%7B%0A + @@ -3129,16 +3129,20 @@ int.y%5D,%0A + @@ -3177,24 +3177,28 @@ + radius: _thi @@ -3224,16 +3224,20 @@ Radius,%0A + @@ -3306,24 +3306,405 @@ its) - %0A %7D) +%0A %7D);%0A %7D%0A else %7B%0A geom = _this.properties.currentPoint;%0A %7D%0A%0A // Use the current location and buffer the point to create a search radius%0A query = new Query();%0A queryTask = new QueryTask(_this.properties.serviceUrl);%0A%0A query.where = %221=1%22; // Get everything %0A query.geometry = geom ;%0A
1fa2a2aa3b50a8564f533b6aafdac96a75d1b745
Copy commits individually (#7486)
bin/copy.js
bin/copy.js
const copyAssets = require("./copy-assets") const copyModules = require("./copy-modules") const minimist = require("minimist"); const fs = require("fs"); const chalk = require("chalk"); const args = minimist(process.argv.slice(1), { string: ["mc"], boolean: ["watch", "symlink", "assets"] }); const mc = args.mc || "./firefox"; const watch = args.watch; const symlink = args.symlink; const assets = args.assets console.log(`Copying Files to ${mc} with params: `, {watch, assets, symlink}) async function start() { if (fs.existsSync(mc)) { try { await copyAssets({ assets, mc, watch, symlink}) await copyModules.run({ mc, watch }) } catch (e) { console.error(e); if (e.code === "ENOENT") { missingFilesErrorMessage(); } } } else { missingFilesErrorMessage(); } } function missingFilesErrorMessage() { let errorMessage = [ 'It looks like you are missing some files. The mozilla-central ', 'codebase may be missing at ${mc}. You can clone mozilla-central by ', 'running \`./bin/prepare-mochitests-dev\` from the root of the ', 'debugger.html repository. You can find more information on bundling ', 'or mochitests at ', 'https://github.com/devtools-html/debugger.html/blob/master/docs/bundling.md or ', 'https://github.com/devtools-html/debugger.html/blob/master/docs/mochitests.md' ].join(''); console.warn(chalk.yellow(errorMessage)); } start();
JavaScript
0
@@ -1,16 +1,301 @@ +%0A/*%0A * copy files to mc%0A * node ./bin/copy --mc ../gecko-dev%0A *%0A * copy files per commit%0A * node ./bin/copy --mc ../gecko-dev --sha 123%0A *%0A * copy files per commit with a message%0A * node ./bin/copy --mc ../gecko-dev --sha 123 --message %22bug 123 (release 106) __message__.r=dwalsh%22%0A */%0A %0Aconst copyAsset @@ -464,16 +464,79 @@ chalk%22); +%0Aconst shell = require(%22shelljs%22);%0Aconst path = require(%22path%22) %0A%0Aconst @@ -591,16 +591,34 @@ g: %5B%22mc%22 +, %22sha%22, %22message%22 %5D,%0A boo @@ -781,109 +781,154 @@ ets%0A -%0A cons -ole.log(%60Copying Files to $%7Bmc%7D with params: %60, %7Bwatch, assets, symlink%7D)%0A%0Aasync function start( +t sha = args.sha%0Aconst message = args.message %7C%7C %22%22%0A%0Aconst mcPath = path.join(__dirname, mc)%0A%0Aasync function copy(%7Bassets, mc, watch, symlink%7D ) %7B%0A @@ -1236,16 +1236,140 @@ %0A %7D%0A%7D%0A%0A +async function start() %7B%0A console.log(%60Copying Files to $%7Bmc%7D with params: %60, %7Bwatch, assets, symlink%7D)%0A return copy()%0A%7D%0A%0A function @@ -1970,16 +1970,892 @@ e));%0A%7D%0A%0A +async function copyCommits() %7B%0A function exec(cmd) %7B%0A return shell.exec(cmd, %7B silent: true %7D).stdout;%0A %7D%0A%0A function getMessage(sha) %7B%0A return exec(%60git log --format=%25B -n 1 $%7Bsha%7D%60).split(%22%5Cn%22)%5B0%5D%0A %7D%0A%0A function getCommitsAfter(sha) %7B%0A return exec(%60git rev-list --reverse $%7Bsha%7D%5E..HEAD%60).trim().split(%22%5Cn%22);%0A %7D%0A%0A function commitChanges(%7Bmsg%7D) %7B%0A console.log(%60git commit -m %22$%7Bprefix%7D $%7Bmsg%7D%22%60)%0A const commitMessage = message.replace('__message__', msg)%0A exec(%60git add devtools; git commit -m %22$%7Bprefix%7D $%7BcommitMessage%7D%22%60)%0A %7D%0A%0A const commits = getCommitsAfter(sha)%0A for (const commit of commits) %7B%0A const message = getMessage(commit);%0A console.log(%60Copying $%7Bmessage%7D%60)%0A exec(%60git checkout $%7Bcommit%7D%60);%0A%0A await copy(%7Bmc%7D);%0A shell.cd(mc);%0A commitChanges(%7Bmessage%7D);%0A shell.cd(%60-%60);%0A %7D%0A%7D%0A%0Aif (sha) %7B%0A copyCommits();%0A%7D else %7B%0A start(); @@ -2851,12 +2851,14 @@ %0A start();%0A +%7D%0A
be351ce1face2c69c68a4eda2418e57998b3e3fa
check for null in getTextBounds
js/views/headerBarView.js
js/views/headerBarView.js
(function(ionic) { 'use strict'; ionic.views.HeaderBar = ionic.views.View.inherit({ initialize: function(opts) { this.el = opts.el; ionic.extend(this, { alignTitle: 'center' }, opts); this.align(); }, align: function(align) { align || (align = this.alignTitle); // Find the titleEl element var titleEl = this.el.querySelector('.title'); if(!titleEl) { return; } var self = this; //We have to rAF here so all of the elements have time to initialize ionic.requestAnimationFrame(function() { var i, c, childSize; var childNodes = self.el.childNodes; var leftWidth = 0; var rightWidth = 0; var isCountingRightWidth = false; // Compute how wide the left children are // Skip all titles (there may still be two titles, one leaving the dom) // Once we encounter a titleEl, realize we are now counting the right-buttons, not left for(i = 0; i < childNodes.length; i++) { c = childNodes[i]; if (c.tagName && c.tagName.toLowerCase() == 'h1') { isCountingRightWidth = true; continue; } childSize = null; if(c.nodeType == 3) { childSize = ionic.DomUtil.getTextBounds(c).width; } else if(c.nodeType == 1) { childSize = c.offsetWidth; } if(childSize) { if (isCountingRightWidth) { rightWidth += childSize; } else { leftWidth += childSize; } } } var margin = Math.max(leftWidth, rightWidth) + 10; //Reset left and right before setting again titleEl.style.left = titleEl.style.right = ''; // Size and align the header titleEl based on the sizes of the left and // right children, and the desired alignment mode if(align == 'center') { if(margin > 10) { titleEl.style.left = margin + 'px'; titleEl.style.right = margin + 'px'; } if(titleEl.offsetWidth < titleEl.scrollWidth) { if(rightWidth > 0) { titleEl.style.right = (rightWidth + 5) + 'px'; } } } else if(align == 'left') { titleEl.classList.add('title-left'); if(leftWidth > 0) { titleEl.style.left = (leftWidth + 15) + 'px'; } } else if(align == 'right') { titleEl.classList.add('title-right'); if(rightWidth > 0) { titleEl.style.right = (rightWidth + 15) + 'px'; } } }); } }); })(ionic);
JavaScript
0
@@ -1277,25 +1277,26 @@ -childSize +var bounds = ionic @@ -1324,15 +1324,88 @@ s(c) -.width; +;%0A if(bounds) %7B%0A childSize = bounds.width;%0A %7D %0A
44bf5eb045d89b20ba28e6648e91a371ecf9cf10
Refactor the bin file
bin/pnpm.js
bin/pnpm.js
#!/usr/bin/env node if (~process.argv.indexOf('--debug')) { process.env.DEBUG = 'pnpm:*' process.argv.push('--quiet') } var rc = require('rc') var camelcaseKeys = require('camelcase-keys') var spawnSync = require('cross-spawn').sync var installCmd = require('../lib/cmd/install') var uninstallCmd = require('../lib/cmd/uninstall') function run (argv) { const cli = require('meow')({ argv: argv, help: [ 'Usage:', ' $ pnpm install', ' $ pnpm install <name>', ' $ pnpm uninstall', ' $ pnpm uninstall <name>', '', 'Options:', ' -S, --save save into package.json under dependencies', ' -D, --save-dev save into package.json under devDependencies', ' -O, --save-optional save into package.json under optionalDependencies', ' -E, --save-exact save exact spec', '', ' --dry-run simulate', ' -g, --global install globally', '', ' --production don\'t install devDependencies', ' --quiet don\'t print progress', ' --debug print verbose debug message' ].join('\n') }, { boolean: [ 'save-dev', 'save', 'save-exact', 'save-optional', 'dry-run', 'global', 'quiet', 'debug' ], alias: { 'no-progress': 'quiet', D: 'save-dev', S: 'save', E: 'save-exact', O: 'save-optional', g: 'global', v: 'version' } }) var installCmds = ['install', 'i'] var supportedCmds = installCmds.concat(['uninstall', 'r', 'rm', 'un', 'unlink', 'help']) if (supportedCmds.indexOf(cli.input[0]) === -1) { spawnSync('npm', argv, { stdio: 'inherit' }) return } if (cli.flags.debug) { cli.flags.quiet = true } ['dryRun'].forEach(function (flag) { if (cli.flags[flag]) { console.error("Error: '" + flag + "' is not supported yet, sorry!") process.exit(1) } }) var opts = Object.assign({}, getRC('npm'), getRC('pnpm')) // This is needed because the arg values should be used only if they were passed Object.keys(cli.flags).forEach(function (key) { opts[key] = opts[key] || cli.flags[key] }) var cmd = installCmds.indexOf(cli.input[0]) === -1 ? uninstallCmd : installCmd return cmd(cli.input.slice(1), opts).catch(require('../lib/err')) } function getRC (appName) { return camelcaseKeys(rc(appName)) } module.exports = run if (!module.parent) run(process.argv.slice(2))
JavaScript
0.000006
@@ -13,16 +13,29 @@ nv node%0A +'use strict'%0A if (~pro @@ -344,16 +344,81 @@ tall')%0A%0A +const supportedCmds = new Set(%5B'install', 'uninstall', 'help'%5D)%0A%0A function @@ -1564,127 +1564,44 @@ var -installC +c md -s = -%5B'install', 'i'%5D%0A var supportedCmds = installCmds.concat(%5B'uninstall', 'r', 'rm', 'un', 'unlink', 'help' +getCommandFullName(cli.input%5B0 %5D)%0A @@ -1605,16 +1605,17 @@ )%0A if ( +! supporte @@ -1624,36 +1624,16 @@ mds. -indexOf(cli.input%5B0%5D) === -1 +has(cmd) ) %7B%0A @@ -1691,16 +1691,34 @@ return + Promise.resolve() %0A %7D%0A%0A @@ -2196,63 +2196,79 @@ %0A%0A -var cmd = installCmds.indexOf(cli.input%5B0%5D) === -1 +const cliArgs = cli.input.slice(1)%0A const cmdfn = cmd === 'install' ? -un inst @@ -2276,16 +2276,18 @@ llCmd : +un installC @@ -2305,63 +2305,319 @@ cmd +fn (cli -.input.slice(1), opts).catch(require('../lib/err')) +Args, opts)%0A%7D%0A%0Afunction getCommandFullName (cmd) %7B%0A switch (cmd) %7B%0A case 'install':%0A case 'i':%0A return 'install'%0A case 'uninstall':%0A case 'r':%0A case 'rm':%0A case 'un':%0A case 'unlink':%0A return 'uninstall'%0A case 'help':%0A return 'help'%0A default:%0A return cmd%0A %7D %0A%7D%0A%0A @@ -2703,16 +2703,16 @@ s = run%0A - if (!mod @@ -2749,9 +2749,38 @@ lice(2)) +.catch(require('../lib/err')) %0A
7e62aaf4395dc69b92d4e4ea3c437677430e7797
Update neko.js
bot/neko.js
bot/neko.js
/* Created by ℭrystaℒ on 7/10/2017. */ const Discord = require('discord.js'); const client = new Discord.Client(); const fs = require("fs"); const path = require("path"); const prefixPath = path.join(__dirname, "prefixes.json"); require("./functions/functions.js")(client); fs.readdir("./events/", (err, files) => { console.log(`Adding ${files.length} events.`); if (err) return console.error(err); files.forEach(file => { let eventFunction = require(`./events/${file}`); let eventName = file.split(".")[0]; client.on(eventName, (...args) => eventFunction.run(client, ...args)); }); }); client.on("message", async (message) => { const gprefix = JSON.parse(fs.readFileSync(prefixPath, 'utf8')); if (message.author.bot) return; if(message.content.indexOf(gprefix[message.guild.id].prefix) !== 0) return; // This is the best way to define args. Trust me. const args = message.content.slice(gprefix[message.guild.id].prefix.length).trim().split(/ +/g); const command = args.shift().toLowerCase(); // The list of if/else is replaced with those simple 2 lines: try { let commandFile = require(`./commands/${command}.js`); commandFile.run(client, message, args); } catch (err) { console.error(err); } }); client.login(client.config.token).catch(e => console.warn('wew tf happened here ' + e )); process.on('uncaughtException', err => { let errorMsg = err.stack.replace(new RegExp(`${__dirname}\/`, 'g'), './'); console.error("Uncaught Exception: ", errorMsg); }); process.on("unhandledRejection", err => { console.error("Uncaught Promise Error: ", err); });
JavaScript
0
@@ -119,125 +119,8 @@ );%0D%0A -const fs = require(%22fs%22);%0D%0Aconst path = require(%22path%22);%0D%0Aconst prefixPath = path.join(__dirname, %22prefixes.json%22);%0D%0A requ @@ -570,78 +570,8 @@ %7B%0D%0A - const gprefix = JSON.parse(fs.readFileSync(prefixPath, 'utf8'));%0D%0A @@ -634,23 +634,31 @@ indexOf( -g +client. prefix +es %5Bmessage @@ -792,15 +792,23 @@ ice( -g +client. prefix +es %5Bmes
0e593910e739f1776152502c3f93387078d962d0
Enable cobertura coverage report generation for jenkins consumption
gulp-tasks/tests.js
gulp-tasks/tests.js
var angularProtractor = require('gulp-angular-protractor'), del = require('del'), exec = require('child_process').exec, mocha = require('gulp-spawn-mocha'), path = require('path'), symlink = require('gulp-symlink'); var yargs = require('yargs'); module.exports = function(gulp) { gulp.task('unit-test', function() { return gulp.src(['test/unit/**/*.js'], { read: false }) .pipe(mocha({ recursive: true, compilers: 'js:babel-core/register', env: { NODE_PATH: './browser' }, grep: yargs.argv.grep, g: yargs.argv.g, reporter: yargs.argv.reporter, istanbul: true })); }); gulp.task('protractor-install', function(cb) { var cmd = path.join('node_modules', 'gulp-angular-protractor', 'node_modules', 'gulp-protractor', 'node_modules', '.bin') + path.sep + 'webdriver-manager'; cmd += ' update'; exec(cmd, function(err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('protractor-run', function() { return gulp.src(['../test/ui/**/*.js']) .pipe(angularProtractor({ 'configFile': 'protractor-conf.js', 'autoStartStopServer': false, 'debug': false })) .on('error', function(e) { throw e; }); }); };
JavaScript
0
@@ -659,20 +659,57 @@ tanbul: -true +%7B%0A report: 'cobertura'%0A %7D %0A %7D
877d2929b8ced2bf4fdf804819dd012547dfede1
remove comment in gulp.config.js
gulp/gulp.config.js
gulp/gulp.config.js
module.exports = function (fs) { var paths = { assets: __base + 'assets/', bower: __base + 'bower_components/' }; var config = { bundleSettingPath: __base + 'gulp/bundle.setting', bower: { "bootstrap": paths.bower + "bootstrap/dist/**/*.{js,map,css,ttf,svg,woff,eot}", "jquery": paths.bower + "jquery/dist/jquery*.{js,map}" // "angular": paths.bower + "angular/angular*.{js,map}", // "slick": paths.bower + "slick-carousel/slick/*.{js,css}", // "slider": paths.bower + "seiyria-bootstrap-slider/dist/**/*.{js,css}", // "mousewheel": paths.bower + "jquery-mousewheel/*.js" }, lib: paths.assets + 'lib/', js: paths.assets + 'js/', css: paths.assets + 'css/', script: paths.assets + 'Script/', style: paths.assets + 'Style/', fonts: { path: paths.assets + 'fonts/', source: [ paths.bower + 'bootstrap/dist/fonts/*.{ttf,svg,woff,eot}' ] } }; return config; }
JavaScript
0.000001
@@ -380,292 +380,8 @@ p%7D%22%0A - // %22angular%22: paths.bower + %22angular/angular*.%7Bjs,map%7D%22,%0A // %22slick%22: paths.bower + %22slick-carousel/slick/*.%7Bjs,css%7D%22,%0A // %22slider%22: paths.bower + %22seiyria-bootstrap-slider/dist/**/*.%7Bjs,css%7D%22,%0A // %22mousewheel%22: paths.bower + %22jquery-mousewheel/*.js%22%0A
9b09db804c2c8f3dc51fdf54d85754569c7e330b
update browser versions
browsers.js
browsers.js
'use strict'; /* eslint camelcase: [0] */ module.exports = { sl_chrome_41_osx9: { base: 'SauceLabs', platform: 'OS X 10.9', browserName: 'chrome', version: '41' }, sl_firefox_36_osx9: { base: 'SauceLabs', platform: 'OS X 10.9', browserName: 'firefox', version: '36' }, sl_safari_7_osx9: { base: 'SauceLabs', platform: 'OS X 10.9', browserName: 'safari', version: '7' }, sl_safari_8_osx10: { base: 'SauceLabs', platform: 'OS X 10.10', browserName: 'safari', version: '8' }, sl_ie_10_win7: { base: 'SauceLabs', platform: 'Windows 7', browserName: 'internet explorer', version: '10' }, sl_ie_11_win7: { base: 'SauceLabs', platform: 'Windows 7', browserName: 'internet explorer', version: '11' }, sl_chrome_41_win7: { base: 'SauceLabs', platform: 'Windows 7', browserName: 'chrome', version: '41' }, sl_firefox_36_win7: { base: 'SauceLabs', platform: 'Windows 7', browserName: 'firefox', version: '36' } };
JavaScript
0.000002
@@ -69,25 +69,26 @@ hrome_41_osx -9 +10 : %7B%0A%09%09base: @@ -113,33 +113,34 @@ tform: 'OS X 10. -9 +10 ',%0A%09%09browserName @@ -185,25 +185,26 @@ refox_36_osx -9 +10 : %7B%0A%09%09base: @@ -229,33 +229,34 @@ tform: 'OS X 10. -9 +10 ',%0A%09%09browserName @@ -304,17 +304,18 @@ ri_7_osx -9 +10 : %7B%0A%09%09ba @@ -356,9 +356,10 @@ 10. -9 +10 ',%0A%09
62a4043f4eacc778c8a1ba57c83926fd843fd505
remove logging
db/jobs.js
db/jobs.js
"use strict" /** * [collectionName description] * @type {String} */ var collectionName = 'Jobs' /** * [description] * @param {[type]} dbs [description] * @param {[type]} opts [description] * @param {[type]} _cb [description] * @return {[type]} [description] */ module.exports.get = (dbs, opts, _cb) => { dbs.mongo.collection(collectionName).find(opts.query, opts.proj, opts.opts, (err, cursor) => { if (err) return _cb(err, cursor) if (opts.transform.indexOf('array') > -1) { cursor.toArray((err, res) => { _cb(err, res) }) } else { _cb(err, cursor) } }) } /** * [description] * @param {[type]} dbs [description] * @param {[type]} opts [description] * @param {[type]} _cb [description] * @return {[type]} [description] */ module.exports.findOne = (dbs, opts, _cb) => { dbs.mongo.collection(collectionName).findOne(opts.query, opts.proj, () => { console.log(arguments); _cb(err, result) }) }
JavaScript
0.000001
@@ -916,42 +916,25 @@ j, ( -) =%3E %7B%0A console.log(arguments); +err, result) =%3E %7B %0A
baa7c4bc738aaae47e4897142362eaec19a86843
fix tests
server/test/session.js
server/test/session.js
var Lab = require('lab'); var Code = require('code'); var server = require('../').hapi; var lab = exports.lab = Lab.script(); var sessionA = { id: 'john.doe', name: 'John Doe', }; var changesSessionA = { name: 'Jane Doe' }; var credentials = { id: 'john.doe', name: 'John Doe', participations: [{ role: 'development-team', event: '1000-sinfo' }] }; lab.experiment('Session', function() { lab.test('Create', function(done) { var options = { method: 'POST', url: '/api/sessions', credentials: credentials, payload: sessionA }; server.inject(options, function(response) { var result = response.result; Code.expect(response.statusCode).to.equal(201); Code.expect(result).to.be.instanceof(Object); Code.expect(result.id).to.equal(sessionA.id); Code.expect(result.name).to.equal(sessionA.name); done(); }); }); lab.test('List all', function(done) { var options = { method: 'GET', url: '/api/sessions', credentials: credentials, }; server.inject(options, function(response) { var result = response.result; Code.expect(response.statusCode).to.equal(200); Code.expect(result).to.be.instanceof(Array); Code.expect(result[0].id).to.be.string; Code.expect(result[0].name).to.be.string; done(); }); }); lab.test('Get one', function(done) { var options = { method: 'GET', url: '/api/sessions/'+sessionA.id, credentials: credentials, }; server.inject(options, function(response) { var result = response.result; Code.expect(response.statusCode).to.equal(200); Code.expect(result).to.be.instanceof(Object); Code.expect(result.id).to.equal(sessionA.id); Code.expect(result.name).to.equal(sessionA.name); done(); }); }); lab.test('Update', function(done) { var options = { method: 'PUT', url: '/api/sessions/'+sessionA.id, credentials: credentials, payload: changesSessionA }; server.inject(options, function(response) { var result = response.result; Code.expect(response.statusCode).to.equal(200); Code.expect(result).to.be.instanceof(Object); Code.expect(result.id).to.equal(sessionA.id); Code.expect(result.name).to.equal(changesSessionA.name); done(); }); }); lab.test('Delete', function(done) { var options = { method: 'DELETE', url: '/api/sessions/'+sessionA.id, credentials: credentials, }; server.inject(options, function(response) { var result = response.result; Code.expect(response.statusCode).to.equal(200); Code.expect(result).to.be.instanceof(Object); Code.expect(result.id).to.equal(sessionA.id); Code.expect(result.name).to.equal(changesSessionA.name); done(); }); }); });
JavaScript
0.000001
@@ -177,18 +177,92 @@ n Doe',%0A -%7D; + event: 'test-event'%0A%7D;%0A%0Avar sessionId = sessionA.id + '-' + sessionA.event %0A%0Avar ch @@ -885,35 +885,33 @@ to.equal(session -A.i +I d);%0A Code.e @@ -1554,35 +1554,33 @@ ssions/'+session -A.i +I d,%0A credent @@ -1834,35 +1834,33 @@ to.equal(session -A.i +I d);%0A Code.e @@ -2039,35 +2039,33 @@ ssions/'+session -A.i +I d,%0A credent @@ -2350,35 +2350,33 @@ to.equal(session -A.i +I d);%0A Code.e @@ -2573,19 +2573,17 @@ +session -A.i +I d,%0A @@ -2853,19 +2853,17 @@ (session -A.i +I d);%0A
b8631b79ce8bceb13444815f42fc23255c27514f
fix testcase
test/startserver.test.js
test/startserver.test.js
'use strict'; var path = require('path'); var CliTest = require('command-line-test'); var StartServer = require('../build/server'); var logger = require('../build/middleware/logger'); var markdown = require('../build/middleware/markdown'); var statics = require('../build/middleware/static'); var directory = require('../build/middleware/directory'); var pkg = require('../package'); describe('/build/server.js', function() { var server; describe('main', function () { it('should has not error', function() { var error; try{ server = new StartServer(); } catch (e) { error = e; } (typeof error === 'undefined').should.be.true; }); }); describe('stack', function() { it('init function must have this members', function() { server.stack.should.have.length(0); }); }); describe('middleware', function() { it('should be ok', function() { server .bundle(logger) .bundle(markdown) .bundle(statics) .bundle(directory); server.stack.should.have.length(4); }); }); describe('middleware', function() { it('command line tool should be ok', function *() { var cliTest = new CliTest(); var binFile = path.resolve(pkg.bin['startserver']); var res = yield cliTest.execFile(binFile, ['-v'], {}); res.stdout.should.be.containEql(pkg.version); }); }); });
JavaScript
0.000009
@@ -111,21 +111,19 @@ ire('../ -build +lib /server' @@ -142,37 +142,35 @@ r = require('../ -build +lib /middleware/logg @@ -194,37 +194,35 @@ n = require('../ -build +lib /middleware/mark @@ -247,37 +247,35 @@ s = require('../ -build +lib /middleware/stat @@ -308,21 +308,19 @@ ire('../ -build +lib /middlew
95fc8af2c642989d247a5b9d637945fb7686a2e8
Fix configure step usage.
lib/configure.js
lib/configure.js
module.exports = exports = configure /** * Module dependencies. */ var path = require('path') , win = process.platform == 'win32' exports.usage = 'Generates ' + (win ? 'MSVS project files' : 'a Makefile') + ' for the current platform' function configure (gyp, argv, callback) { var python = gyp.opts.python || 'python' // TODO: Really detect the latest version if (!gyp.opts.target) { gyp.opts.target = 0.7 } // TODO: Don't always install, check if this version is installed first gyp.commands.install([gyp.opts.target], go) function go (err) { if (err) return callback(err) // TODO: Detect and add support for a "current" dev version, // so `target` would be implicit. var target = String(gyp.opts.target) , devDir = path.join(process.env.HOME, '.node-gyp', target) , gyp_addon = path.join(devDir, 'tools', 'gyp_addon') // Force the 'make' target for non-Windows if (!win) { argv.unshift('make') argv.unshift('-f') } argv.unshift(gyp_addon) var cp = gyp.spawn(python, argv) cp.on('exit', function (code, signal) { if (code !== 0) { callback(new Error('`gyp_addon` failed with exit code: ' + code)) } else { callback() } }) } }
JavaScript
0
@@ -173,17 +173,17 @@ n ? 'MSV -S +C project @@ -226,24 +226,22 @@ current -platform +module '%0A%0Afunct
1cd22bab62d358dedf80c376da31dc3236cd6cb7
Use double quotes by default for all languages
lib/converter.js
lib/converter.js
var sprintf = require("sprintf-js").sprintf; /** * Perform JSON conversion to target language */ function jsonToLang(json, lang, level) { var indentationLevel = level || 0; var dataFormatted = ''; var formatMap = { csharp: { fileStart: "", variable: "var data = ", hashStart: "new Hashtable {", hashEnd: "}", hashRow: "{ \"%s\", %s }", hashRowEnd: ",\n", indent: " ", lineEnd: ";" }, php: { fileStart: "<?php\n", variable: "$data = ", hashStart: "[", hashEnd: "]", hashRow: "'%s' => %s", hashRowEnd: ",\n", indent: " ", lineEnd: ";" }, python: { fileStart: "", variable: "data = ", hashStart: "{", hashEnd: "}", hashRow: "'%s' : %s", hashRowEnd: ",\n", indent: " ", lineEnd: "" }, ruby: { fileStart: "", variable: "data = ", hashStart: "{", hashEnd: "}", hashRow: ":%s => %s", hashRowEnd: ",\n", indent: " ", lineEnd: "" } }; // Format JSON data according to how it looks // Calls jsonToLang recursively to format arrays and objects var jsonValueFormat = function(value, lang) { var indent = "\t".repeat(indentationLevel) var valueType = typeof value; // Recursive if (valueType == "array" || valueType == "object") { value = jsonToLang(value, lang, indentationLevel+1); } else if (valueType == "string") { // Certain languages require double quotes for values switch(lang) { case 'csharp': value = "\"" + value + "\""; break; default: value = "'" + value + "'"; break; } } return value; }; // What kind of language is it? switch(lang) { case 'json': dataFormatted = 'var data = ' + JSON.stringify(json, null, 4); break; default: var format = formatMap[lang]; if (!format) { return false; } // Level indentation if (indentationLevel === 0) { dataFormatted += format.fileStart.replace('<', '&lt;').replace('>', '&gt;'); dataFormatted += format.variable; } dataFormatted += format.hashStart + "\n"; var indent = format.indent.repeat(indentationLevel + 1); if (typeof json == "array") { var jsonLen = json.length; for(var key = 0; key < jsonLen; key++) { var value = jsonValueFormat(json[key], lang); dataFormatted += indent + sprintf(format.hashRow, key, value); if (jsonLen != key) { dataFormatted += format.hashRowEnd; } }; } else if (typeof json == "object") { var jsonLen = Object.keys(json).length; var i = 0; for(var key in json) { i++; var value = jsonValueFormat(json[key], lang); dataFormatted += indent + sprintf(format.hashRow, key, value); if (jsonLen != i) { dataFormatted += format.hashRowEnd; } }; } indent = format.indent.repeat(indentationLevel); dataFormatted += "\n" + indent + format.hashEnd; if (indentationLevel === 0) { dataFormatted += format.lineEnd; } } return dataFormatted; } /** * String repeat polyfill * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat */ if (!String.prototype.repeat) { String.prototype.repeat = function(count) { 'use strict'; if (this == null) { throw new TypeError('can\'t convert ' + this + ' to object'); } var str = '' + this; count = +count; if (count != count) { count = 0; } if (count < 0) { throw new RangeError('repeat count must be non-negative'); } if (count == Infinity) { throw new RangeError('repeat count must be less than infinity'); } count = Math.floor(count); if (str.length == 0 || count == 0) { return ''; } // Ensuring count is a 31-bit integer allows us to heavily optimize the // main part. But anyway, most current (August 2014) browsers can't handle // strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) { throw new RangeError('repeat count must not overflow maximum string size'); } var rpt = ''; for (;;) { if ((count & 1) == 1) { rpt += str; } count >>>= 1; if (count == 0) { break; } str += str; } return rpt; } } /** * Exports */ module.exports.jsonToLang = jsonToLang;
JavaScript
0
@@ -570,20 +570,22 @@ shRow: %22 -'%25s' +%5C%22%25s%5C%22 =%3E %25s%22, @@ -782,12 +782,14 @@ w: %22 -'%25s' +%5C%22%25s%5C%22 : %25 @@ -1493,247 +1493,36 @@ -// Certain languages require double quotes for values%0A switch(lang)%0A %7B%0A case 'csharp':%0A value = %22%5C%22%22 + value + %22%5C%22%22;%0A break;%0A%0A default:%0A value = %22'%22 + value + %22'%22;%0A break;%0A %7D +value = %22%5C%22%22 + value + %22%5C%22%22; %0A
985370371ac0b00e5397011fb1fae120d391db40
update basic package-file testing
test/testPackageFiles.js
test/testPackageFiles.js
/* jshint -W097 */ /* jshint strict:false */ /* jslint node: true */ /* jshint expr: true */ var expect = require('chai').expect; var fs = require('fs'); describe('Test package.json and io-package.json', function() { it('Test package files', function (done) { console.log(); var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8'); var ioPackage = JSON.parse(fileContentIOPackage); var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8'); var npmPackage = JSON.parse(fileContentNPMPackage); expect(ioPackage).to.be.an('object'); expect(npmPackage).to.be.an('object'); expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist; expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist; expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version); if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) { console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!'); console.log(); } expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist; expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist; if (ioPackage.common.name.indexOf('template') !== 0) { if (Array.isArray(ioPackage.common.authors)) { expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0); if (ioPackage.common.authors.length === 1) { expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <[email protected]>'); } } else { expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <[email protected]>'); } } else { console.log('WARNING: Testing for set authors field in io-package skipped because template adapter'); console.log(); } expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true; expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true; if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') { console.log('WARNING: titleLang is not existing in io-package.json. Please add'); console.log(); } if ( ioPackage.common.title.indexOf('iobroker') !== -1 || ioPackage.common.title.indexOf('ioBroker') !== -1 || ioPackage.common.title.indexOf('adapter') !== -1 || ioPackage.common.title.indexOf('Adapter') !== -1 ) { console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.'); console.log(); } if (ioPackage.common.name.indexOf('vis-') !== 0) { if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) { console.log('WARNING: Admin3 support is missing! Please add it'); console.log(); } if (ioPackage.common.materialize) { expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true; } } expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist'); var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8'); expect(fileContentReadme.indexOf('## License'), 'The README.md needs to have a section ## License').not.equal(-1); expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## Changelog').not.equal(-1); expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## License').to.be.below(fileContentReadme.indexOf('## License')); done(); }); });
JavaScript
0
@@ -4107,38 +4107,35 @@ utf8');%0A -expect +if (fileContentRead @@ -4158,19 +4158,61 @@ icense') -, ' + === -1) %7B%0A console.log('Warning: The READ @@ -4213,32 +4213,30 @@ e README.md -needs to +should have a sect @@ -4255,83 +4255,145 @@ se') -.not.equal(-1);%0A expect(fileContentReadme.indexOf('## Changelog'), ' +;%0A console.log();%0A %7D%0A if (fileContentReadme.indexOf('## Changelog') === -1) %7B%0A console.log('Warning: The @@ -4398,32 +4398,30 @@ e README.md -needs to +should have a sect @@ -4442,187 +4442,46 @@ og') -.not.equal(-1);%0A expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## License').to.be.below(fileContentReadme.indexOf('## License')); +;%0A console.log();%0A %7D %0A
1208d188372e5c67309cf74ca438e70ddc46ce71
add the post method
lib/db_helper.js
lib/db_helper.js
var sqlite3 = require('sqlite3').verbose(); var _ = require("underscore"); var config = require('../iot').config; var MongoClient = require('mongodb').MongoClient; var mongodb_url = 'mongodb://127.0.0.1:27017/' + config.mongodb_name.toString(); function DBHelper() { 'use strict'; return; } function generateDBKey(this_block) { 'use strict'; var str = ""; _.each(this_block, function (key) { str += key + ","; }); str = str.substring(0, str.length - 1); return str; } DBHelper.postData = function (block, callback) { 'use strict'; var db = new sqlite3.Database(config.db_name); var str = generateDBKey(config.keys); var string = generateDBKey(block); var insert_db_string = "insert or replace into " + config.table_name + " (" + str + ") VALUES (" + string + ");"; console.log(insert_db_string); db.all(insert_db_string, function (err) { if (err !== null) { console.log(err); } db.close(); callback(); }); }; DBHelper.deleteData = function (url, callback) { 'use strict'; var db = new sqlite3.Database(config.db_name); console.log("DELETE FROM " + config.table_name + " where " + url.split('/')[1] + "=" + url.split('/')[2]); var insert_db_string = "DELETE FROM " + config.table_name + " where " + url.split('/')[1] + "=" + url.split('/')[2]; console.log(insert_db_string); db.all(insert_db_string, function (err) { if (err !== null) { console.log(err); } db.close(); callback(); }); }; function mongodb_getdata(url, db_callback) { 'use strict'; MongoClient.connect(mongodb_url, function (err, db) { if (err) { throw err; } var findDocuments = function (db, callback) { var collection = db.collection('documents'); var query = {}; var element = url.split('/')[1].toString(); var element_value = url.split('/')[2]; query[element] = parseInt(element_value, 10); collection.find(query).toArray(function (err, docs) { console.log("Found the following records"); callback(docs[0]); }); }; findDocuments(db, function (docs) { console.dir(docs); delete docs._id; db_callback(JSON.stringify(docs)); db.close(); }); }); } DBHelper.getData = function (url, db_callback) { 'use strict'; var db = new sqlite3.Database(config.db_name); // mongodb_getdata(url, db_callback); console.log("SELECT * FROM " + config.table_name + " where " + url.split('/')[1] + "=" + url.split('/')[2]); db.all("SELECT * FROM " + config.table_name + " where " + url.split('/')[1] + "=" + url.split('/')[2], function (err, rows) { if (err !== null) { console.log(err); } db.close(); db_callback(JSON.stringify(rows)); }); }; module.exports = DBHelper;
JavaScript
0
@@ -511,24 +511,1123 @@ urn str;%0A%7D%0A%0A +function mongodb_postData(convertedData, callback) %7B%0A 'use strict';%0A MongoClient.connect(mongodb_url, function (err, db) %7B%0A if (err) %7B%0A throw err;%0A %7D%0A console.log(%22connect:%22 + convertedData);%0A var updateDocument = function (db, mongodb_callback) %7B%0A var collection = db.collection('documents');%0A console.log(%22in update:%22 + convertedData);%0A collection.update(%7B%7D, %7B $set: convertedData%7D, function (err, docs) %7B%0A console.log(%22Found the following records%22);%0A console.log(docs);%0A mongodb_callback(docs);%0A %7D);%0A %7D;%0A updateDocument(db, function (docs) %7B%0A console.log(%22update:%22 + convertedData);%0A console.dir(docs);%0A delete docs._id;%0A callback(JSON.stringify(docs));%0A db.close();%0A %7D);%0A %7D);%0A%7D%0A%0Afunction generateDBMap(str, string) %7B%0A 'use strict';%0A var result = %7B%7D;%0A _.each(config.keys, function (key, index) %7B%0A result%5Bkey%5D = string.split(',')%5Bindex%5D;%0A %7D);%0A return result;%0A%7D%0A%0A DBHelper.pos @@ -1808,24 +1808,128 @@ BKey(block); +%0A%0A// var convertedData = generateDBMap(str, string);%0A// mongodb_postData(convertedData, callback); %0A var ins
a40a4c6082a836fe5a052d282dc4f1199588d025
Use camel-case for font-size property
src/Cell.js
src/Cell.js
// @flow import React from 'react'; function Cell(props) { var classname="xwordjs-cell"; if (props.isHidden) { classname += " xwordjs-cell-hidden"; } else if (props.isBlack) { classname += " xwordjs-cell-black"; } if (props.isTop) { classname += " xwordjs-cell-top"; } if (props.isShaded) { classname += " xwordjs-cell-shaded"; } if (props.isLeft) { classname += " xwordjs-cell-left"; } if (props.isFocus) { classname += " xwordjs-cell-focus"; if (props.isIncorrect) classname += "-incorrect"; } else if (props.isActive) { classname += " xwordjs-cell-active"; if (props.isIncorrect) classname += "-incorrect"; } if (props.isIncorrect && !props.isHidden) { classname += " xwordjs-cell-incorrect"; } var circleclass = ""; if (props.isCircled) { circleclass = "xwordjs-cell-circled"; } var fontsize = 14; if (props.value.length > 2) { fontsize = 30 / props.value.length; } return <div className={classname} id={props.id} onClick={() => props.onClick(props.id)}> <div className={circleclass}> <div className="xwordjs-cell-number">{props.number}</div> <div className="xwordjs-cell-text" style={{"font-size": fontsize + "px"}}>{props.value}</div> </div> </div>; } export default Cell;
JavaScript
0.000001
@@ -1236,18 +1236,17 @@ =%7B%7B%22font --s +S ize%22: fo
af7afe7eb749937eabe5b4cac860f023fe2e4ae9
Revert "Testing."
test/test_controllers.js
test/test_controllers.js
'use strict'; var assert = require('assert'); var fs = require('fs'); var path = require('path'); var after = require('mocha').after; var afterEach = require('mocha').afterEach; var async = require('async'); var before = require('mocha').before; var beforeEach = require('mocha').beforeEach; var cheerio = require('cheerio'); var describe = require('mocha').describe; var express = require('express'); var it = require('mocha').it; var request = require('supertest'); var uuid = require('uuid'); var stormpath = require('../index'); var stormpathRaw = require('stormpath'); describe('register', function() { var stormpathApplication; var stormpathClient; var stormpathPrefix; before(function() { console.log('does it exist?', process.env.STORMPATH_API_KEY_ID); var apiKey = new stormpathRaw.ApiKey( process.env.STORMPATH_API_KEY_ID, process.env.STORMPATH_API_KEY_SECRET ); stormpathClient = new stormpathRaw.Client({ apiKey: apiKey }); }); beforeEach(function(done) { stormpathPrefix = uuid.v4(); var appData = { name: stormpathPrefix }; var opts = { createDirectory: true }; stormpathClient.createApplication(appData, opts, function(err, app) { if (err) { return done(err); } stormpathApplication = app; done(); }); }); afterEach(function(done) { stormpathApplication.delete(function(err) { if (err) { return done(err); } done(); }); }); it('should bind to /register by default', function(done) { var app = express(); app.use(stormpath.init(app, { apiKeyId: process.env.STORMPATH_API_KEY_ID, apiKeySecret: process.env.STORMPATH_API_KEY_SECRET, application: stormpathApplication.href, })); request(app) .get('/register') .expect(200) .end(function(err, res) { if (err) { return done(err); } var $ = cheerio.load(res.text); assert($('input[name=_csrf]').val()); done(); }); }); it('should bind to another URL if specified', function(done) { var app = express(); app.use(stormpath.init(app, { apiKeyId: process.env.STORMPATH_API_KEY_ID, apiKeySecret: process.env.STORMPATH_API_KEY_SECRET, application: stormpathApplication.href, registrationUrl: '/newregister', })); async.series([ function(cb) { request(app) .get('/newregister') .expect(200) .end(function(err, res) { if (err) { return cb(err); } var $ = cheerio.load(res.text); assert($('input[name=_csrf]').val()); cb(); }); }, function(cb) { request(app) .get('/register') .expect(404) .end(function(err, res) { if (err) { return cb(err); } cb(); }); } ], function(err) { if (err) { return done(err); } done(); }); }); it('should not require givenName if requireGivenName is false', function(done) { var app = express(); var agent = request.agent(app); app.use(stormpath.init(app, { apiKeyId: process.env.STORMPATH_API_KEY_ID, apiKeySecret: process.env.STORMPATH_API_KEY_SECRET, application: stormpathApplication.href, requireGivenName: false, })); agent .get('/register') .expect(200) .end(function(err, res) { if (err) { return done(err); } var $ = cheerio.load(res.text); var csrfToken = $('input[name=_csrf]').val(); var email = uuid.v4() + '@test.com'; setTimeout(function() { agent .post('/register') .type('form') .send({ surname: uuid.v4() }) .send({ email: email }) .send({ password: uuid.v4() + uuid.v4().toUpperCase() + '!' }) .send({ _csrf: csrfToken }) .end(function(err, res) { if (err) { return done(err); } stormpathApplication.getAccounts({ email: email }, function(err, accounts) { if (err) { return done(err); } accounts.each(function(account, cb) { if (account.email === email) { return done(); } cb(); }, function() { done(new Error('Account not created.')); }); }); }); }, 5000); }); }); it('should not require surname if requireSurname is false', function(done) { var app = express(); var agent = request.agent(app); app.use(stormpath.init(app, { apiKeyId: process.env.STORMPATH_API_KEY_ID, apiKeySecret: process.env.STORMPATH_API_KEY_SECRET, application: stormpathApplication.href, requireSurname: false, })); agent .get('/register') .expect(200) .end(function(err, res) { if (err) { return done(err); } var $ = cheerio.load(res.text); var csrfToken = $('input[name=_csrf]').val(); var email = uuid.v4() + '@test.com'; setTimeout(function() { agent .post('/register') .type('form') .send({ givenName: uuid.v4() }) .send({ email: email }) .send({ password: uuid.v4() + uuid.v4().toUpperCase() + '!' }) .send({ _csrf: csrfToken }) .end(function(err, res) { if (err) { return done(err); } stormpathApplication.getAccounts({ email: email }, function(err, accounts) { if (err) { return done(err); } accounts.each(function(account, cb) { if (account.email === email) { return done(); } cb(); }, function() { done(new Error('Account not created.')); }); }); }); }, 5000); }); }); });
JavaScript
0
@@ -706,77 +706,8 @@ ) %7B%0A - console.log('does it exist?', process.env.STORMPATH_API_KEY_ID);%0A
8f9da1d96891b99bab9c0c1441da0ba336571d7e
Add tests for move-right command
test/unit/interpreter.js
test/unit/interpreter.js
const assert = require('chai').assert; const interpret = require('../../interpreter'); function initState(input) { return { input: '', output: '', pointer: 0, tape: [], }; } describe('unit > interpreter', () => { let state; beforeEach(() => { state = initState('foo'); }); afterEach(() => { state = null; }); it('Returns the state tree.', () => { const tokens = []; const state = initState('foo'); const result = Object.keys(interpret(tokens, state)); [ 'input', 'output', 'pointer', 'tape', ].forEach( key => assert.include(result, key) ); assert.strictEqual(result.length, 4); }); describe('commands > decrement', () => { it('Stores the new byte in the correct cell.', () => { const tokens = [ { type: '-', }, ]; state = Object.assign( state, { pointer: 2, tape: [ , , 3, ], } ); const result = interpret(tokens, state).tape; const expected = [ , , 2, ]; assert.deepEqual(expected, result); }); it('Decreases the current byte by 1.', () => { const tokens = [ { type: '-', }, ]; state = Object.assign(state, { tape: [ 3, ], }); const result = interpret(tokens, state).tape; const expected = [ 2, ]; assert.deepEqual(expected, result); }); it('Wraps from 0 to 255.', () => { const tokens = [ { type: '-', }, ]; state = Object.assign(state, { tape: [ 0, ], }); const result = interpret(tokens, state).tape; const expected = [ 255, ]; assert.deepEqual(expected, result); }); it('Treats an undefined byte as 0.', () => { const tokens = [ { type: '-', }, ]; const result = interpret(tokens, state).tape; const expected = [ 255, ]; assert.deepEqual(expected, result); }); }); describe('commands > increment', () => { it('Stores the new byte at the correct position.', () => { const tokens = [ { type: '+', }, ]; state = Object.assign( state, { pointer: 2, tape: [ , , 3, ], } ); const result = interpret(tokens, state).tape; const expected = [ , , 4, ]; assert.deepEqual(expected, result); }); it('Increases the current byte by 1.', () => { const tokens = [ { type: '+', }, ]; state = Object.assign(state, { tape: [ 3, ], }); const result = interpret(tokens, state).tape; const expected = [ 4, ]; assert.deepEqual(expected, result); }); it('Wraps from 255 to 0.', () => { const tokens = [ { type: '+', }, ]; state = Object.assign(state, { tape: [ 255, ], }); const result = interpret(tokens, state).tape; const expected = [ 0, ]; assert.deepEqual(expected, result); }); it('Treats an undefined byte as 0.', () => { const tokens = [ { type: '+', }, ]; const result = interpret(tokens, state).tape; const expected = [ 1, ]; assert.deepEqual(expected, result); }); }); describe('commands > move-left', () => { it('Moves the pointer 1 to the left.', () => { const tokens = [ { type: '<', }, ]; state = Object.assign(state, { pointer: 1, }); const result = interpret(tokens, state).pointer; const expected = 0; assert.deepEqual(expected, result); }); it('Throws a RangeError if the next position is out of range.', () => { const tokens = [ { type: '<', }, ]; assert.throws(() => interpret(tokens, state), RangeError); }); }); describe('commands > move-right', () => { it('Moves the pointer 1 to the right.', () => {}); }); describe('commands > loop', () => { it('Repeats the loop until the current byte is 0.', () => {}); it('Skips the loop if the current byte is 0.', () => {}); it('Runs an arbitrary number of nested loops.', () => {}); }); describe('commands > input', () => { it('Gets the ASCII code point for the first character of the input string.', () => {}); it('Sets the code point as the current byte.', () => {}); it('Removes the first character from the input string.', () => {}); }); describe('commands > output', () => { it('Gets the ASCII character at the code point equal to the current byte.', () => {}); it('Appends the ASCII character to state.output', () => {}); }); });
JavaScript
0.000001
@@ -3684,32 +3684,259 @@ right.', () =%3E %7B +%0A const tokens = %5B %7B type: '%3E', %7D, %5D;%0A%0A state = Object.assign(state, %7B pointer: 1, %7D);%0A%0A const result = interpret(tokens, state).pointer;%0A%0A const expected = 2;%0A%0A assert.deepEqual(expected, result);%0A %7D);%0A %7D);%0A%0A des
5bbb8a32966d794d665e031c3a416922f078d71a
Clean redis session data before test
test/unit/store/redis.js
test/unit/store/redis.js
/** * The MIT License (MIT) * * Copyright (c) 2017 GochoMugo <[email protected]> * Copyright (c) 2017 Forfuture LLC <[email protected]> */ // built-in modules const assert = require("assert"); // own modules const SessionStore = require("../../../store/base"); const RedisStore = require("../../../store/redis"); describe("RedisStore", function() { const sid = "SID"; const session = { key: "value" }; const options = { ttl: +Infinity }; let store; beforeEach(function() { store = new RedisStore({ prefix: "test:mau:", }); }); it("is exported as a Function/constructor", function() { assert.equal(typeof RedisStore, "function"); }); it("sub-classes SessionStore", function() { assert.ok(store instanceof SessionStore); }); describe("#put()", function() { it("[#get()] saves key-value pair", function(done) { store.put(sid, session, options, function(error) { assert.ifError(error); store.get(sid, function(error, sess) { assert.ifError(error); assert.deepEqual(sess, session, "Incorrect session returned."); return done(); }); }); }); }); describe("#del()", function() { it("deletes session", function(done) { store.del(sid, function(error) { assert.ifError(error); store.get(sid, function(error, sess) { assert.ifError(error); assert.ok(!sess, "Session not destroyed."); return done(); }); }); }); }); });
JavaScript
0
@@ -353,24 +353,56 @@ unction() %7B%0A + const prefix = %22test:mau:%22;%0A const si @@ -412,16 +412,16 @@ %22SID%22;%0A - cons @@ -522,32 +522,36 @@ reEach(function( +done ) %7B%0A stor @@ -593,32 +593,49 @@ efix -: %22test:mau:%22,%0A %7D +,%0A %7D);%0A store.del(sid, done );%0A @@ -1392,16 +1392,25 @@ it(%22 +%5B#put()%5D deletes @@ -1428,32 +1428,138 @@ unction(done) %7B%0A + store.put(sid, session, options, function(error) %7B%0A assert.ifError(error);%0A stor @@ -1595,32 +1595,36 @@ + assert.ifError(e @@ -1638,32 +1638,36 @@ + + store.get(sid, f @@ -1701,32 +1701,36 @@ + assert.ifError(e @@ -1748,32 +1748,36 @@ + + assert.ok(!sess, @@ -1816,32 +1816,36 @@ + return done();%0A @@ -1835,32 +1835,56 @@ return done();%0A + %7D);%0A
5f17d881a9e8447a317f97f029f1a914888f875c
Fix nit.
test/unit/stream_spec.js
test/unit/stream_spec.js
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ 'use strict'; describe('stream', function() { beforeEach(function() { this.addMatchers({ toMatchTypedArray: function(expected) { var actual = this.actual; if (actual.length != expected.length) return false; for (var i = 0, ii = expected.length; i < ii; i++) { var a = actual[i], b = expected[i]; if (a !== b) return false; } return true; } }); }); describe('PredictorStream', function() { it('should decode simple predictor data', function() { var dict = new Dict(); dict.set('Predictor', 12); dict.set('Colors', 1); dict.set('BitsPerComponent', 8); dict.set('Columns', 2); var input = new Stream(new Uint8Array([2, 100, 3, 2, 1, 255, 2, 1, 255]), 0, 9, dict); var predictor = new PredictorStream(input, dict); var result = predictor.getBytes(6); expect(result).toMatchTypedArray(new Uint8Array([100, 3, 101, 2, 102, 1])); }); }); });
JavaScript
0.000005
@@ -1100,16 +1100,25 @@ edArray( +%0A new Uint @@ -1149,16 +1149,23 @@ 102, 1%5D) +%0A );%0A %7D
0e4563924c752e24f3ef779f9d455ac0cebe81ae
Update Configuration.test.js
lib/Configuration.test.js
lib/Configuration.test.js
'use strict'; /** * Unit tests for Configuration. */ const chai = require('chai'); const Configuration = require('./Configuration'); const expect = chai.expect; describe('Configuration', () => { describe('defaults', () => { let expectedDefaults; before(() => { expectedDefaults = { webpackConfig: 'webpack.config.js', includeModules: false, packager: 'npm', packagerOptions: {}, keepOutputDirectory: false, config: null, serializedCompile: false }; }); it('should set default configuration without custom', () => { const config = new Configuration(); expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults); expect(config).to.have.a.property('hasLegacyConfig').that.is.false; }); it('should set default configuration without webpack property', () => { const config = new Configuration({}); expect(config).to.have.a.property('_config').that.deep.equals(expectedDefaults); expect(config).to.have.a.property('hasLegacyConfig').that.is.false; }); }); describe('with legacy configuration', () => { it('should use custom.webpackIncludeModules', () => { const testCustom = { webpackIncludeModules: { forceInclude: ['mod1'] } }; const config = new Configuration(testCustom); expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules); }); it('should use custom.webpack as string', () => { const testCustom = { webpack: 'myWebpackFile.js' }; const config = new Configuration(testCustom); expect(config).to.have.a.property('webpackConfig').that.equals('myWebpackFile.js'); }); it('should detect it', () => { const testCustom = { webpack: 'myWebpackFile.js' }; const config = new Configuration(testCustom); expect(config).to.have.a.property('hasLegacyConfig').that.is.true; }); it('should add defaults', () => { const testCustom = { webpackIncludeModules: { forceInclude: ['mod1'] }, webpack: 'myWebpackFile.js' }; const config = new Configuration(testCustom); expect(config).to.have.a.property('includeModules').that.deep.equals(testCustom.webpackIncludeModules); expect(config._config).to.deep.equal({ webpackConfig: 'myWebpackFile.js', includeModules: { forceInclude: ['mod1'] }, packager: 'npm', packagerOptions: {}, keepOutputDirectory: false, config: null, serializedCompile: false }); }); }); describe('with a configuration object', () => { it('should use it and add any defaults', () => { const testCustom = { webpack: { includeModules: { forceInclude: ['mod1'] }, webpackConfig: 'myWebpackFile.js' } }; const config = new Configuration(testCustom); expect(config._config).to.deep.equal({ webpackConfig: 'myWebpackFile.js', includeModules: { forceInclude: ['mod1'] }, packager: 'npm', packagerOptions: {}, keepOutputDirectory: false, config: null, serializedCompile: false }); }); it('should favor new configuration', () => { const testCustom = { webpackIncludeModules: { forceExclude: ['mod2'] }, webpack: { includeModules: { forceInclude: ['mod1'] }, webpackConfig: 'myWebpackFile.js' } }; const config = new Configuration(testCustom); expect(config._config).to.deep.equal({ webpackConfig: 'myWebpackFile.js', includeModules: { forceInclude: ['mod1'] }, packager: 'npm', packagerOptions: {}, keepOutputDirectory: false, config: null, serializedCompile: false }); }); }); });
JavaScript
0.000001
@@ -496,32 +496,30 @@ -serializedCompile: false +concurrency: undefined %0A @@ -2549,32 +2549,30 @@ -serializedCompile: false +concurrency: undefined %0A @@ -3175,32 +3175,30 @@ -serializedCompile: false +concurrency: undefined %0A @@ -3800,32 +3800,30 @@ -serializedCompile: false +concurrency: undefined %0A
1e11be51df72c81a3df8aafc6c0e072462d6b093
Fix for custom arrows issue https://github.com/akiran/react-slick/issues/671
examples/CustomArrows.js
examples/CustomArrows.js
import React, { Component } from 'react' import Slider from '../src/slider' var SampleNextArrow = React.createClass({ render: function() { return <div {...this.props} style={{display: 'block', background: 'red'}}></div>; } }); var SamplePrevArrow = React.createClass({ render: function() { return ( <div {...this.props} style={{display: 'block', background: 'red'}}></div> ); } }); export default class CustomArrows extends Component { render() { const settings = { dots: true, infinite: true, slidesToShow: 3, slidesToScroll: 1, nextArrow: <SampleNextArrow />, prevArrow: <SamplePrevArrow /> }; return ( <div> <h2>Custom Arrows</h2> <Slider {...settings}> <div><h3>1</h3></div> <div><h3>2</h3></div> <div><h3>3</h3></div> <div><h3>4</h3></div> <div><h3>5</h3></div> <div><h3>6</h3></div> </Slider> </div> ); } }
JavaScript
0
@@ -74,58 +74,57 @@ r'%0A%0A -var SampleNextArrow = React.createClass( +class CarouselArrow extends Component %7B%0A +%0A render : fu @@ -115,34 +115,24 @@ %7B%0A%0A render -: function () %7B%0A ret @@ -132,21 +132,28 @@ -return %3Cdiv %7B +let style = %7B%0A ...t @@ -157,34 +157,38 @@ ..this.props -%7D +. style -=%7B%7B +,%0A display: 'bl @@ -184,32 +184,38 @@ isplay: 'block', +%0A background: 're @@ -216,183 +216,183 @@ d: ' -red'%7D%7D%3E%3C/div%3E;%0A %7D%0A%7D);%0A%0Avar SamplePrevArrow = React.createClass(%7B%0A render: function() %7B%0A return (%0A %3Cdiv %7B...this.props%7D style=%7B%7Bdisplay: 'block', background: 'red'%7D%7D%3E +#d8e4e8',%0A 'paddingLeft': '6px',%0A %7D;%0A%0A return (%0A %3Cdiv className=%7Bthis.props.className%7D%0A onClick=%7Bthis.props.onClick%7D%0A style=%7Bstyle%7D%3E%0A %3C/di @@ -406,18 +406,16 @@ );%0A %7D%0A%7D -); %0A%0Aexport @@ -608,18 +608,16 @@ w: %3C -SampleNext +Carousel Arro @@ -644,18 +644,16 @@ w: %3C -SamplePrev +Carousel Arro
2291f6c2ae8785f4dff7d5c1054f763462f3eeec
Fix host 'id' value in error responses
host/nodeachrome.js
host/nodeachrome.js
#!/Users/admin/.nvm/versions/node/v4.2.4/bin/node // ^ full path to node must be specified above, edit for your system. may also try: // #!/usr/local/bin/node 'use strict'; // Native messaging host, provides native access to OS functions over stdin/stdout // for the Google Chrome extension // TODO: port off nodejs? const process = require('process'); const fs = require('fs'); const path = require('path'); const nativeMessage = require('chrome-native-messaging'); const input = new nativeMessage.Input(); const transform = new nativeMessage.Transform(messageHandler); const output = new nativeMessage.Output(); // Prepend all paths with this filesystem root const ROOT = path.join(__dirname, '../sandbox'); if (!fs.existsSync(ROOT)) fs.mkdirSync(ROOT); function fixpath(relativePath) { const newPath = path.join(ROOT, relativePath); if (!newPath.startsWith(ROOT)) { return ROOT; // tried to go above root, return root } return newPath; } process.stdin .pipe(input) .pipe(transform) .pipe(output) .pipe(process.stdout); function encodeResult(err, data, id) { if (err) { return {error: { code: err.errno, // must be an integer, but err.code is a string like 'ENOENT' message: err.toString(), id: id, } }; } else { return {result:data, id:id}; } } function messageHandler(msg, push, done) { const method = msg.method; const params = msg.params; const id = msg.id; function cb(err, data) { push(encodeResult(err, data, id)); done(); } if (method === 'echo') { push(msg); done(); } else if (method === 'fs.access') { const path = fixpath(params[0]); if (params.length < 2) { fs.access(path, cb); } else { const mode = params[1]; fs.access(path, mode, cb); } } else if (method === 'fs.chmod') { const path = fixpath(params[0]); const mode = params[1]; fs.chmod(path, mode, cb); } else if (method === 'fs.chown') { const path = fixpath(params[0]); const uid = params[1]; const gid = params[2]; fs.chown(path, uid, gid, cb); } else if (method === 'fs.close') { const fd = params[0]; fs.close(fd, cb); /* TODO } else if (method === 'fs.createReadStream') { const path = params[0]; */ } else if (method === 'fs.exists') { // deprecated, by npm uses const path = fixpath(params[0]); fs.exists(path, cb); } else if (method === 'fs.fstat') { const fd = params[0]; fs.fstat(fd, cb); } else if (method === 'fs.lstat') { const path = fixpath(params[0]); fs.lstat(path, cb); } else if (method === 'fs.mkdir') { const path = fixpath(params[0]); if (params.length < 2) { fs.mkdir(path, cb); } else { const mode = params[1]; fs.mkdir(path, mode, cb); } } else if (method === 'fs.open') { const path = fixpath(params[0]); const flags = params[1]; if (params.length < 3) { const mode = params[2]; fs.open(path, flags, mode, cb); } else { fs.open(path, flags, cb); } } else if (method === 'fs.readFile') { const file = fixpath(params[0]); // TODO: restrict access to only a limited set of files if (params.length < 2) { //const callback = params[1]; fs.readFile(file, cb); } else { const options = params[1]; //const callback = params[2]; fs.readFile(file, options, cb); } } else if (method === 'fs.readdir') { const path = fixpath(params[0]); fs.readdir(path, cb); } else if (method === 'fs.readlink') { const path = fixpath(params[0]); fs.readlink(path, cb); } else if (method === 'fs.realpath') { const path = fixpath(params[0]); if (params.length < 2) { fs.realpath(path, cb); } else { const cache = params[1]; fs.realpath(path, cache, cb); } } else if (method === 'fs.rename') { const oldPath = fixpath(params[0]); const newPath = fixpath(params[1]); fs.rename(oldPath, newPath, cb); } else if (method === 'fs.rmdir') { const path = fixpath(params[0]); fs.rmdir(path, cb); } else if (method === 'fs.stat') { const path = fixpath(params[0]); fs.stat(path, cb); } else if (method === 'fs.symlink') { const target = fixpath(params[0]); const path = fixpath(params[1]); if (params.length < 3) { fs.symlink(target, path, cb); } else { const type = params[2]; fs.symlink(target, path, type, cb); } } else if (method === 'fs.unlink') { const path = fixpath(params[0]); fs.unlink(path, cb); } else if (method === 'fs.writeFile') { const file = fixpath(params[0]); const data = params[1]; if (params.length < 3) { fs.writeFile(file, data, cb); } else { const options = params[2]; fs.writeFile(file, data, options, cb); } } else if (method === 'fs.write') { const fd = params[0]; // TODO: restrict fd? 0, 1, 2 stdio? const buffer = params[1]; const offset = params[2]; const length = params[3]; if (params.length < 5) { fs.write(fd, data, length, cb); } else { const position = params[4]; fd.write(fd, data, length, position, cb); } } else { push({error: { code: -32601, // defined in http://www.jsonrpc.org/specification#response_object message: 'Method not found', data: `invalid method: ${method}`, id: id, }}); done(); } }
JavaScript
0.000004
@@ -1272,32 +1272,25 @@ - id: id +%7D ,%0A @@ -1292,17 +1292,23 @@ -%7D +id: id, %0A
ae33f6a77e2bc7b5d095c9b46ee0cf8d1a977b70
add delete confirmation reducer to reducer index [#146514255]
client/reducers/index.js
client/reducers/index.js
import { combineReducers } from 'redux'; import users from './userReducer'; import documents from './documentReducer'; import search from './searchReducer'; import auth from './auth'; const rootReducer = combineReducers({ auth, documents, users, search }); export default rootReducer;
JavaScript
0
@@ -34,16 +34,66 @@ redux';%0A +import %7B reducer %7D from 'react-redux-sweetalert';%0A import u @@ -296,16 +296,39 @@ users,%0A + sweetalert: reducer,%0A search
e57b78e4014c6d004e20ae1a9cd50645cd5ef443
Clarify test, add ref to special code in comment
tests/BookReader.test.js
tests/BookReader.test.js
import '../BookReader/jquery-1.10.1.js'; import '../BookReader/jquery-ui-1.12.0.min.js'; import '../BookReader/jquery.browser.min.js'; import '../BookReader/dragscrollable-br.js'; import '../BookReader/jquery.colorbox-min.js'; import '../BookReader/jquery.bt.min.js'; import BookReader from '../src/js/BookReader.js'; import '../src/js/plugins/plugin.resume.js'; import '../src/js/plugins/plugin.url.js'; let br; beforeAll(() => { document.body.innerHTML = '<div id="BookReader">'; br = new BookReader(); }); afterEach(() => { jest.clearAllMocks(); }); test('has registered PostInit events', () => { expect(BookReader.eventNames.PostInit).toBeTruthy(); }); test('has registered zoom events', () => { expect(BookReader.eventNames.zoomIn).toBeTruthy(); expect(BookReader.eventNames.zoomOut).toBeTruthy(); }); test('has registered view type selected events', () => { expect(BookReader.eventNames['1PageViewSelected']).toBeTruthy(); expect(BookReader.eventNames['2PageViewSelected']).toBeTruthy(); expect(BookReader.eventNames['3PageViewSelected']).toBeTruthy(); }); test('has registered fullscreen toggle event', () => { expect(BookReader.eventNames.fullscreenToggled).toBeTruthy(); }); test('checks cookie when initParams called', () => { br.getResumeValue = jest.fn(() => 15); br.urlReadFragment = jest.fn(() => ''); const params = br.initParams(); expect(br.getResumeValue).toHaveBeenCalledTimes(1); expect(params.init).toBe(true); expect(params.index).toBe(15); expect(params.fragmentChange).toBe(true); }); test('does not check cookie when initParams called', () => { br.getResumeValue = jest.fn(() => null); br.urlReadFragment = jest.fn(() => ''); br.options.enablePageResume = false; const params = br.initParams(); expect(br.getResumeValue).toHaveBeenCalledTimes(0); expect(params.init).toBe(true); expect(params.index).toBe(0); expect(params.fragmentChange).toBe(false); }); test('overrides cookie if page fragment when InitParams called', () => { br.getResumeValue = jest.fn(() => 15); br.urlReadFragment = jest.fn(() => 'page/n4'); br.options.enablePageResume = true; const params = br.initParams(); expect(br.getResumeValue).toHaveBeenCalledTimes(1); expect(params.init).toBe(true); expect(params.index).toBe(4); expect(params.fragmentChange).toBe(true); }); test('sets prevReadMode when init called', () => { br.init(); expect(br.prevReadMode).toBeTruthy(); }); test('sets prevPageMode if initial mode is thumb', () => { br.urlReadFragment = jest.fn(() => 'page/n4/mode/thumb'); br.init(); expect(br.prevReadMode).toBe(BookReader.constMode1up); }); test('calls switchMode with init option when init called', () => { br.switchMode = jest.fn(); br.init(); expect(br.switchMode.mock.calls[0][1]) .toHaveProperty('init', true); }); test('has suppressFragmentChange true when init with no input', () => { br.getResumeValue = jest.fn(() => null); br.urlReadFragment = jest.fn(() => ''); br.switchMode = jest.fn(); br.init(); expect(br.switchMode.mock.calls[0][1]) .toHaveProperty('suppressFragmentChange', true); }); test('has suppressFragmentChange false when init with cookie', () => { br.getResumeValue = jest.fn(() => 5); br.urlReadFragment = jest.fn(() => ''); br.switchMode = jest.fn(); br.init(); expect(br.switchMode.mock.calls[0][1]) .toHaveProperty('suppressFragmentChange', false); }); test('has suppressFragmentChange false when init with fragment', () => { br.getResumeValue = jest.fn(() => null); br.urlReadFragment = jest.fn(() => 'mode/1up'); br.switchMode = jest.fn(); br.init(); expect(br.switchMode.mock.calls[0][1]) .toHaveProperty('suppressFragmentChange', false); });
JavaScript
0
@@ -1946,41 +1946,62 @@ st(' -overrides cookie if page fragment +gets index from fragment when both fragment and cookie whe @@ -2463,32 +2463,147 @@ eTruthy();%0A%7D);%0A%0A +// Default behavior same in%0A// BookReader.prototype.drawLeafsThumbnail%0A// BookReader.prototype.getPrevReadMode%0A test('sets prevP
446c64496dd2abcbae478d4698e4cdcdbc7e4f43
remove protocol from nominatim url
contrib/l.geosearch.provider.openstreetmap.js
contrib/l.geosearch.provider.openstreetmap.js
/** * L.Control.GeoSearch - search for an address and zoom to it's location * L.GeoSearch.Provider.OpenStreetMap uses openstreetmap geocoding service * https://github.com/smeijer/leaflet.control.geosearch */ L.GeoSearch.Provider.OpenStreetMap = L.Class.extend({ options: { }, initialize: function(options) { options = L.Util.setOptions(this, options); }, GetServiceUrl: function (qry) { var parameters = L.Util.extend({ q: qry, format: 'json' }, this.options); return 'http://nominatim.openstreetmap.org/search' + L.Util.getParamString(parameters); }, ParseJSON: function (data) { if (data.length == 0) return []; var results = []; for (var i = 0; i < data.length; i++) results.push(new L.GeoSearch.Result( data[i].lon, data[i].lat, data[i].display_name )); return results; } });
JavaScript
0.000009
@@ -551,13 +551,8 @@ rn ' -http: //no @@ -1006,8 +1006,9 @@ %7D%0A%7D); +%0A
231c549a19b2adef0d33fa1bc33f9705fa78404d
Remove link to elife and link to HW feedback form.
nodes/cover/cover_view.js
nodes/cover/cover_view.js
"use strict"; var _ = require("underscore"); var util = require("substance-util"); var html = util.html; var NodeView = require("../node").View; var TextView = require("../text").View; var $$ = require("substance-application").$$; var articleUtil = require("../../article_util"); // Lens.Cover.View // ========================================================================== var CoverView = function(node, viewFactory) { NodeView.call(this, node, viewFactory); this.$el.attr({id: node.id}); this.$el.addClass("content-node cover"); }; CoverView.Prototype = function() { // Render it // -------- // // .content // video // source // .title // .caption // .doi this.render = function() { NodeView.prototype.render.call(this); var node = this.node; var pubInfo = this.node.document.get('publication_info'); // Intro + Send feedback for HighWire // -------------- // // TODO: this should be refactored and live in some configuration object if (pubInfo.provider === "HighWire") { var introEl = $$('.intro.container', { children: [ $$('.intro-text', { html: '<i class="icon-info"></i>&nbsp;&nbsp;<a href="http://lens.elifesciences.org">Lens</a> provides a novel way of looking at research on the web.' }), $$('a.send-feedback', {href: "mailto:[email protected]?subject=Lens%20Feedback", text: "Send feedback"}) ] }); this.content.appendChild(introEl); } if (node.breadcrumbs && node.breadcrumbs.length > 0) { var breadcrumbs = $$('.breadcrumbs', { children: _.map(node.breadcrumbs, function(bc) { var html; if (bc.image) { html = '<img src="'+bc.image+'" title="'+bc.name+'"/>'; } else { html = bc.name; } return $$('a', {href: bc.url, html: html}) }) }); this.content.appendChild(breadcrumbs); } if (pubInfo) { var pubDate = pubInfo.published_on; if (pubDate) { this.content.appendChild($$('.published-on', { text: articleUtil.formatDate(pubDate) })); } } // Title View // -------------- // // HACK: we need to update to a newer substance version to be able to delegate // to sub-views. var titleView = new TextView(this.node, { path: ['document', 'title'], classes: 'title' }); this.content.appendChild(titleView.render().el); // Render Authors // -------------- // var authors = $$('.authors', { children: _.map(node.getAuthors(), function(authorPara) { var paraView = this.viewFactory.createView(authorPara); var paraEl = paraView.render().el; this.content.appendChild(paraEl); return paraEl; }, this) }); authors.appendChild($$('.content-node.text.plain', { children: [ $$('.content', {text: this.node.document.on_behalf_of}) ] })); this.content.appendChild(authors); // Render Links // -------------- // if (pubInfo && pubInfo.links.length > 0) { var linksEl = $$('.links'); _.each(pubInfo.links, function(link) { if (link.type === "json" && link.url === "") { // Make downloadable JSON var json = JSON.stringify(this.node.document.toJSON(), null, ' '); var bb = new Blob([json], {type: "application/json"}); linksEl.appendChild($$('a.json', { href: window.URL ? window.URL.createObjectURL(bb) : "#", html: '<i class="icon-external-link-sign"></i> '+link.name, target: '_blank' })); } else { linksEl.appendChild($$('a.'+link.type, { href: link.url, html: '<i class="icon-external-link-sign"></i> '+ link.name, target: '_blank' })); } }, this); this.content.appendChild(linksEl); } if (pubInfo) { var doi = pubInfo.doi; if (doi) { this.content.appendChild($$('.doi', { html: 'DOI: <a href="'+doi+'">'+doi+'</a>' })); } } return this; } }; CoverView.Prototype.prototype = NodeView.prototype; CoverView.prototype = new CoverView.Prototype(); module.exports = CoverView;
JavaScript
0
@@ -928,17 +928,16 @@ -%0A // - %0A // @@ -1205,56 +1205,12 @@ bsp; -%3Ca href=%22http://lens.elifesciences.org%22%3ELens%3C/a%3E +Lens pro @@ -1321,58 +1321,48 @@ f: %22 -mailto:[email protected]?subject=Lens%2520F +http://home.highwire.org/feedback/lens-f eedb @@ -1388,16 +1388,35 @@ eedback%22 +, target: %22_blank%22 %7D)%0A @@ -1939,20 +1939,16 @@ %0A %7D%0A%0A - %0A if @@ -2195,25 +2195,24 @@ -----%0A // - %0A%0A // HAC @@ -2517,25 +2517,24 @@ -----%0A // - %0A%0A var au @@ -3063,17 +3063,16 @@ -%0A // - %0A%0A if
f5f7e2dbed86e3b31dc2636e22d59c5d9ba6842f
Update electron sample to make it work on electron v5.
samples/electron/start.js
samples/electron/start.js
const electron = require('electron') // Module to control application life. const app = electron.app // Module to create native browser window. const BrowserWindow = electron.BrowserWindow; var mainWindow = null; app.on('window-all-closed', function() { if (process.platform != 'darwin') app.quit(); }); app.on('ready', function() { mainWindow = new BrowserWindow({width: 800, height: 600}); mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); });
JavaScript
0
@@ -369,16 +369,21 @@ Window(%7B +%0A width: 8 @@ -385,16 +385,20 @@ th: 800, +%0A height: @@ -401,16 +401,66 @@ ght: 600 +,%0A webPreferences: %7B nodeIntegration: true %7D%0A %7D);%0A ma
0429a053484977fd26a3cd53fbbf28000f896b3a
Add tests
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-markdown-remark/test/fixtures/unvalidated.js
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-markdown-remark/test/fixtures/unvalidated.js
'use strict'; // MODULES // var config = require( './config.js' ); // VARIABLES // var valid; var test; // MAIN // // Create our test cases: valid = []; test = { 'code': [ 'function fizzBuzz() {', ' // This is a single-line comment', ' var out;', ' var i;', '', ' for ( i = 1; i <= 100; i++ ) {', ' /*', ' * This is a multi-line comment...', ' */', ' out = ( i % 5 === 0 ) ? "Buzz" : ( i % 3 === 0 ) ? "Fizz" : i;', ' console.log( out );', ' }', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/**/', 'function fizzBuzz() {', ' // This is a single-line comment', ' var out;', ' var i;', '', ' for ( i = 1; i <= 100; i++ ) {', ' /*', ' * This is a multi-line comment...', ' */', ' out = ( i % 5 === 0 ) ? "Buzz" : ( i % 3 === 0 ) ? "Fizz" : i;', ' console.log( out );', ' }', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '// Beep boop.', 'function fizzBuzz() {', ' // This is a single-line comment', ' var out;', ' var i;', '', ' for ( i = 1; i <= 100; i++ ) {', ' /*', ' * This is a multi-line comment...', ' */', ' out = ( i % 5 === 0 ) ? "Buzz" : ( i % 3 === 0 ) ? "Fizz" : i;', ' console.log( out );', ' }', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); test = { 'code': [ '/* Beep boop. */', 'function fizzBuzz() {', ' // This is a single-line comment', ' var out;', ' var i;', '', ' for ( i = 1; i <= 100; i++ ) {', ' /*', ' * This is a multi-line comment...', ' */', ' out = ( i % 5 === 0 ) ? "Buzz" : ( i % 3 === 0 ) ? "Fizz" : i;', ' console.log( out );', ' }', '}' ].join( '\n' ), 'options': [ { 'config': config } ] }; valid.push( test ); // EXPORTS // module.exports = valid;
JavaScript
0.000001
@@ -1922,24 +1922,286 @@ h( test );%0A%0A +// The following is only valid as the configuration provided:%0Atest = %7B%0A%09'code': %5B%0A%09%09'/**',%0A%09%09'* Beep boop.',%0A%09%09'*',%0A%09%09'* ## Beep',%0A%09%09'*',%0A%09%09'* ## Beep',%0A%09%09'*/',%0A%09%09'function beep() %7B',%0A%09%09' console.log( %22boop%22 );',%0A%09%09'%7D'%0A%09%5D.join( '%5Cn' )%0A%7D;%0Avalid.push( test );%0A%0A %0A// EXPORTS
a256180f267a02c53a6809a7db01853629ae6fdb
Add isPaused check to fail download quicker
src/actions/Bluetooth/SensorDownloadActions.js
src/actions/Bluetooth/SensorDownloadActions.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2021 */ import moment from 'moment'; import { PermissionActions } from '../PermissionActions'; import BleService from '../../bluetooth/BleService'; import TemperatureLogManager from '../../bluetooth/TemperatureLogManager'; import SensorManager from '../../bluetooth/SensorManager'; import { UIDatabase } from '../../database'; import { isValidMacAddress, VACCINE_CONSTANTS } from '../../utilities/modules/vaccines/index'; import { DOWNLOADING_ERROR_CODES } from '../../utilities/modules/vaccines/constants'; import { syncStrings } from '../../localization'; import { selectIsSyncingTemps } from '../../selectors/Bluetooth/sensorDownload'; import { BreachActions } from '../BreachActions'; export const DOWNLOAD_ACTIONS = { DOWNLOAD_LOGS_START: 'Bluetooth/downloadLogsStart', DOWNLOAD_LOGS_ERROR: 'Bluetooth/downloadLogsError', DOWNLOAD_LOGS_COMPLETE: 'Bluetooth/downloadLogsComplete', PASSIVE_DOWNLOAD_START: 'Bluetooth/passiveDownloadStart', SENSOR_DOWNLOAD_START: 'Bluetooth/sensorDownloadStart', SENSOR_DOWNLOAD_SUCCESS: 'Bluetooth/sensorDownloadSuccess', SENSOR_DOWNLOAD_ERROR: 'Bluetooth/sensorDownloadError', }; const startPassiveDownloadJob = () => ({ type: DOWNLOAD_ACTIONS.PASSIVE_DOWNLOAD_START }); const downloadLogsStart = () => ({ type: DOWNLOAD_ACTIONS.DOWNLOAD_LOGS_START }); const downloadLogsComplete = () => ({ type: DOWNLOAD_ACTIONS.DOWNLOAD_LOGS_COMPLETE }); const downloadLogsError = error => ({ type: DOWNLOAD_ACTIONS.DOWNLOAD_LOGS_ERROR, payload: { error }, }); const sensorDownloadStart = sensor => ({ type: DOWNLOAD_ACTIONS.SENSOR_DOWNLOAD_START, payload: { sensor }, }); const sensorDownloadError = (sensor, error) => ({ type: DOWNLOAD_ACTIONS.SENSOR_DOWNLOAD_ERROR, payload: { sensor, error }, }); const sensorDownloadSuccess = sensor => ({ type: DOWNLOAD_ACTIONS.SENSOR_DOWNLOAD_SUCCESS, payload: { sensor }, }); const downloadAll = () => async dispatch => { dispatch(downloadLogsStart()); // Ensure there are some sensors which have been assigned a location before syncing. const sensors = UIDatabase.objects('Sensor').filtered('location != null && isActive == true'); if (!sensors.length) { dispatch(downloadLogsError(syncStrings.no_sensors)); return null; } for (let i = 0; i < sensors.length; i++) { const sensor = sensors[i]; if (isValidMacAddress(sensors[i].macAddress)) { // Intentionally sequential try { // eslint-disable-next-line no-await-in-loop await dispatch(downloadLogsFromSensor(sensor)); // eslint-disable-next-line no-await-in-loop await dispatch(downloadInfoFromSensor(sensor)); } catch (exception) { dispatch(downloadLogsError(exception.message)); } } else { dispatch(sensorDownloadError(sensor, DOWNLOADING_ERROR_CODES.E_INVALID_MAC_FORMAT)); } } // this will now overwrite the error message dispatch(downloadLogsComplete()); return null; }; const downloadLogsFromSensor = sensor => async dispatch => { try { const { macAddress, logInterval, logDelay, isPaused, programmedDate, mostRecentLog } = sensor; const timeNow = moment(); if (timeNow.isAfter(moment(logDelay)) && !isPaused) { dispatch(sensorDownloadStart(sensor)); try { const downloadedLogsResult = (await BleService().downloadLogsWithRetries( macAddress, VACCINE_CONSTANTS.MAX_BLUETOOTH_COMMAND_ATTEMPTS )) ?? {}; if (downloadedLogsResult) { try { const mostRecentLogTime = moment(mostRecentLog ? mostRecentLog.timestamp : 0); // This is the time which must have passed before downloading a new log. // Either the time has passed the programmed date (ensuring no time travel), // the logging delay must be in the past and the most recent log + the logging interval // must be in the past. const downloadBoundary = moment .max([ moment(programmedDate), moment(logDelay), moment(mostRecentLogTime).add(logInterval, 's'), ]) .unix(); // If the logDelay is after the most recent log (which, if there aren't any logs is 0) // then the nextTimestamp should be the logDelay. Else, use the most recent log time. const nextTimestamp = moment(logDelay).isAfter(mostRecentLogTime) ? moment(logDelay) : mostRecentLogTime; const numberOfLogsToSave = await TemperatureLogManager().calculateNumberOfLogsToSave( logInterval, downloadBoundary ); const temperatureLogs = await TemperatureLogManager().createLogs( downloadedLogsResult, sensor, numberOfLogsToSave, nextTimestamp.unix() ); await TemperatureLogManager().saveLogs(temperatureLogs); await dispatch(BreachActions.createConsecutiveBreaches(sensor)); } catch (e) { dispatch(sensorDownloadError(sensor, DOWNLOADING_ERROR_CODES.E_CANT_CONNECT)); } } } catch (e) { dispatch(sensorDownloadError(sensor, DOWNLOADING_ERROR_CODES.E_CANT_SAVE)); } dispatch(sensorDownloadSuccess(sensor)); } } catch (error) { dispatch(sensorDownloadError(sensor, DOWNLOADING_ERROR_CODES.E_UNKNOWN)); } }; const downloadInfoFromSensor = sensor => async () => { const { macAddress } = sensor; const sensorInfo = (await BleService().getInfoWithRetries( macAddress, VACCINE_CONSTANTS.MAX_BLUETOOTH_COMMAND_ATTEMPTS )) ?? {}; if (sensorInfo) { // creating a new object to allow mutating. // cannot use spread operator down here const updatedSensor = SensorManager().sensorCreator(sensor); updatedSensor.batteryLevel = parseInt(sensorInfo.batteryLevel, 10); await SensorManager().saveSensor(updatedSensor); } return null; }; const startDownloadAll = () => async (dispatch, getState) => { // Ensure there isn't already a download in progress before starting a new one const state = getState(); const isSyncingTemps = selectIsSyncingTemps(state); if (isSyncingTemps) return null; await PermissionActions.withLocationAndBluetooth(dispatch, getState, downloadAll()); return null; }; export const SensorDownloadActions = { startDownloadAll, startPassiveDownloadJob, };
JavaScript
0
@@ -2151,16 +2151,21 @@ iltered( +%0A 'locatio @@ -2193,17 +2193,41 @@ == true -' + && isPaused == false'%0A );%0A%0A if
f13e4e40d42578be2006c5167b48e19f13ce7c90
Fix typo mistake for user config object
files/api/user/services/jwt.js
files/api/user/services/jwt.js
'use strict'; /** * Module dependencies */ // Public node modules const jwt = require('jsonwebtoken'); /** * Service method to generate a new token based on payload we want to put on it. * * @param {String} payload * * @return {*} */ exports.issue = function (payload) { return jwt.sign( payload, process.env.JWT_SECRET || strapi.api.users.config.jwtSecret || 'oursecret' ); }; /** * Service method to verify that the token we received on a req hasn't be tampered with. * * @param {String} token Token to validate * * @return {*} */ exports.verify = function (token) { const deferred = Promise.defer(); jwt.verify( token, process.env.JWT_SECRET || strapi.api.users.config.jwtSecret || 'oursecret', {}, function (err, user) { if (err || !user || !user.id) { return deferred.reject(err); } deferred.resolve(user); } ); return deferred.promise; }; /** * Service method to get current user token. Note that this will also verify actual token value. * * @param {Object} ctx Context * @param {Boolean} throwError Throw error from invalid token specification * * @return {*} */ exports.getToken = function *(ctx, throwError) { const params = _.assign({}, ctx.request.body, ctx.request.query); let token = ''; // Yeah we got required 'authorization' header. if (ctx.request && ctx.request.header && ctx.request.header.authorization) { const parts = ctx.request.header.authorization.split(' '); if (parts.length === 2) { const scheme = parts[0]; const credentials = parts[1]; if (/^Bearer$/i.test(scheme)) { token = credentials; } } else if (throwError) { throw new Error('Invalid authorization header format. Format is Authorization: Bearer [token]'); } } else if (params.token) { token = params.token; } else if (throwError) { throw new Error('No authorization header was found'); } return exports.verify(token); };
JavaScript
0.000182
@@ -350,33 +350,32 @@ strapi.api.user -s .config.jwtSecre @@ -712,17 +712,16 @@ api.user -s .config.
700a932f05e901d53915da5ced17d2cbb588c299
Update all batching token placeholder
examples/all_batching.js
examples/all_batching.js
/* * Copyright 2015 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * This example shows how to batch events with the * SplunkLogger with all available settings: * batchInterval, maxBatchCount, & maxBatchSize. */ // Change to require("splunk-logging").Logger; var SplunkLogger = require("../index").Logger; /** * Only the token property is required. * * Here, batchInterval is set to flush every 1 second, when * 10 events are queued, or when the size of queued events totals * more than 1kb. */ var config = { token: "your-token", url: "https://localhost:8088", batchInterval: 1000, maxBatchCount: 10, maxBatchSize: 1024 // 1kb }; // Create a new logger var Logger = new SplunkLogger(config); Logger.error = function(err, context) { // Handle errors here console.log("error", err, "context", context); }; // Define the payload to send to Splunk's Event Collector var payload = { // Message can be anything, doesn't have to be an object message: { temperature: "70F", chickenCount: 500 }, // Metadata is optional metadata: { source: "chicken coop", sourcetype: "httpevent", index: "main", host: "farm.local", }, // Severity is also optional severity: "info" }; console.log("Queuing payload", payload); // Don't need a callback here Logger.send(payload); var payload2 = { message: { temperature: "75F", chickenCount: 600, note: "New chickens have arrived" }, metadata: payload.metadata }; console.log("Queuing second payload", payload2); // Don't need a callback here Logger.send(payload2); /** * Since we've configured batching, we don't need * to do anything at this point. Events will * will be sent to Splunk automatically based * on the batching settings above. */ // Kill the process setTimeout(function() { console.log("Events should be in Splunk! Exiting..."); process.exit(); }, 2000);
JavaScript
0
@@ -1072,16 +1072,21 @@ ur-token +-here %22,%0A u
4e729898c234339a9256eb890533cf80d26cf439
Add clickable `localhost` link (#28)
examples/basic/server.js
examples/basic/server.js
var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var config = require('./webpack.config'); new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, historyApiFallback: true, stats: { colors: true } }).listen(3000, 'localhost', function (err) { if (err) { console.log(err); } console.log('Listening at localhost:3000'); });
JavaScript
0
@@ -385,16 +385,23 @@ ning at +http:// localhos
004f0dd6d0286893a4f12ed75beb0df9f45e6f01
add seenBy column to message model
server/models/message.js
server/models/message.js
'use strict'; module.exports = (sequelize, DataTypes) => { const Message = sequelize.define('Message', { id: { allowNull: false, primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, sentBy: { type: DataTypes.STRING, allowNull: false, validate: { len: { args: [1, 100], msg: 'Name of sender must have one or more characters' } } }, senderId: { type: DataTypes.UUID, allowNull: false }, priority: { type: DataTypes.TEXT, allowNull: false, validate: { isIn: { args: [['normal', 'urgent', 'critical']], msg: 'Message priority is either normal, urgent or critical' } } }, body: { type: DataTypes.TEXT, allowNull: false, validate: { len: { args: [1, 100000], msg: 'Body of message must have one or more characters' } } }, isComment: { type: DataTypes.BOOLEAN } }); Message.associate = (models) => { Message.belongsTo(models.Group, { onDelete: 'CASCADE', foreignKey: 'groupId' }); }; return Message; };
JavaScript
0
@@ -443,24 +443,136 @@ %7D%0A %7D,%0A + seenBy: %7B%0A type: DataTypes.ARRAY(DataTypes.JSON),%0A allowNull: true,%0A defaultValue: %5B%5D%0A %7D,%0A senderId
666aa9a0981af80532f66da82d1f735b677f5ce1
add class if iframe has height property
utils/dom-purify/dom-purify.web.js
utils/dom-purify/dom-purify.web.js
var objectAssign = require('object-assign'); var DOMPurify = require('dompurify'); var defaults = { ALLOWED_TAGS: [ 'a', 'b', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'iframe', 'img', 'p', 'small', 'sub', 'sup', 'span' ], RETURN_DOM: true, CUSTOM_CLASSES: { 'a': 'link', 'iframe_container': 'embedded-iframe-container' } }; DOMPurify.addHook('afterSanitizeAttributes', function (node) { // set all elements owning target to target=_blank if ('target' in node) { node.setAttribute('target','_blank'); } // set non-HTML/MathML links to xlink:show=new if (!node.hasAttribute('target') && (node.hasAttribute('xlink:href') || node.hasAttribute('href'))){ node.setAttribute('xlink:show', 'new'); } }); DOMPurify.addHook('afterSanitizeAttributes', function (node, data, config) { if (!config.CUSTOM_CLASSES) return; var className = config.CUSTOM_CLASSES[node.nodeName.toLowerCase()] if (!!className) node.classList.add(className); }); DOMPurify.addHook('afterSanitizeElements', function (node, data, config) { if (node.nodeName.toLowerCase() === 'iframe') { node.width = '100%'; node.style.width = '100%'; } }); function wrapIframes (val, options) { if (!val) return ''; var iframes = val.getElementsByTagName('iframe'); if (iframes.length) { var iframeContainerClass = options.CUSTOM_CLASSES.iframe_container for (var i = 0; i < iframes.length; i++) { if (!iframes[i].parentNode.classList.contains(iframeContainerClass)) { iframes[i].outerHTML = `<div class='${iframeContainerClass}'>${iframes[i].outerHTML}</div>`; } } } return val.innerHTML || ''; } exports.sanitize = function (dirty, config) { var options = objectAssign({}, defaults, config); var val = wrapIframes(DOMPurify.sanitize(dirty, options), options); return val.replace(/&nbsp;/g, ' '); } exports['default'] = DOMPurify;
JavaScript
0.000003
@@ -1494,16 +1494,128 @@ %7B%0A +var iframe = iframes%5Bi%5D;%0A var heightClass = iframe.height %7C%7C iframe.style.height ? 'has-height' : ''%0A if (!ifr @@ -1617,20 +1617,16 @@ (!iframe -s%5Bi%5D .parentN @@ -1683,28 +1683,24 @@ iframe -s%5Bi%5D .outerHTML = @@ -1736,16 +1736,31 @@ erClass%7D + $%7BheightClass%7D '%3E$%7Bifra @@ -1761,20 +1761,16 @@ $%7Biframe -s%5Bi%5D .outerHT @@ -1780,18 +1780,16 @@ %3C/div%3E%60; - %0A %7D
df79e1529b479fc116eacb4511052f8d98d9b4bb
Add login nav functionality to Home
simul/app/components/home.js
simul/app/components/home.js
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, TouchableHighlight, } from 'react-native'; import Search from './search.js' class Home extends Component{ constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli','Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli' ]) }; } _onPressLogin() { } _onPressRegister() { } _onPressStory() { // this.props.navigator.push({ // title: 'Story', // component: Story // }) } featuredStory() { return( <View style={{backgroundColor: 'lightgrey'}}> <Text>"My day today was very interesting. First I woke up late and I couldn't find my clean clothes and my mom......"</Text> <Text style={{color: 'purple', textAlign: 'right'}}>-Ahmed</Text> </View> ) } fetchUserData() { fetch('http:///simulnos.herokuapp.com/api/users').then(function(response){ return response.json() }) } render() { return ( <View style={styles.container}> <Text style={styles.title}>HOME YA</Text> <TouchableHighlight onPress={ () => this._onPressLogin()}><Text style={styles.nav}>Login</Text></TouchableHighlight> <TouchableHighlight onPress={ () => this._onPressRegister()}><Text style={styles.nav}>Register</Text></TouchableHighlight> <Search /> <ListView style={styles.listItems} dataSource={this.state.dataSource} renderRow={(rowData) => <TouchableHighlight onPress={ () => this._onPressStory()}><Text style={ styles.listText}>{rowData}</Text></TouchableHighlight>} renderHeader={ () => this.featuredStory() } /> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#27c2dc', paddingTop: 80, }, title: { flex: .5, backgroundColor: 'white', fontSize: 20, textAlign: 'center', }, listItems: { flex: 9, backgroundColor: 'powderblue', }, listText: { color: '#32161F', textAlign: 'center', }, nav: { flex: .25, alignItems: 'center', color: 'white', fontFamily: 'Farah', backgroundColor: '#FFB30F', textAlign: 'center', } }); module.exports = Home;
JavaScript
0
@@ -165,12 +165,38 @@ arch -.js' +'%0Aimport Login from './login'%0A %0A%0Acl @@ -928,24 +928,108 @@ ssLogin() %7B%0A + this.props.navigator.push(%7B%0A title: 'Login',%0A component: Login%0A %7D)%0A %7D%0A%0A _onPr
e6f438a17e9cf530440cd8f66ff269b126ec1aa8
Add messages model
server/models/message.js
server/models/message.js
export default (connection, Sequelize) => { const Message = connection.define('message', { messageId: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true }, inGroup: { type: Sequelize.UUID, allowNull: false }, author: { type: Sequelize.UUID, allowNull: false }, body: { type: Sequelize.TEXT, allowNull: false, unique: true }, priority: { type: Sequelize.ENUM, values: ['normal', 'urgent', 'critical'], allowNull: false } }, { paranoid: true }); return Message; };
JavaScript
0.000001
@@ -410,28 +410,8 @@ alse -,%0A unique: true %0A
9257014f5aed89a6e36cbcdc105f176c6449351a
Update code style.
base/UI.js
base/UI.js
/* =============================================================================== Class defines UI: HUD (head-up display) with player stats and menu GUI. =============================================================================== */ function UI() { if ( !(this instanceof UI) ) return new UI(); this.camera = new THREE.OrthographicCamera( DOA.Settings.width / -2, DOA.Settings.width / 2, DOA.Settings.height / 2, DOA.Settings.height / -2, DOA.Settings.minView, DOA.Settings.maxView ); /* * If camera rotation on Y is 0, not PI radian, all objects visible by * camera must have negative Z coordinates. In this case, the backside * of the object is visible only, and Material.side should be set to * THREE.DoubleSide, so the object can be drawn. */ this.camera.rotateY( Math.PI ); this.scene = new THREE.Scene(); this.menu = null; } /* ================ init Creates objects of user interface. ================ */ UI.prototype.init = function () { // Interface // Menu this.menu = new dat.GUI(); this.menu.domElement.style.display = 'none'; this.buildSettingsMenu(); }; /* ================ updateSize Updates camera size and projection in accordance with window size. ================ */ UI.prototype.updateSize = function () { this.camera.left = DOA.Settings.width / - 2; this.camera.right = DOA.Settings.width / 2; this.camera.top = DOA.Settings.height / 2; this.camera.bottom = DOA.Settings.height / - 2; this.camera.updateProjectionMatrix(); }; /* ================ updateHudSize Updates HUD elements texture size. ================ */ UI.prototype.updateHud = function () { }; /* ================ clearMenu Removes all elements from the menu recursively. ================ */ UI.prototype.clearMenu = function ( menu ) { menu = menu || this.menu; var k; for ( k in menu.__controllers ) { menu.remove( menu.__controllers[ k ] ); delete menu.__controllers[ k ]; delete menu.__listening[ k ]; } menu.__controllers = []; menu.__listening = []; for ( k in menu.__folders ) { UI.prototype.clearMenu( menu.__folders[ k ] ); menu.__folders[ k ].domElement.parentNode.remove(); delete menu.__folders[ k ]; } }; /* ================ resetMenu Resets menu values to the remembered ones. ================ */ UI.prototype.resetMenu = function () { try { this.menu.revert(); } catch ( ex ) { // Cannot read property 'selectedIndex' of undefined } }; /* ================ buildSettingsMenu Creates new set of controllers, based on DOA.Settings. ================ */ UI.prototype.buildSettingsMenu = function () { this.clearMenu(); var folder = this.menu.addFolder( 'Common' ); folder.add( DOA.Settings, 'fps', [ 30, 60 ] ).name( 'fps counter' ).listen(); folder.addColor( DOA.Settings.colors, 'mesh' ).name( 'blank color' ).listen(); folder.open(); folder = this.menu.addFolder( 'Graphics' ); folder.add( DOA.Settings, 'minView', 0.1, 1.0 ).step( 0.1 ).name( 'min view' ).listen(); folder.add( DOA.Settings, 'maxView', 100, 9000 ).step( 100 ).name( 'max view' ).listen(); folder.add( DOA.Settings, 'fov', 30, 120 ).step( 15 ).name( 'filed of view' ).listen(); folder.add( DOA.Settings, 'anisotropy', 1, 16 ).step( 1 ).name( 'anisotropy' ).listen(); folder.open(); folder = this.menu.addFolder( 'Player' ); folder.add( DOA.Settings, 'mouseSensitivity', 0.05, 0.5 ).step( 0.05 ).name( 'mouse speed' ).listen(); folder.add( DOA.Settings, 'hudSize', { normal : 32, big : 64, large : 128 } ).name( 'HUD size' ).listen(); folder.add( DOA.Settings, 'hudOpacity', 0.0, 1.0 ).step( 0.01 ).name( 'HUD opacity' ).listen(); folder.open(); this.menu.add( DOA.UI, 'resetMenu' ).name( 'Reset' ); this.menu.add( DOA.Settings, 'quickSave' ).name( 'Save' ); this.menu.add( DOA.Settings, 'quickLoad' ).name( 'Load' ); }; /* --------------------------------------------------------------------------- DOA --------------------------------------------------------------------------- */ DOA.UI = new UI();
JavaScript
0.000004
@@ -1456,25 +1456,24 @@ s.width / - - 2;%0A this. @@ -1509,17 +1509,16 @@ width / - 2;%0A @@ -1562,17 +1562,16 @@ ight / - 2;%0A t @@ -1613,17 +1613,16 @@ ight / - - 2;%0A t
7b96e4a7e51db89549edc230c7946ec4fec48850
Update the build process to build assets in the correct path.
Gulpfile.js
Gulpfile.js
/** * Created by Marian on 09/12/2015. */ var paths = { tmp: './tmp', src: './app', pub: './public' }; var gulp = require('gulp'); var jade = require('gulp-jade'); var data = require('gulp-data'); var debug = require('gulp-debug'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var rev = require('gulp-rev'); var clean = require('gulp-clean'); var inject = require('gulp-inject'); var sourcemaps = require('gulp-sourcemaps'); var plumber = require('gulp-plumber'); var autoprefixer = require('gulp-autoprefixer'); var htmlMin = require('gulp-html-minifier'); var sassdoc = require('sassdoc'); var autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] }; var sassOptions = { dev : { errLogToConsole: true, outputStyle : 'expanded' }, prod: { outputStyle: 'compressed' } }; function browserSyncInit(baseDir, files) { browserSync.instances = browserSync.init(files, { startPath: '/', server : { baseDir } }); } gulp.task('clean:tmp', function () { return gulp .src([ paths.tmp + '/**/*.css', paths.tmp + '/**/*.html' ]) .pipe(clean()); }); gulp.task('assets', function () { gulp.src(paths.src + '/assets/fonts/**/*') .pipe(gulp.dest(paths.tmp + '/fonts')); }); gulp.task('index', ['clean:tmp', 'assets', 'sass:dev'], function () { // return gulp.src(paths.src + '/index.html') return gulp.src(paths.src + '/*.jade') .pipe(data((file) => require('./app/data/cv.json'))) .pipe(jade({ pretty: true })) .pipe(inject( gulp.src(paths.tmp + '/stylesheets/**/*.css', { read: false }).pipe(debug()), { relative : false, addRootSlash: true } )) .pipe(gulp.dest(paths.tmp)); }); gulp.task('serve', ['index'], function () { // Initialize browser sync server browserSyncInit([ paths.tmp ]); // Watch for sass gulp.watch([paths.src + '/**/*.scss', paths.src + '/**/_*.scss'], ['sass:dev']); // // // Watch for HTML // gulp.watch(paths.src + '/**/*.html', ['index']); gulp.watch(paths.src + '/**/*.jade', ['index']).on('change', function(event) { console.log('File src' + event.path + ' was ' + event.type + ', running tasks...'); browserSync.reload; }); gulp.watch(paths.tmp + '/index.html').on('change', function(event) { console.log('File tmp' + event.path + ' was ' + event.type + ', running tasks...'); browserSync.reload; }); }); gulp.task('sass:dev', function () { return gulp // Find all `.scss` files from the `stylesheets/` folder .src(paths.src + '/stylesheets/**/*.scss') .pipe(plumber()) // Run Sass on those files .pipe(sass(sassOptions.dev).on('error', sass.logError)) .pipe(sourcemaps.write(paths.tmp + '/stylesheets/maps')) // Write the resulting CSS in the output folder .pipe(gulp.dest(paths.tmp + '/stylesheets')) .pipe(browserSync.stream()) }); gulp.task('sass:prod', function () { return gulp // Find all `.scss` files from the `stylesheets/` folder .src(paths.src + '/stylesheets/**/*.scss') .pipe(plumber()) // Run Sass on those files .pipe(sass(sassOptions.prod).on('error', sass.logError)) .pipe(sourcemaps.write(paths.pub + '/stylesheets/maps')) .pipe(autoprefixer(autoprefixerOptions)) // Write the resulting CSS in the output folder .pipe(gulp.dest(paths.pub + '/stylesheets')); }); gulp.task('minify', ['assets', 'sass:prod'], function () { // gulp.src(paths.src + '/**/*.html') gulp.src(paths.src + '/**/*.jade') .pipe(data((file) => require('./app/data/cv.json'))) .pipe(jade()) .pipe(inject( gulp.src(paths.pub + '/**/*.css', { read: false }), { relative : false, addRootSlash: true, transform : function (filepath, file, i, length) { var regexp = new RegExp(paths.pub.slice(1)) filepath = filepath.replace(regexp, ''); return `<link rel="stylesheet" href="${filepath}">`; } } )) .pipe(htmlMin({ collapseWhitespace: true })) .pipe(gulp.dest(paths.pub)) }); gulp.task('prod', ['minify'], function () { }); gulp.task('default', ['serve']);
JavaScript
0
@@ -1326,16 +1326,20 @@ ('assets +:dev ', funct @@ -1343,24 +1343,24 @@ nction () %7B%0A - gulp.src @@ -1439,32 +1439,172 @@ /fonts'));%0A%7D);%0A%0A +gulp.task('assets:build', function () %7B%0A gulp.src(paths.src + '/assets/fonts/**/*')%0A .pipe(gulp.dest(paths.pub + '/fonts'));%0A%7D);%0A%0A gulp.task('index @@ -1623,24 +1623,28 @@ mp', 'assets +:dev ', 'sass:dev @@ -3939,16 +3939,22 @@ %5B'assets +:build ', 'sass
2030b2c8405b1c011ef09e3c4386486f91121917
Fix z-index issue (#53)
simulator/js/ToolBarGroup.js
simulator/js/ToolBarGroup.js
var ToolTypeEnum = { RADIO: 1, RADIOLIST: 2, BUTTON: 3, CHECK: 4, SLIDE: 5, HELP: 6 }; Object.freeze(ToolTypeEnum); class ToolBarItem { /** * Create a ToolBarItem that can be any type listed in ToolTypeEnum. * @param {string|String[]} name * @param {string} id * @param {string} img popover image. * @param {number|ToolTypeEnum} type any type listed in ToolTypeEnum. * @param {ToolBarItem[]|undefined} content the list of items in RADIOLIST. * @param {function|undefined} action the action that triggers on BUTTON click. * @param {number|undefined} min the minimum value in SLIDE. * @param {number|undefined} max the maximum value in SLIDE. * @param {number|undefined} step the step size in SLIDE. * @param {number|undefined} value the current value in SLIDE. */ constructor(name, id, img, type, content, action, min, max, step, value) { this.name = name; this.id = id; this.img = img; //@param {string|number} description popover description or z-index for RADIOLIST. this.description = "";//description; //Warning: Dirty code below. if (this.name == "Mirrors") this.description = 4; else if (this.name == "Glasses") this.description = 3; else if (this.name == "Point Source") this.description = 6; else if (this.name == "Blockers") this.description = 7; else if (this.name == "Samples") this.description = 5; else this.description = getMsg(this.id + "_popover"); this.type = type; this.selected = ""; this.content = content; if (this.type == ToolTypeEnum.RADIOLIST) { for (var i = 0; i < content.length; i++) { this.selected = ko.observable(content[i].name); break; } } else if (this.type == ToolTypeEnum.CHECK) { this.selected = ko.observable(false); } else if (this.type == ToolTypeEnum.BUTTON) { this.action = action; } else if (this.type == ToolTypeEnum.SLIDE) { this.min = ko.observable(min); this.max = ko.observable(max); this.step = ko.observable(step); this.value = ko.observable(value); } else if (this.type == ToolTypeEnum.HELP) { this.selected = ko.observable(true); } //console.log(this); } getTitle() { return "<b>" + this.getLocaleName() + "</b>"; } getLocaleName() { return getMsg(this.id); } getContent() { var image = ""; if (this.img != undefined) image = "<img src='../img/" + this.img + ".svg' align='left' style='margin-right: 10px; margin-bottom: 4px; max-width: 250px'>"; return image + "<b>" + this.description + "</b>"; } } class ToolBarGroup { /** * Creates a ToolBarGroup that results in a new toolgroup row in toolbar. * @param {string} title * @param {ToolBarItem[]} tools * @constructor */ constructor(title, tools) { this.title = title; this.tools = tools; for (var i = 0; i < tools.length; i++) { this.selected = ko.observable(tools[i].name); break; } } getLocaleName() { return getMsg(this.title); } }
JavaScript
0
@@ -1084,38 +1084,1229 @@ // -Warning: Dirty code below.%0A + Currently, a hack is used to make the RADIOLIST dropdown menu appear%0A // above other toolbar buttons. This hack requires setting the%0A // %60description%60 of the RADIOLIST to represent its z-index. This%0A // value should monotonically decrease for each RADIOLIST%0A // (from left to right, top to bottom).%0A //%0A // This works because a higher z-index button will always appear above a%0A // lower z-index one, and a button will never be covered by a dropdown menu%0A // of another RADIOLIST button at its right or below it. Therefore, the%0A // z-index of a button must be higher than all buttons at its right or%0A // below.%0A //%0A // The current approach is far from ideal. A better approach is to make%0A // the buttons in the dropdown menu to have higher z-indices than normal%0A // buttons. However, this is currently not possible due to unknown reasons.%0A //%0A // TL;DR: For each RADIOLIST button, its %60description%60 must be set to a%0A // value higher than all RADIOLIST buttons at its right or below.%0A // This value should be updated whenever a new RADIOLIST button is%0A // added or reordered.%0A if (this.name == %22Glasses%22)%0A this.description = 3;%0A else if @@ -2377,38 +2377,39 @@ (this.name == %22 -Glasse +Blocker s%22)%0A this.d @@ -2413,33 +2413,33 @@ s.description = -3 +5 ;%0A else if (t @@ -2498,74 +2498,8 @@ 6;%0A - else if (this.name == %22Blockers%22)%0A this.description = 7;%0A @@ -2548,33 +2548,33 @@ s.description = -5 +7 ;%0A else%0A
83e991339ed3ca179f7e38fcc6ff4d35cf97ecef
Fix remove bit length select for ECC algo and GnuPG usage
src/app/keyring/components/AdvKeyGenOptions.js
src/app/keyring/components/AdvKeyGenOptions.js
/** * Copyright (C) 2016 Mailvelope GmbH * Licensed under the GNU Affero General Public License version 3 */ import React from 'react'; import PropTypes from 'prop-types'; import * as l10n from '../../../lib/l10n'; import moment from 'moment'; import {KeyringOptions} from '../KeyringOptions'; import DatePicker from './DatePicker'; l10n.register([ 'keygrid_algorithm', 'keygrid_default_label', 'key_gen_key_size', 'key_gen_experimental', 'key_gen_expiration', 'key_gen_future_default', 'keygrid_key_not_expire' ]); export default function AdvKeyGenOptions({value: {keyAlgo, keySize, keyExpirationTime}, onChange, disabled}) { const handleDateChange = moment => onChange({target: {id: 'keyExpirationTime', value: moment}}); const keyAlgos = [ <option value="rsa" key={0}>RSA</option>, <option value="ecc" key={1}>{`ECC - Curve25519 (${l10n.map.key_gen_experimental})`}</option> ]; const gpgKeyAlgos = [ <option value="default" key={0}>{l10n.map.keygrid_default_label}</option>, <option value="future-default" key={1}>{`${l10n.map.key_gen_future_default} (${l10n.map.key_gen_experimental})`}</option> ]; return ( <div className="adv-key-gen-options"> <div className="form-group"> <label htmlFor="keyAlgo">{l10n.map.keygrid_algorithm}</label> <select id="keyAlgo" value={keyAlgo} onChange={onChange} className="custom-select" disabled={disabled}> <KeyringOptions.Consumer> {options => options.gnupg ? gpgKeyAlgos : keyAlgos} </KeyringOptions.Consumer> </select> </div> <div className={`form-group ${keyAlgo === 'rsa' ? '' : 'hide'}`}> <label htmlFor="keySize"><span htmlFor="keySize">{l10n.map.key_gen_key_size}</span>&nbsp;(<span>Bit</span>)</label> <select id="keySize" value={keySize} onChange={onChange} className="custom-select" disabled={disabled}> <option value="2048">2048 Bit</option> <option value="4096">4096 Bit</option> </select> </div> <div className="form-group key-expiration-group"> <label htmlFor="keyExpirationTime">{l10n.map.key_gen_expiration}</label> <DatePicker id="keyExpirationTime" value={keyExpirationTime} onChange={handleDateChange} placeholder={l10n.map.keygrid_key_not_expire} minDate={moment().add({days: 1})} maxDate={moment('2080-12-31')} disabled={disabled} /> </div> </div> ); } AdvKeyGenOptions.propTypes = { value: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, disabled: PropTypes.bool };
JavaScript
0
@@ -640,16 +640,68 @@ led%7D) %7B%0A + const context = React.useContext(KeyringOptions);%0A const @@ -1478,65 +1478,16 @@ -%3CKeyringOptions.Consumer%3E%0A %7Boptions =%3E options +%7Bcontext .gnu @@ -1519,45 +1519,8 @@ os%7D%0A - %3C/KeyringOptions.Consumer%3E%0A @@ -1582,16 +1582,17 @@ group $%7B +( keyAlgo @@ -1600,16 +1600,35 @@ == 'rsa' + && !context.gnupg) ? '' : @@ -1632,11 +1632,13 @@ : ' -hid +d-non e'%7D%60
200cc21b91ae8348268c666d1c71306f6415c9da
drop debug statement
dnt/dnt.js
dnt/dnt.js
/*jslint white:true */ /*global chrome */ (function ( http ) { 'use strict'; var dnt_header = { name: 'DNT', value: '1' }, filter = { urls: [ '<all_urls>' ] }, info = [ 'requestHeaders', 'blocking' ]; function doNotTrack( r ) { console.log( r ); r.requestHeaders.push( dnt_header ); return { requestHeaders: r.requestHeaders }; } http.onBeforeSendHeaders.addListener( doNotTrack, filter, info ); }( chrome.webRequest ));
JavaScript
0.000001
@@ -1,8 +1,327 @@ +// ____ __ __ ______ %0A// /%5C _%60%5C /%5C %5C/%5C %5C/%5C__ _%5C %0A// %5C %5C %5C/%5C %5C %5C %60%5C%5C %5C/_/%5C %5C/ %0A// %5C %5C %5C %5C %5C %5C , %60 %5C %5C %5C %5C %0A// %5C %5C %5C_%5C %5C %5C %5C%60%5C %5C %5C %5C %5C %0A// %5C %5C____/%5C %5C_%5C %5C_%5C %5C %5C_%5C%0A// %5C/___/ %5C/_/%5C/_/ %5C/_/%0A//%0A// DNT :: Do Not Track Extension for Chrome%0A// Copyright (c) 2012 Ori Livneh. BSD License.%0A%0A /*jslint @@ -335,16 +335,16 @@ true */%0A - /*global @@ -541,16 +541,16 @@ ng' %5D;%0A%0A + func @@ -576,34 +576,8 @@ ) %7B%0A - console.log( r );%0A
b2cacec4919cf60436ba5ba1108c8bd1b6802cd2
Update comment_admin.js
modules/comment/tpl/js/comment_admin.js
modules/comment/tpl/js/comment_admin.js
function doCancelDeclare() { var comment_srl = new Array(); jQuery('#fo_list input[name=cart]:checked').each(function() { comment_srl[comment_srl.length] = jQuery(this).val(); }); if(comment_srl.length<1) return; var params = new Array(); params['comment_srl'] = comment_srl.join(','); exec_xml('comment','procCommentAdminCancelDeclare', params, function() { location.reload(); }); } function insertSelectedModule(id, module_srl, mid, browser_title) { location.href = current_url.setQuery('module_srl',module_srl); } function completeAddCart(ret_obj, response_tags) { } function getCommentList() { var commentListTable = jQuery('#commentListTable'); var cartList = []; commentListTable.find(':checkbox[name=cart]').each(function(){ if(this.checked) cartList.push(this.value); }); var params = new Array(); var response_tags = ['error','message', 'comment_list']; params["comment_srls"] = cartList.join(","); exec_xml('comment','procCommentGetList',params, completeGetCommentList, response_tags); } function completeGetCommentList(ret_obj, response_tags) { var htmlListBuffer = ''; var statusNameList = {"N":"Public", "Y":"Secret"}; var publishedStatusList = {0:'Unpublished', 1:'Published'}; if(ret_obj['comment_list'] == null) { htmlListBuffer = '<tr>' + '<td colspan="4" style="text-align:center">'+ret_obj['message']+'</td>' + '</tr>'; } else { var comment_list = ret_obj['comment_list']['item']; if(!jQuery.isArray(comment_list)) comment_list = [comment_list]; for(var x in comment_list) { var objComment = comment_list[x]; htmlListBuffer += '<tr>' + '<td class="title">'+ objComment.content +'</td>' + '<td class="nowr">'+ objComment.nick_name +'</td>' + '<td class="nowr">'+ statusNameList[objComment.is_secret] +'</td>' + '<td>'+ publishedStatusList[objComment.status] + '<input type="hidden" name="cart[]" value="'+objComment.comment_srl+'" />' + '</td>' + '</tr>'; } jQuery('#selectedCommentCount').html(comment_list.length); } jQuery('#commentManageListTable>tbody').html(htmlListBuffer); } function doChangePublishedStatus(new_status) { container_div = jQuery("#listManager"); var act = container_div.find("input[name=act]"); var will_publish = container_div.find("input[name=will_publish]"); var action = "procCommentAdminChangePublishedStatusChecked"; will_publish.val(new_status); act.val(action); } function checkSearch(form) { if(form.search_target.value == '') { alert(xe.lang.msg_empty_search_target); return false; } /* if(form.search_keyword.value == '') { alert(xe.lang.msg_empty_search_keyword); return false; } */ }
JavaScript
0.000001
@@ -90,20 +90,24 @@ ut%5Bname= +%22 cart +%5B%5D%22 %5D:checke
69fea5c1f020484fffc669abcedbcaae927b735e
remove todo tag
scaffold/gulp/gulpfile.js
scaffold/gulp/gulpfile.js
var gulp = require('gulp'), fs = require("fs"), file = require('gulp-file'), runSequence = require('run-sequence'), replace = require('gulp-replace'), babel = require('gulp-babel'), bc=require('babel-core'); var componentFileArr=[]; gulp.task('readFile',function(callback) { walk("src/component", function (path) { var ext = getFileExt(path); // if (ext === ".html" || ext === ".css") { componentFileArr.push(path); // } }, function () { var map=arrToObj(componentFileArr); console.log(map) for(var key in map){ var paths=map[key]; var i= 0,len=paths.length; var contentArr=[]; for(;i<len;i++){ var path=paths[i]; if(getFileExt(path)===".js")continue; contentArr.push(fileContentToStr(fs.readFileSync(path, "utf8"),getFileExt(path)===".html",path)); } contentArr.push( bc.transform(fs.readFileSync("src/component/"+key+"/index.js", "utf8"), { presets: ['es2015'] }) .code); file(key+".js", contentArr.join("") , { src: true }) .pipe(gulp.dest('dev/component')) } callback(); }) }) gulp.task('copyHTML', function () { return gulp.src('src/*.html') .pipe(replace(/<script src="component\/(.*?)\/index.js"><\/script>/gm ,function(a,b,c){ return '<script src="component\/'+b+'.js"><\/script>'; })) .pipe(gulp.dest('dev')); }); gulp.task('copyJS', function () { return gulp.src('src/js/*js').pipe(babel({ presets: ['es2015'] })).pipe(gulp.dest('dev/js')); }); gulp.task('fixUtil', function () { return gulp.src('fix/util.js').pipe(gulp.dest('dev/js')); }); //http://www.tuicool.com/articles/rQvUbu2 gulp.task('default', function (taskDone) { runSequence( 'readFile', 'copyHTML', 'copyJS', 'fixUtil', taskDone ); }); function arrToObj(arr){ var obj={}; for(var i= 0,len=arr.length;i<len;i++){ var item=arr[i]; var key=item.split("/")[2]; if(!obj[key]){ obj[key]=[]; } obj[key].push(item); } return obj; } function getFileExt(filename) { var index1 = filename.lastIndexOf(".") var index2 = filename.length; return filename.substring(index1, index2).toLowerCase(); } function fileContentToStr(r ,isTpl ,path) { var strVar =isTpl? "tpl":"css"; var g = ""; var arr = r.replace(/\r/g,"").split("\n"); g += "App.componentRes['"+path.substring(4,path.length)+"'] =\n"; var i = 0; for (; i < arr.length; i++) { var l = ''; if (i === 0) { l += "'" } ; if (i === arr.length - 1) { l += arr[i] + "';\n\n"; } else { l += arr[i] + "\\\n"; } g += l; } return g; } function walk (path, handleFile, callback) { var len = 1, // 文件|目录数,起始一个 floor = 0; // 第x个目录? function done () { // 完成任务, 运行回调函数 if (--len === 0) { callback(); } } function composeErr (err) { // 错误处理 console.log('stat error'); done(); // 以错误内容完成 } function composeDir (path) { // 目录处理 floor++; fs.readdir(path, function (err, files) { if (err) { console.log('read dir error'); done(); // 目录完成 return; } len += files.length; // 子文件|子目录计数 files.forEach(function (filename) { compose(path + '/' + filename); // 子内容新的操作 }); done(); // 目录完成 }); } function composeFile (path) { // 文件处理 handleFile(path, floor); done(); // 文件完成 } function compose (path) { //同步 fs.stat(path, function (err, stats) { if (err) { composeErr(err); return; } if (stats.isDirectory()) { composeDir(path); return; } composeFile(path); }); } compose(path); } //todo es6转换
JavaScript
0.000001
@@ -4242,18 +4242,4 @@ );%0A%7D -%0A%0A//todo es6%E8%BD%AC%E6%8D%A2
bc74c89e7600430d6f00c36b4cb72d73935ffd4c
Update excerpt helper to properly filter HTML footnotes
core/server/helpers/excerpt.js
core/server/helpers/excerpt.js
// # Excerpt Helper // Usage: `{{excerpt}}`, `{{excerpt words="50"}}`, `{{excerpt characters="256"}}` // // Attempts to remove all HTML from the string, and then shortens the result according to the provided option. // // Defaults to words="50" var hbs = require('express-hbs'), _ = require('lodash'), downsize = require('downsize'), excerpt; excerpt = function (options) { var truncateOptions = (options || {}).hash || {}, excerpt; truncateOptions = _.pick(truncateOptions, ['words', 'characters']); _.keys(truncateOptions).map(function (key) { truncateOptions[key] = parseInt(truncateOptions[key], 10); }); /*jslint regexp:true */ excerpt = String(this.html); // Strip inline and bottom footnotes excerpt = excerpt.replace(/<a.*?rel="footnote">.*?<\/a>/gi, ''); excerpt = excerpt.replace(/<div class="footnotes"><ol>.*?<\/ol><\/div>/, ''); // Strip other html excerpt = excerpt.replace(/<\/?[^>]+>/gi, ''); excerpt = excerpt.replace(/(\r\n|\n|\r)+/gm, ' '); /*jslint regexp:false */ if (!truncateOptions.words && !truncateOptions.characters) { truncateOptions.words = 50; } return new hbs.handlebars.SafeString( downsize(excerpt, truncateOptions) ); }; module.exports = excerpt;
JavaScript
0.000001
@@ -818,16 +818,26 @@ lace(/%3Ca + href=%22#fn .*?rel=%22
015c8807bac4db359950dd13298cc925e69699f1
Fix CSV format
bin/cli.js
bin/cli.js
#!/usr/bin/env node 'use strict'; var path = require('path'); var jade = require('jade'); var Table = require('cli-table'); var numeral = require('numeral'); var program = require('commander'); var json2csv = require('json2csv'); var _ = require('underscore'); _.str = require('underscore.string'); _.mixin(_.str.exports()); _.str.include('Underscore.string', 'string'); var StyleStats = require('../lib/stylestats'); /** * Prettify StyleStats data. * @param {object} [result] StyleStats parse data. Required. * @return {array} prettified data. */ function prettify(result) { var collections = []; Object.keys(result).forEach(function(key) { var stats = {}; var prop = _(_(key).humanize()).titleize(); if (key === 'propertiesCount') { var array = []; result[key].forEach(function(item) { array.push([item.property, item.count]); }); stats[prop] = array.join('\n').replace(/\,/g, ': '); } else if (key === 'size' || key === 'gzippedSize' || key === 'dataUriSize') { stats[prop] = numeral(result[key]).format('0.0b').replace(/\.0B/, 'B').replace(/0\.0/, '0'); } else if (key === 'simplicity' || key === 'ratioOfDataUriSize') { stats[prop] = numeral(result[key]).format('0.00%'); } else if (key === 'published' || key === 'paths') { return true; } else { stats[prop] = Array.isArray(result[key]) ? result[key].join('\n') : result[key]; if (stats[prop] === '') { stats[prop] = 'N/A'; } } collections.push(stats); }); return collections; } program .version(require('../package.json').version) .usage('[options] <file ...>') .option('-c, --config [path]', 'Path and name of the incoming JSON file.') .option('-t, --type [format]', 'Specify the output format. <json|html|csv>') .option('-s, --simple', 'Show compact style\'s log.') .parse(process.argv); if (!program.args.length) { console.log('\n No input file specified.'); program.help(); } var stats = new StyleStats(program.args, program.config); stats.parse(function(result) { switch (program.type) { case 'json': var json = JSON.stringify(result, null, 2); console.log(json); break; case 'csv': json2csv({ data: result, fields: Object.keys(result) }, function(err, csv) { console.log(csv); }); break; case 'html': var template = path.join(__dirname, '../assets/stats.jade'); var html = jade.renderFile(template, { pretty: true, stats: prettify(result), published: result.published, paths: result.paths }); console.log(html); break; default: var table = new Table({ style: { head: ['cyan'], compact: program.simple } }); prettify(result).forEach(function(data) { table.push(data); }); console.log(' StyleStats!\n' + table.toString()); break; } });
JavaScript
0.999994
@@ -2378,16 +2378,184 @@ 'csv':%0A + Object.keys(result).forEach(function(key) %7B%0A result%5Bkey%5D = Array.isArray(result%5Bkey%5D) ? result%5Bkey%5D.join(' ') : result%5Bkey%5D;%0A %7D);%0A
ac6c0b44dec5a286d2ea79d77ad4a2e2365fab56
Fix loading with global "define" set to null
build/wrapper.template.js
build/wrapper.template.js
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ (function() { // This is "window" in browsers and "global" in nodejs. // See https://github.com/google/shaka-player/issues/1445 var innerGlobal = typeof window != 'undefined' ? window : global; // This is where our library exports things to. It is "this" in the wrapped // code. With this, we can decide later what module loader we are in, if any, // and put these exports in the appropriate place for that loader. var exportTo = {}; // According to the Closure team, their polyfills will be written to // $jscomp.global, which will be "window", or "global", or "this", depending // on circumstances. // See https://github.com/google/closure-compiler/issues/2957 and // https://github.com/google/shaka-player/issues/1455#issuecomment-393250035 // We provide "global" for use by Closure, and "window" for use by the Shaka // library itself. Both point to "innerGlobal" above. // We also provide "module", which is always undefined, to prevent compiled-in // code from doing its own exports that conflict with ours. (function(window, global, module) { %output% }).call(/* this= */ exportTo, /* window= */ innerGlobal, /* global= */ innerGlobal, /* module= */ undefined); if (typeof exports != 'undefined') { // CommonJS module loader. Use "exports" instead of "module.exports" to // avoid triggering inappropriately in Electron. for (var k in exportTo.shaka) { exports[k] = exportTo.shaka[k]; } } else if (typeof define != 'undefined' && define.amd) { // AMD module loader. define(function(){ return exportTo.shaka; }); } else { // Loaded as an ES module or directly in a <script> tag. // Export directly to the global scope. innerGlobal.shaka = exportTo.shaka; } })();
JavaScript
0.000014
@@ -1615,29 +1615,28 @@ define -! += = ' +f un -defined +ction ' && def
7597f2c653b077e8696bb200ac29f6f35dd382ab
Comment test on vuejsdialog with vue3
resources/js/app.js
resources/js/app.js
import { createApp, defineAsyncComponent } from 'vue'; import '@fontsource/kreon'; const app = createApp({ mounted: function() { document.body.classList.add('cssLoading'); setTimeout(() => document.body.classList.remove('cssLoading'), 0); }, components: { PageRandom: defineAsyncComponent(() => import('./components/pageRandom.vue')), Pending: defineAsyncComponent(() => import('./components/pending.vue')), OrganizerForm: defineAsyncComponent(() => import('./components/organizer/form.vue')), DearSantaForm: defineAsyncComponent(() => import('./components/dearSantaForm.vue')), Dashboard: defineAsyncComponent(() => import('./components/dashboard.vue')), Faq: defineAsyncComponent(() => import('./components/faq.vue')), VueFetcher: defineAsyncComponent(() => import('./components/vueFetcher.vue')) } }); app.mount('#main'); const lang = document.documentElement.lang.substr(0, 2); import Locale from './vue-i18n-locales.generated.js'; import { createI18n } from 'vue-i18n'; const i18n = createI18n({ locale: lang, messages: Locale, globalInjection: true }); app.use(i18n); import VuejsDialog from 'vuejs-dialog'; app.use(VueJsDialog);
JavaScript
0
@@ -1173,16 +1173,18 @@ i18n);%0A%0A +// import V @@ -1215,16 +1215,18 @@ ialog';%0A +// app.use(
d4e433d79d650b623a42909a20b9761e43a1f537
Fix Gulpfile
Gulpfile.js
Gulpfile.js
var gulp = require('gulp'); var gulpif = require('gulp-if'); var uglify = require('gulp-uglify'); var uglifycss = require('gulp-uglifycss'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var debug = require('gulp-debug'); var livereload = require('gulp-livereload'); var order = require('gulp-order'); var merge = require('merge-stream'); var env = process.env.GULP_ENV; var rootPath = 'web/assets/'; var adminRootPath = rootPath + 'admin/'; var shopRootPath = rootPath + 'shop/'; var paths = { admin: { js: [ 'node_modules/jquery/dist/jquery.min.js', 'node_modules/semantic-ui-css/semantic.min.js', 'vendor/sylius/sylius/src/Sylius/Bundle/AdminBundle/Resources/private/js/**', 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**', 'vendor/sylius/sylius/src/Sylius/Bundle/ShippingBundle/Resources/public/js/**', 'vendor/sylius/sylius/src/Sylius/Bundle/PromotionBundle/Resources/public/js/sylius-promotion.js', 'vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/Resources/public/js/sylius-user.js' ], sass: [ 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**', ], css: [ 'node_modules/semantic-ui-css/semantic.min.css', ], img: [ 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**', ] }, shop: { js: [ 'node_modules/jquery/dist/jquery.min.js', 'node_modules/semantic-ui-css/semantic.min.js', 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**', 'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/js/**' ], sass: [ 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**', ], css: [ 'node_modules/semantic-ui-css/semantic.min.css', ], img: [ 'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**', ] } }; gulp.task('admin-js', function () { return gulp.src(paths.admin.js) .pipe(concat('app.js')) .pipe(gulpif(env === 'prod', uglify)) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(adminRootPath + 'js/')) ; }); gulp.task('admin-css', function() { gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(adminRootPath + 'css/themes/')); var cssStream = gulp.src(paths.admin.css) .pipe(concat('css-files.css')) ; var sassStream = gulp.src(paths.admin.sass) .pipe(sass()) .pipe(concat('sass-files.scss')) ; return merge(cssStream, sassStream) .pipe(order(['css-files.css', 'sass-files.scss'])) .pipe(concat('style.css')) .pipe(gulpif(env === 'prod', uglifycss)) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(adminRootPath + 'css/')) .pipe(livereload()) ; }); gulp.task('admin-img', function() { return gulp.src(paths.admin.img) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(adminRootPath + 'img/')) ; }); gulp.task('admin-watch', function() { livereload.listen(); gulp.watch(paths.admin.js, ['admin-js']); gulp.watch(paths.admin.sass, ['admin-css']); gulp.watch(paths.admin.css, ['admin-css']); gulp.watch(paths.admin.img, ['admin-img']); }); gulp.task('shop-js', function () { return gulp.src(paths.shop.js) .pipe(concat('app.js')) .pipe(gulpif(env === 'prod', uglify)) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(shopRootPath + 'js/')) ; }); gulp.task('shop-css', function() { gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(shopRootPath + 'css/themes/')); var cssStream = gulp.src(paths.shop.css) .pipe(concat('css-files.css')) ; var sassStream = gulp.src(paths.shop.sass) .pipe(sass()) .pipe(concat('sass-files.scss')) ; return merge(cssStream, sassStream) .pipe(order(['css-files.css', 'sass-files.scss'])) .pipe(concat('style.css')) .pipe(gulpif(env === 'prod', uglifycss)) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(shopRootPath + 'css/')) .pipe(livereload()) ; }); gulp.task('shop-img', function() { return gulp.src(paths.shop.img) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(shopRootPath + 'img/')) ; }); gulp.task('shop-watch', function() { livereload.listen(); gulp.watch(paths.shop.js, ['shop-js']); gulp.watch(paths.shop.sass, ['shop-css']); gulp.watch(paths.shop.css, ['shop-css']); gulp.watch(paths.shop.img, ['shop-img']); }); gulp.task('default', ['admin-js', 'admin-css', 'admin-img', 'shop-js', 'shop-css', 'shop-img']); gulp.task('watch', ['admin-watch', 'shop-watch']);
JavaScript
0.00002
@@ -1936,32 +1936,123 @@ ivate/sass/**',%0A + 'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/scss/**',%0A %5D,%0A @@ -5031,24 +5031,35 @@ k('watch', %5B +'default', 'admin-watch
afc26be7607f399ab038c8d5bf5a627759912bbc
Add bandaid fix for #91
src/Util.js
src/Util.js
const crypto = require('crypto') /** * @module Util */ module.exports = { /** * Performs string formatting for things like custom nicknames. * * @param {string} formatString The string to format (contains replacement strings) * @param {object} data The data to replace the string replacements with * @param {GuildMember} member The guild member this string is being formatted for * @returns {string} The processed string */ formatDataString (formatString, data, member) { let replacements = { '%USERNAME%': data.robloxUsername, '%USERID%': data.robloxId, '%DISCORDNAME%': data.discordName || '', '%DISCORDID%': data.discordId || '' } if (member != null) { replacements['%DISCORDNAME%'] = member.user.username replacements['%DISCORDID%'] = member.id replacements['%SERVER%'] = member.guild.name } return formatString.replace(/%\w+%/g, (all) => { return replacements[all] || all }) }, /** * Returns a promise that resolves after the given time in milliseconds. * @param {int} sleepTime The amount of time until the promise resolves * @returns Promise */ async sleep (sleepTime) { return new Promise(resolve => { setTimeout(resolve, sleepTime) }) }, /** * Takes an array of numbers and simplifies it into a string containing ranges, e.g.: * [0, 1, 2, 4, 6, 7, 8] --> "0-2, 4, 6-8" * @param {array} numbers The input numbers * @returns {string} The output string */ simplifyNumbers (numbers) { let output = [] let rangeStart for (let i = 0; i < numbers.length; i++) { let number = numbers[i] let next = numbers[i + 1] if (rangeStart != null && (next - number !== 1 || next == null)) { output.push(`${rangeStart}-${number}`) rangeStart = null } else if (next == null || next - number !== 1) { output.push(`${number}`) } else if (rangeStart == null) { rangeStart = number } } return output.join(', ') }, /** * Returns an md5 hash of the input string. * This is used for a key for a group binding. The key is the hash of the json of the rank binding. * @param {string} string The input string. * @returns {string} The md5 hash of the string. */ md5 (string) { return crypto.createHash('md5').update(string).digest('hex') }, /** * Gets group rank binding text for a binding. * Turns a rank binding object into a human-readable format. * @param {object} binding The binding object. * @param {boolean} [addCodeBlock=false] Whether or not to wrap the binding in markdown code block. * @returns {string} The binding in human-readable format. */ getBindingText (binding, addCodeBlock = false) { let bindingMessage = addCodeBlock ? '```markdown\n' : '' for (let [index, group] of binding.groups.entries()) { if (index > 0) bindingMessage += '...or\n' if (group.id.match(/[a-z]/i)) { bindingMessage += `# Virtual Group ${group.id}\n` bindingMessage += `Argument ${group.ranks.length > 0 ? group.ranks[0] : 'none'}` } else { bindingMessage += `# Group ${group.id}\n` bindingMessage += `Rank${group.ranks.length === 1 ? '' : 's'} ` + module.exports.simplifyNumbers(group.ranks) } bindingMessage += '\n\n' } return addCodeBlock ? bindingMessage + '\n```' : bindingMessage }, /** * Gets the user-facing link for the verification registry. * This is not used for actually checking against the registry. * This is for functionality in the future where we want to know where the user came from to help make sure that * they are on the right account on the website by making sure the user is in the guild they came from. * @param {Guild} guild The guild this link is being generated for. * @returns {string} The link to the verification site */ getVerifyLink (guild) { return `https://verify.eryn.io` // /?from=${guild.id}` } }
JavaScript
0
@@ -2830,24 +2830,157 @@ own%5Cn' : ''%0A +%0A if (binding.groups == null) %7B%0A return %60%5CnInvalid Group Format - Unbind role $%7Bbinding.role%7D to fix this problem.%5Cn%60%0A %7D%0A%0A for (let
e4698003aa02a0fa93225c2b96689217f2cd4986
remove commetns for sse
xgds_core/static/xgds_core/js/sseUtils.js
xgds_core/static/xgds_core/js/sseUtils.js
// __BEGIN_LICENSE__ //Copyright (c) 2015, United States Government, as represented by the //Administrator of the National Aeronautics and Space Administration. //All rights reserved. // //The xGDS platform is 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. // __END_LICENSE__ sse = {}; //namespace $.extend(sse, { initialize: function() { sse.heartbeat(); }, heartbeat: function() { setInterval(sse.checkHeartbeat, 11000); sse.subscribe('heartbeat', sse.connectedCallback, 'sse'); }, checkHeartbeat: function() { var connected = false if (sse.lastHeartbeat != undefined){ var diff = moment.duration(moment().diff(sse.lastHeartbeat)); if (diff.asSeconds() <= 10) { connected = true; } } if (!connected){ sse.disconnectedCallback(); } }, connectedCallback: function(event){ try { sse.lastHeartbeat = moment(JSON.parse(event.data).timestamp); var cdiv = $("#connected_div"); if (cdiv.hasClass('alert-danger')){ cdiv.removeClass('alert-danger'); cdiv.addClass('alert-success'); var c = $("#connected"); c.removeClass('fa-bolt'); c.addClass('fa-plug'); } } catch(err){ // in case there is no such page } }, disconnectedCallback: function(event){ try { var cdiv = $("#connected_div"); if (cdiv.hasClass('alert-success')){ cdiv.removeClass('alert-success'); cdiv.addClass('alert-danger'); var c = $("#connected"); c.addClass('fa-bolt'); c.removeClass('fa-plug'); } } catch(err){ // in case there is no such page } }, allChannels: function(theFunction, channels){ for (var i=0; i<channels.length; i++){ var channel = channels[i]; if (channel != 'sse') { theFunction(channel); } } }, activeChannels: undefined, getChannelsUrl: '/xgds_core/sseActiveChannels', getChannels: function(url) { // get the active channels over AJAX if (sse.activeChannels === undefined){ $.ajax({ url: sse.getChannelsUrl, dataType: 'json', async: false, success: $.proxy(function(data) { sse.activeChannels = data; }, this) }); } return sse.activeChannels; }, parseEventChannel: function(event){ return sse.parseChannel(event.target.url); }, parseChannel: function(fullUrl){ var splits = fullUrl.split('='); if (splits.length > 1){ return splits[splits.length-1]; } return 'sse'; }, subscribe: function(event_type, callback, channels) { if (channels != undefined) { if (!_.isArray(channels)) { channels = [channels]; } for (var i=0; i<channels.length; i++){ var channel = channels[i]; console.log('SUBSCRIBING TO ' + channel + ':' + event_type); var source = new EventSource("/sse/stream?channel=" + channel); source.addEventListener(event_type, callback, false); } } else { var allChannels = sse.getChannels(); for (var i=0; i<allChannels.length; i++){ var channel = allChannels[i]; console.log('SUBSCRIBING TO ' + channel + ':' + event_type); var source = new EventSource("/sse/stream?channel=" + channel); source.addEventListener(event_type, callback, false); } } } });
JavaScript
0.00002
@@ -3125,32 +3125,34 @@ hannels%5Bi%5D;%0A%09%09%09%09 +// console.log('SUB @@ -3495,16 +3495,18 @@ i%5D;%0A%09%09%09%09 +// console.
5a4fd3a0e456b4884f4a8ffefa3666e1bc5eb754
check if has internet connection
bin/cli.js
bin/cli.js
#! /usr/bin/env node 'use strict' const pkg = require('../package.json'), got = require('got'), money = require('money'), colors = require('colors'), API = 'https://api.fixer.io/latest' // arguments let argv = process.argv.slice(2), amount = argv[0], from = argv[1] // version if(argv.indexOf('--version') !== -1 || argv.indexOf('-v') !== -1) { console.log(pkg.version) return } // help if(argv.indexOf('--help') !== -1 || argv.indexOf('-h') !== -1 || argv.length == 0) { console.log(` Usage $ moeda <amount> <currency> Some currency [ usd, eur, gbp, brl... ] Examples $ moeda 1 usd Result Euro: 0.92 Libra Esterlina: 0.82 Real Brazilian: 3.15 Conversion of USD 1 `) return } // default console.log() got(API, { json: true }).then(response => { money.base = response.body.base money.rates = response.body.rates let rates = ['USD', 'EUR', 'GBP', 'BRL'], names = [ ' Dollar EUA:', ' Euro:', ' Libra Esterlina:', ' Real Brazilian:' ] rates.map((item, index) => { if(item != from.toUpperCase()) { console.log(` ${names[index].gray.italic} ${money.convert(amount, { from: from.toUpperCase(), to: item }).toFixed(2).green.bold} `) } }) console.log(` Conversion of ${from.toUpperCase()} ${amount} `.italic.gray) })
JavaScript
0.000449
@@ -419,30 +419,40 @@ .version)%0A -return +process.exit(1)%0A %0A%7D%0A%0A%0A// help @@ -809,19 +809,31 @@ D 1%0A + %60)%0A -return +process.exit(1)%0A %0A%7D%0A%0A @@ -1225,17 +1225,16 @@ se()) %7B%0A -%0A co @@ -1464,16 +1464,16 @@ amount%7D%0A - %60.it @@ -1483,11 +1483,245 @@ c.gray)%0A + process.exit(1)%0A%0A%7D).catch(error =%3E %7B%0A if(error.code === 'ENOTFOUND') %7B%0A console.log(' Please check your internet connection.%5Cn'.red)%0A%0A %7Delse %7B%0A console.log(' Internal server error... %5Cn'.red)%0A %0A %7D%0A process.exit(1)%0A%0A %7D)%0A
ee5b0ad78e6ac38d65432bfc483fc7b01659a966
fix onload
public/js/index.js
public/js/index.js
/** * Created by azu on 2014/06/10. * LICENSE : MIT */ "use strict"; function windowOnload() { require("./console-editor").initilize(); require("./sync-toc").initilize(); require("./bug-report").initilize(); } window.addEventListener("DOMContentLoaded", windowOnload);
JavaScript
0.000014
@@ -218,16 +218,151 @@ ze();%0A%7D%0A +var readyState = document.readyState;%0Aif (readyState == %22interactive%22 %7C%7C readyState === 'complete') %7B%0A windowOnload();%0A%7D else %7B%0A window.a @@ -411,8 +411,10 @@ Onload); +%0A%7D
66702e84ad3b31e82759243acb6a719a2d8159b0
upgrade the code for 0.2.0
bin/cli.js
bin/cli.js
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json'); var Promise = require('rsvp').Promise; var CMDS = ['on', 'off', 'state', 'temp', 'version', 'voltage']; var _ = require('lodash'); var yargs = require('yargs'); var argv = yargs .demand(1) .usage('Usage: $0 cmd [relay] [opts]') .help('h') .alias('h', ['?', 'help']) .version(pkg.version + '\n', 'version') .showHelpOnFail(true, 'Valid commands are: ' + CMDS.join(', ')) .describe('p', 'The usb port uri to use. Leave empty to use port scan') .alias('p', 'port') .describe('n', 'The number of relays on the board') .alias('n', 'relayCount') .defaults('n', 2) .boolean('v') .describe('v', 'Enables verbose mode (for debug only)') .alias('v', 'verbose') .check(function (argv, opts) { return _.contains(CMDS, argv._[0]); }) .argv; var Tosr0x = require('tosr0x').Tosr0x; var cmd = argv._[0]; var ctl; process.title = 'Tosr0x'; if (cmd === 'temp') { cmd = 'temperature'; } else if (cmd === 'state') { cmd = 'refreshStates'; } var create = function () { var options = { debug: argv.v, relayCount: argv.n }; if (!argv.p) { return Tosr0x.fromPortScan(); // TODO: put options when available } else { return new Promise(function (res) { res(new Tosr0x(argv.p, options)); }); } }; var run = function (c) { ctl = c; return ctl.open().then(function () { return ctl[cmd](parseInt(argv._[1], 10) || 0); }); }; var display = function (res) { console.log(res); console.log('Done.'); }; var error = function (err) { console.error(err); }; var close = function () { if (!!ctl) { ctl.closeImmediate(); } }; create() .then(run) .then(display) .catch(error) .finally(close);
JavaScript
0.000026
@@ -1019,22 +1019,19 @@ %0A%7D%0A%0Avar -create +run = funct @@ -1039,185 +1039,46 @@ on ( +c ) %7B%0A%09 -var options = %7B%0A%09%09debug: argv.v,%0A%09%09relayCount: argv.n%0A%09%7D;%0A%09if (!argv.p) %7B%0A%09%09return Tosr0x.fromPortScan(); // TODO: put options when available%0A%09%7D else %7B%0A%09%09return new Promise +ctl = c;%0A%09return ctl.open().then (fun @@ -1088,69 +1088,55 @@ on ( -res ) %7B%0A%09%09 -%09 re -s(new Tosr0x(argv.p, options) +turn ctl%5Bcmd%5D(argv._%5B1%5D );%0A -%09 %09%7D);%0A -%09%7D%0A %7D;%0A%0Avar run @@ -1127,27 +1127,31 @@ %7D);%0A%7D;%0A%0Avar -run +display = function @@ -1155,150 +1155,145 @@ on ( -c +res ) %7B%0A%09 -ctl = c;%0A%09return ctl.open().then(function () %7B%0A%09%09return ctl%5Bcmd%5D(parseInt(argv._%5B1%5D, 10) %7C%7C 0);%0A%09%7D);%0A%7D;%0A%0Avar display = function (res) +if (_.isObject(res)) %7B%0A%09%09_.forOwn(res, function (val, key) %7B%0A%09%09%09if (key !== 'ctl') %7B%0A%09%09%09%09console.log(val);%0A%09%09%09%7D%0A%09%09%7D);%0A%09%7D else %7B%0A +%09 %09con @@ -1307,16 +1307,19 @@ g(res);%0A +%09%7D%0A %09console @@ -1466,18 +1466,71 @@ %7D;%0A%0A -create()%0A%09 +Tosr0x.create(argv.p, %7B%0A%09debug: argv.v,%0A%09relayCount: argv.n%0A%7D)%0A .the @@ -1536,17 +1536,16 @@ en(run)%0A -%09 .then(di @@ -1551,17 +1551,16 @@ isplay)%0A -%09 .catch(e @@ -1565,17 +1565,16 @@ (error)%0A -%09 .finally
76bfa593e9a03579487fd396d03c9ee7a140b06e
Improve yarn init
bin/init.js
bin/init.js
var fs = require('fs-extra'); var logger = require('winston'); var path = require('path'); var inquirer = require('inquirer'); var child_process = require('child_process'); module.exports = function init() { var destination = process.cwd(); var questions = [ { type: 'confirm', name: 'destinationOk', message: 'OK to create new yarn site at path: ' + destination + '?', default: true } ]; inquirer.prompt(questions, function(answers) { if (answers.destinationOk === false) { process.exit(1); } var scaffoldSource = path.join(__dirname, '../node_modules/yarn-scaffold'); try { fs.copySync(scaffoldSource, destination); } catch (e) { logger.error('Unable to initialize a new yarn site.'); } [ '_site', 'node_modules' ].forEach(function(dir) { var rmDir = path.join(destination, dir); try { fs.removeSync(rmDir); } catch (e) { // Fail silently, not a big deal to not be able to remove files. } }); var npmInstallProc; try { npmInstallProc = child_process.spawn('npm', [ 'install' // Disable caching. ], { stdio: 'inherit', cwd: destination }); } catch (e) { logger.warn('Unable to run `npm install`'); } npmInstallProc.on('close', function() { logger.info('New yarn site created at ' + destination); }); }); };
JavaScript
0.000001
@@ -630,24 +630,54 @@ caffold');%0A%0A + // Copy scaffold project.%0A try %7B%0A @@ -816,44 +816,706 @@ -%5B%0A '_site',%0A 'node_modules +// Create our package.json file. Grab the existing dependencies from the%0A // scaffold package.json and create our clean new one.%0A try %7B%0A var scaffoldJson = require(path.join(destination, 'package.json'));%0A%0A var packageJsonData = %7B%0A main: 'my-yarn-site',%0A dependencies: scaffoldJson.dependencies%0A %7D;%0A%0A var packageJsonPath = path.join(destination, 'package.json');%0A fs.outputFileSync(packageJsonPath, JSON.stringify(packageJsonData));%0A %7D catch (e) %7B%0A logger.error('Unable to create package.json files.');%0A %7D%0A%0A // Remove un-needed files.%0A %5B%0A '_site',%0A 'node_modules',%0A 'images/.gitkeep',%0A '.npmignore',%0A 'README.md '%0A
8df91fd2ba6fbc09141b87ca37dce1f949341cd1
Fix path
bin/cli.js
bin/cli.js
#!/usr/bin/env node var entity2utf8 = require('../lib/check-entity'), log = require('../lib/log'), program = require('commander'), isutf8 = require('isutf8'), Q = require('q'), FS = require('q-io/fs'); program .version(require('../package.json').version) .usage('[options] <file...>') .option( '--ignore <entities>', 'List of entities separated with commas. Example: "&nbsp;,&raquo;,&shy;"', function(value) { return value.split(',').map(function(item) { return item.trim(); }); }, []) .parse(process.argv); if(!program.args.length) { program.help(); } Q.all(program.args.map(function(file) { return FS.read(file, 'b') .then(function(content) { if(!isutf8(content)) { log.error(file + ' not UTF-8.'); return; } var result = entity2utf8.find(content.toString('utf8'), program.ignore); if(result.length) { log.errorNewLine(file); log.error('Need replace:'); result.forEach(function(item) { log.error(item.original + ' → "' + item.replace + '"' + (item.count > 1 ? ', count: ' + item.count : '')); }); } else { log.log('No errors.'); } }, function() { log.errorNewLine(file + ': No such file'); }); })).then(function() { process.exit(log.hasErrors() ? 1 : 0); });
JavaScript
0.000018
@@ -52,20 +52,19 @@ lib/ -check- entity +2utf8 '),%0A
f4e4eb6305916ebf39046d813c1ae8f36db0fc0d
Add support for array bodies
lib/form-data.js
lib/form-data.js
'use strict' var path = require('path') var mime = require('mime-types') , isstream = require('isstream') function generate (options) { var parts = [] Object.keys(options.multipart).forEach(function (key) { var part = options.multipart[key] var body = part.value || part if (isstream(body) && part.options && part.options.knownLength) { body._knownLength = part.options.knownLength } parts.push({ 'content-disposition': 'form-data; name="' + key + '"' + getContentDisposition(part), 'content-type': getContentType(part), body: body }) }) return parts } function getContentDisposition (part) { var body = part.value || part , options = part.options || {} var filename = '' if (options.filename) { filename = options.filename } // fs- and request- streams else if (body.path) { filename = body.path } // http response else if (body.readable && body.hasOwnProperty('httpVersion')) { filename = body.client._httpMessage.path } var contentDisposition = '' if (filename) { contentDisposition = '; filename="' + path.basename(filename) + '"' } return contentDisposition } function getContentType (part) { var body = part.value || part , options = part.options || {} var contentType = '' if (options.contentType) { contentType = options.contentType } // fs- and request- streams else if (body.path) { contentType = mime.lookup(body.path) } // http response else if (body.readable && body.hasOwnProperty('httpVersion')) { contentType = body.headers['content-type'] } else if (options.filename) { contentType = mime.lookup(options.filename) } else if (typeof body === 'object') { contentType = 'application/octet-stream' } else if (typeof body === 'string') { contentType = 'text/plain' } return contentType } exports.generate = generate
JavaScript
0
@@ -279,24 +279,113 @@ lue %7C%7C part%0A + body = (body instanceof Array) ? body : %5Bbody%5D%0A%0A body.forEach(function (item) %7B%0A if (isst @@ -389,20 +389,20 @@ sstream( -body +item ) && par @@ -448,20 +448,22 @@ %7B%0A -body + item ._knownL @@ -499,19 +499,24 @@ gth%0A + %7D%0A%0A + part @@ -524,16 +524,19 @@ .push(%7B%0A + 'c @@ -596,16 +596,19 @@ + + + getCon @@ -626,24 +626,27 @@ tion(part),%0A + 'conte @@ -687,18 +687,31 @@ + body: -body +item%0A %7D) %0A
406f0d1e1df5053847e3bc6cd0f514f50502cf5d
fix this instance
src/a11y.js
src/a11y.js
import after from './after' import validate from './options' import browser from './util/browser' import Suite from './test' export default class A11y { /** * @arg {object} React - The React instance you want to patch * @arg {object} ReactDOM - The ReactDOM instance you'll be using * @arg {object} options - the options * @returns {A11y} The react-a11y instance */ constructor (React, ReactDOM, options = {}) { this.options = validate(options) // extend default opts this.React = React // save react for undoing patches this.ReactDOM = ReactDOM if (!this.React || !this.React.createElement) { throw new Error('Missing parameter: React') } if (!this.ReactDOM || !this.ReactDOM.findDOMNode ) { throw new Error('Missing parameter: ReactDOM') } this.__sync = false this.suite = new Suite(React, ReactDOM, this.options) this.patchReact() } /** * Patch React, replacing its createElement by our implementation * so we can run the tests * @returns {undefined} */ patchReact () { // save old createElement this._createElement = this.React.createElement const that = this this.React.createElement = function (klass, _props = {}, ...children) { // fix for props = null const props = _props || {} // create a refs object to hold the ref. // this needs to be an object so that it can be passed // by reference, and hold chaning state. const refs = typeof props.ref === 'string' ? props.ref : {} const ref = typeof props.ref === 'string' ? props.ref : function (node) { refs.node = node // maintain behaviour when ref prop was already set if ( typeof props.ref === 'function' ) { props.ref(node) } } const newProps = typeof klass === 'string' ? { ...props, ref } : props const reactEl = that._createElement(klass, newProps, ...children) // only test html elements if (typeof klass === 'string') { const handler = that.failureHandler(reactEl, refs) const childrenForTest = children.length === 0 ? props.children || [] : children that.suite.test(klass, props, childrenForTest, handler) } return reactEl } } /** * Restore React and all components as if we were never here * @returns {undefined} */ restoreAll () { this.React.createElement = this._createElement after.restorePatchedMethods() } /** * Creates a failure handler based on the element that was created * @arg {object} reactEl - The react element this failure is for * @arg {object} refs - The object that holds the DOM node (passed by ref) * @returns {function} A handler that knows everything it needs to know */ failureHandler (reactEl, ref) { const { reporter , filterFn } = this.options /** * @arg {string} type - The HTML tagname of the element * @arg {object} props - The props that were passed to the element * @arg {string} msg - The warning message * @returns {undefined} */ return function (errInfo) { // get the owning component (the one that has // the element in its render fn) const owner = reactEl._owner // if there is an owner, use its name // if not, use the tagname of the violating elemnent const displayName = owner && owner.getName() // stop if we're not allowed to proceed if ( !filterFn(displayName, errInfo.props.id, errInfo.msg) ) { return } // gather all info for the reporter const info = { ...errInfo , displayName } // if we need to include the rendered node, we need to wait until // the owner has rendered if ( owner && browser && !this.__sync ) { const instance = owner._instance // Cannot log a node reference until the component is in the DOM, // so defer the call until componentDidMount or componentDidUpdate. after.render(instance, function () { // unpack the ref let DOMNode if ( typeof ref === 'string' ) { DOMNode = this.ReactDOM.findDOMNode(instance.refs[ref]) } else if ( 'node' in ref ) { DOMNode = ref.node } else { throw new Error('could not resolve ref') } reporter({ ...info, DOMNode }) }) } else { reporter(info) } }.bind(this) } /** * Force A11y in sync mode, DOMNodes might be omitted * @arg {boolean} sync - wether or not to force sync mode */ __forceSync (sync = true) { this.__sync = !!sync } }
JavaScript
0.999999
@@ -3355,16 +3355,70 @@ l._owner +%0A console.log('owner', owner && owner._instance) %0A%0A @@ -4571,16 +4571,27 @@ %7D +.bind(this) )%0A
1e4564e97312961cc4d734bd8a927f3df6653f6c
Fix path of file uploads
lib/form-data.js
lib/form-data.js
const mime = require("./mime-types"), fs = require("fs"), os = require("os"), path = require("path"), url = require("url"); class FormData { constructor(server) { let cfg = server.getCfg("file_uploads"); this.server = server; this.buffer = new Buffer("\r\n"); this.type = ""; this.boundary = ""; this.bytesReceived = 0; this.maxBytes = cfg.limit || 1048576; if (cfg.status !== "on") { this.maxBytes = 0; } this.uploaded = false; this.headers(() => { server.req.on("data", data => { this.write(data); }).on("end", () => { this.end(); }); }); } headers(cb) { let header = this.server.req.headers["content-type"], match; if (header && header.match(/urlencoded/i)) { this.type = "urlencoded"; } if (header && header.match(/multipart/i)) { this.type = "multipart"; match = header.match(/boundary=(?:"([^"]+)"|([^;]+))/i); if (match) { match = match[1] || match[2]; this.boundary = new Buffer(match.length + 4); this.boundary.write("\r\n--", 0); this.boundary.write(match, 4); } else { this.server.sendErrorPage(500); return void 0; } } cb(); } write(data) { this.bytesReceived += data.length; if (this.bytesReceived > this.maxBytes) { this.server.sendErrorPage(413); return void 0; } this.buffer = Buffer.concat([this.buffer, data]); } end() { if (this.server.res.finished) { return void 0; } if (this.type === "urlencoded") { this.urlencoded(); } if (this.type === "multipart") { this.multipart(); } } urlencoded() { let buffer = this.buffer; buffer = buffer.toString(); buffer = buffer.replace(/\r\n/g, ""); this.server.POST = url.parse("/?" + buffer, true).query; this.server.sendFile(); } multipart() { let cfg = this.server.getCfg("file_uploads"), part = {}, boundary = this.boundary, buffer = this.buffer, bIdx = 0, idx = 0, field, value, match, chr, state = arguments[1] || 0, s = { BOUNDARY: 0, HEADER_START: 1, FIELD: 2, VALUE: 3 }, i; if (this.server.res.finished) { return void 0; } for (i = arguments[0] || 0; i < buffer.length; ++i) { chr = buffer[i]; switch (state) { case s.BOUNDARY: if (bIdx && chr !== boundary[bIdx]) { bIdx = 0; } if (chr === boundary[bIdx]) { ++bIdx; if (bIdx === boundary.length) { state = s.HEADER_START; if (part.name) { part.data = buffer.slice(idx, i + 1 - bIdx); if (part.filename && cfg.status === "on") { this.writeFile(cfg.dir, part, i, state); return void 0; } else if (!part.filename) { if (part.data.length) { part.data = part.data.toString(); this.server.POST[part.name] = part.data; } } } } } break; case s.HEADER_START: if ((chr === 13 && buffer[i + 1] === 10) || (chr === 45 && buffer[i + 1] === 45)) { state = s.FIELD; idx = i + 2; bIdx = 0; part = { name: "", filename: "", data: "" }; } break; case s.FIELD: if (chr === 58) { field = buffer.slice(idx, i).toString().toLowerCase(); state = s.VALUE; idx = i + 1; if (buffer[i + 1] === 32) { ++idx; } } break; case s.VALUE: if (chr === 13 && buffer[i + 1] === 10) { value = buffer.slice(idx, i).toString(); if (field === "content-disposition") { match = value.match(/name="([^"]*)"/i); if (match) { part.name = match[1]; } match = value.match(/filename="(.*?)"/i); if (match) { match = match[1]; match = match.substr(match.lastIndexOf("\\") + 1); part.filename = match; } } else if (field === "content-type") { part.mime = value; } else if (field === "content-transfer-encoding") { part.transferEncoding = value.toLowerCase(); } if (buffer[i + 2] === 13 && buffer[i + 3] === 10) { state = s.BOUNDARY; idx = i + 4; } else { state = s.FIELD; idx = i + 2; } } break; } } this.server.sendFile(); } writeFile(dir, part, iterator, state) { let name = "upload_", tmp, i; for (i = 0; i < 16; ++i) { tmp = Math.floor(Math.random() * 256); name += ("0" + tmp.toString(16)).slice(-2); } name = path.join(dir || os.tmpdir(), name); fs.writeFile(name, part.data, err => { if (!err) { tmp = {}; tmp.name = part.filename; tmp.tmp_name = name; tmp.size = part.data.length; tmp.type = mime.lookup(part.filename); this.server.FILES[part.name] = tmp; this.uploaded = true; } this.multipart(iterator, state); }); } } module.exports = FormData;
JavaScript
0.000013
@@ -4412,16 +4412,31 @@ th.join( +process.cwd(), dir %7C%7C o @@ -4724,24 +4724,104 @@ = true;%0A%09%09%09%7D + else %7B%0A%09%09%09%09this.server.server.writeError(%22Could not upload file %22 + name);%0A%09%09%09%7D %0A%0A%09%09%09this.mu
6bf3feca6d9d28783962058e876a1e8f757885ef
Add appending of file paths (still weird but at least it will not override it anymore)
bin/cli.js
bin/cli.js
#!/usr/bin/env node "use strict"; const fs = require("fs"); const path = require("path"); const { promisify } = require("util"); const mkdirp = require("mkdirp"); const mkdir = promisify(mkdirp); const writeFile = promisify(fs.writeFile); const readFile = promisify(fs.readFile); const buildStats = require("../plugin/build-stats"); const TEMPLATE = require("../plugin/template-types"); const argv = require("yargs") .strict() .option("extra-style-path", { describe: "Extra override css file path", string: true }) .option("filename", { describe: "Output file name", string: true, default: "./stats.html" }) .option("title", { describe: "Output file title", string: true, default: "RollUp Visualizer" }) .option("template", { describe: "Template type", string: true, choices: TEMPLATE, default: "treemap" }) .help().argv; const listOfFiles = argv._; const run = async (title, template, extraStylePath, filename, files) => { if (files.length === 0) { throw new Error("Empty file list"); } const fileContents = await Promise.all( files.map(async file => { const textContent = readFile(file, { encoding: "utf-8" }); const jsonContent = JSON.parse(textContent); return [file, jsonContent]; }) ); const tree = { name: "root", children: [] }; const nodes = Object.create(null); const nodeIds = Object.create(null); let links = []; for (const [, fileContent] of fileContents) { if (fileContent.tree.name === "root") { tree.children = tree.children.concat(fileContent.tree.children); } else { tree.children.push(fileContent.tree); } Object.assign(nodes, fileContent.nodes); Object.assign(nodeIds, fileContent.nodeIds);//TODO this will override things links = links.concat(fileContent.links); } const data = { tree, links, nodeIds, nodes }; const fileContent = await buildStats( title, data, template, extraStylePath, {} ); await mkdir(path.dirname(filename)); await writeFile(filename, fileContent); }; run( argv.title, argv.template, argv.extraStylePath, argv.filename, listOfFiles ).catch(err => { console.error(err.message); process.exit(1); });
JavaScript
0
@@ -1466,16 +1466,20 @@ (const %5B +file , fileCo @@ -1732,88 +1732,103 @@ s);%0A +%0A -Object.assign(nodeIds, fileContent.nodeIds);//TODO this will override things +for (const %5Bid, uid%5D of fileContent.nodeIds) %7B%0A nodeIds%5Bfile + %22/%22 + id%5D = uid;%0A %7D %0A%0A
f841f65508bb81fc926fdc722a8b0deea01cb5d2
Trim whitespace and remove \n from item name.
src/alza.js
src/alza.js
import _request from 'request-promise' import cheerio from 'cheerio' const jar = _request.jar() const request = _request.defaults({ headers: {'Content-Type': 'application/json'}, jar, }) const SCV='https://www.alza.sk/Services/EShopService.svc/' export function* login(credentials) { return yield request.post(`${SCV}LoginUser`, {body: JSON.stringify(credentials)}) } export function* addToCart({url, count}) { const id = url.match(/(d|dq=)(\d*)(\.htm)?$/)[2] return yield request.post(`${SCV}OrderCommodity`, {body: JSON.stringify( {id, count} )}) } export function* getInfo(url) { const $ = cheerio.load(yield request(url)) const name = $('h1[itemprop="name"]').text() const price = parseFloat( $('span.price_withoutVat').text() .replace(/[^\d,]/g, '') .replace(/,/g, '.') ) const description = $('div.nameextc').text() return {name, price, description} }
JavaScript
0
@@ -688,16 +688,44 @@ ).text() +.trim().replace(/%5Cs+/g, ' ') %0A const
9d8dc8ddf67ca1abc8ef1b60def1b5c5efc644fb
Include exception stack trace in notifications
lib/formatter.js
lib/formatter.js
"use babel"; import gateway from "./gateway"; import main from "./main"; export default { // formats the active text editor formatActiveTextEditor() { if ((editor = atom.workspace.getActiveTextEditor())) { if (main.hasElixirGrammar(editor)) { this.formatTextEditor(editor); } else { atom.notifications.addInfo( "Exfmt-Atom only formats Elixir source code", { dismissable: false } ); } } }, // formats the given text editor formatTextEditor(editor) { try { const { text, range } = this.currentTextSelection(editor); const { status, stdout, stderr } = gateway.runExfmt(text); switch (status) { case 0: { this.insertText(editor, range, stdout.toString()); break; } default: this.showErrorNotifcation("Exfmt-Atom Error", { detail: stderr }); } } catch (exception) { this.showErrorNotifcation("Exfmt-Atom Exception", { detail: exception }); } }, // returns current text selection and range (or entire text if none) currentTextSelection(editor) { if (this.hasSelectedText(editor)) { text = editor.getSelectedText(); range = editor.getSelectedBufferRange(); } else { text = editor.getText(); range = null; } return { text: text, range: range }; }, // inserts the given text and updates cursor position insertText(editor, range, text) { if (range) { editor.setTextInBufferRange(range, this.indentText(editor, range, text)); editor.setCursorScreenPosition(range.start); } else { const cursorPosition = editor.getCursorScreenPosition(); editor.setText(text); editor.setCursorScreenPosition(cursorPosition); } }, // indents text using indentation level of first line of range indentText(editor, range, text) { const indentation = editor.indentationForBufferRow(range.start.row); if (editor.softTabs) { prefix = " ".repeat(indentation * editor.getTabLength()); } else { prefix = "\t".repeat(indentation); } return prefix + text.replace(/\n/g, "\n" + prefix); }, // returns true if editor has selected text hasSelectedText(editor) { return !!editor.getSelectedText(); }, // returns the external exfmt directory from settings (if any) exfmtDirectory() { return atom.config.get("exfmt-atom.exfmtDirectory"); }, // shows error notification showErrorNotifcation(message, options = {}) { options["dismissable"] = true; if (atom.config.get("exfmt-atom.showErrorNotifications")) { atom.notifications.addError(message, options); } } };
JavaScript
0
@@ -966,24 +966,32 @@ xception%22, %7B +%0A detail: exc @@ -996,16 +996,54 @@ xception +,%0A stack: exception.stack%0A %7D);%0A
4bee26216fc55d38f2bd059f74c35bce67c696c7
add pid-file
bin/cli.js
bin/cli.js
#!/usr/bin/env node 'use strict'; const connect = require('connect'); const hall = require('hall'); const {middleware, FileStore, NedbDataStorage, FsBlobStorage} = require('..'); const nedb = require('nedb'); const argentum = require('argentum'); const path = require('path'); const argv = process.argv.slice(2); const config = argentum.parse(argv, { aliases: { d: 'debug', v: 'verbose', }, defaults: { port: process.env.PORT || 8080, debug: process.env.DEBUG === '1', verbose: process.env.VERBOSE === '1', }, }); const DEBUG = config.debug; const VERBOSE = config.verbose; const port = config.port; const dir = path.resolve(process.cwd(), argv[0] || '.'); const storage = new FileStore({ dataStore: new NedbDataStorage({ db: new nedb({ filename: dir + '/files.db', autoload: true, }), }), blobStore: new FsBlobStorage({dir}), }); const router = hall(); const logger = VERBOSE ? console : null; connect() .use(middleware(router, storage, logger, DEBUG)) .use((err, req, res, next) => { if (! err) { res.statusCode = 404; res.statusText = 'Nothing found'; res.end(); } else { res.statusCode = 500; res.statusText = 'Internal error'; res.end(err.message); DEBUG && console.log(err); } }) .listen(port); VERBOSE && console.log('Listening on localhost:%s', port);
JavaScript
0.000001
@@ -238,24 +238,50 @@ argentum');%0A +const fs = require('fs');%0A const path = @@ -294,24 +294,24 @@ re('path');%0A - %0Aconst argv @@ -577,24 +577,91 @@ SE === '1',%0A + pidFile: process.env.PID_FILE %7C%7C '/var/run/file-store.pid'%0A %7D,%0A%7D);%0A%0A @@ -802,16 +802,349 @@ %7C%7C '.'); +%0Aconst PID_FILE = path.resolve(process.cwd(), config.pidFile);%0A%0Aif (fs.existsSync(PID_FILE)) %7B%0A onError(%60Pid file %22$%7BPID_FILE%7D%22 already exists%60);%0A%7D%0A%0Afs.writeFileSync(PID_FILE, process.pid);%0A%0Aprocess.on('beforeExit', () =%3E onExit);%0Aprocess.on('exit', () =%3E onExit);%0Aprocess.on('SIGINT', () =%3E %7B%0A onExit()%0A process.exit();%0A%7D); %0A%0Aconst @@ -1816,16 +1816,16 @@ port);%0A%0A - VERBOSE @@ -1871,12 +1871,167 @@ %25s', port);%0A +%0Afunction onError(error) %7B%0A console.error(error);%0A process.exit(1);%0A%7D%0A%0Afunction onExit() %7B%0A fs.existsSync(PID_FILE) && fs.unlinkSync(PID_FILE);%0A%7D%0A
79ea71c51f0cd54abb4d5059ae4013c7b5cfeb88
Update #broadcast examples to new interface
examples/broadcast.js
examples/broadcast.js
"use strict" var example = require("washington") var Sydney = require("../sydney") example("#broadcast: send to the subscriber", function (check) { var venue = new Sydney var event = { name: "event" } venue.add(function (e) { check(e, event) }) venue.broadcast(event) }) example("#broadcast: chainable", function () { var venue = new Sydney var event = { name: "event" } venue.add(function () {}) return venue.broadcast(event) === venue }) example("#broadcast: @no-subscribers won't fail", function () { new Sydney().broadcast() })
JavaScript
0
@@ -209,32 +209,48 @@ %7D%0A%0A venue.add( +%7B%0A callback: function (e) %7B c @@ -265,16 +265,20 @@ event) %7D +%0A %7D )%0A%0A ven
b7a0da513efd7f4f74f8ba25462abcf4deef3076
Mark sub paths active
public/js/senna.js
public/js/senna.js
function scroll_toc(path) { // remove base either '/docs/' or '/' var base = '/docs/'; path = path.indexOf(base) == 0? path.substring(base.length) : path.substring(1); if(path[path.length - 1] == '/') { path = path.substring(0, path.length - 1); } var path = '.' + path.split('/').join(' .'); if(window.toc.active) { window.toc.active.removeClass('active'); } if(path.length > 1) { window.toc.active = $(path); window.toc.active.addClass('active'); } } $(document).ready(function() { window.toc = { active: null }; if(window.location.pathname) { scroll_toc(window.location.pathname); } var app = new senna.App(); app.setBasePath('/'); // replace html with 'content' id app.addSurfaces('content'); app.addRoutes(new senna.Route(/.*/, senna.HtmlScreen)); app.on('startNavigate', function(event) { scroll_toc(event.path) }); app.on('endNavigate', function(event) { var hash = event.path.indexOf('#'); if (hash !== -1) { location.hash = path.substr(hash); } else { $('#content').scrollTop(0); } }); });
JavaScript
0.000001
@@ -270,20 +270,16 @@ %7D%0A %0A -var path = ' @@ -318,53 +318,20 @@ %0A%0A -if(window.toc.active) %7B%0A window.toc.active +$('.active') .rem @@ -349,20 +349,16 @@ ctive'); -%0A %7D %0A%0A if(p @@ -383,58 +383,149 @@ -window.toc.active = $(path);%0A window.toc.active +$(path).addClass('active');%0A %0A while(path.lastIndexOf(' ') %3E -1) %7B%0A path = path.substring(0, path.lastIndexOf(' '));%0A $(path) .add @@ -541,16 +541,22 @@ tive');%0A + %7D%0A %7D%0A%7D%0A%0A$ @@ -589,79 +589,8 @@ ) %7B%0A - window.toc = %7B active: null %7D;%0A %0A if(window.location.pathname) %7B%0A sc @@ -624,20 +624,16 @@ thname); -%0A %7D %0A%0A var
35e6d43022214df16810194bf62f6a895c88713f
Set session and sessionhandle events
bin/seed.js
bin/seed.js
/* * Copyright (c) 2015 peeracle contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; var Peeracle = require('..'); var program = require('commander'); var mediaFileName; var mediaFileStream; var media; var metadataFileName; var metadataFileStream; var metadata; program .version('0.0.1') .usage('[options] <metadataFile>') .option('-m, --media [file]', 'Original media file') .parse(process.argv); if (!process.argv.slice(2).length) { program.outputHelp(); process.exit(1); } metadataFileName = program.args[0]; mediaFileName = program.media; try { metadataFileStream = new Peeracle.FileDataStream({ path: metadataFileName, mode: 'r' }); } catch (e) { console.log('Can\'t open the metadata file:', e.message); process.exit(1); } function start() { var session = new Peeracle.Session(); var handle = session.addMetadata(metadata); } metadata = new Peeracle.Metadata(); metadata.unserialize(metadataFileStream, function unserializeCb(error) { if (mediaFileName) { try { mediaFileStream = new Peeracle.FileDataStream({ path: mediaFileName }); } catch (e) { console.log('Can\'t open the media file:', e.message); process.exit(1); } Peeracle.Media.loadFromDataStream(mediaFileStream, function loadFromDataStreamCb(error, instance) { if (error) { throw error; } metadata.validateMedia(media, function validateMediaCb(error) { if (error) { throw error; } start(); }); }); return; } start(); });
JavaScript
0
@@ -1245,19 +1245,8 @@ eam; -%0Avar media; %0A%0Ava @@ -1818,16 +1818,21 @@ n start( +media ) %7B%0A va @@ -1910,16 +1910,422 @@ metadata +, media);%0A%0A session.on('connect', function onConnectCb(tracker) %7B%0A %7D);%0A%0A session.on('disconnect', function onDisconnectCb(tracker) %7B%0A %7D);%0A%0A handle.on('enter', function onEnterCb(id, got) %7B%0A %7D);%0A%0A handle.on('leave', function onLeaveCb(id) %7B%0A %7D);%0A%0A handle.on('request', function onRequestCb(id, segment) %7B%0A %7D);%0A%0A handle.on('send', function onSendCb(id, segment, bytesSent) %7B%0A %7D);%0A%0A handle.start( );%0A%7D%0A%0Ame @@ -2759,18 +2759,16 @@ amCb(err -or , instan @@ -2780,34 +2780,32 @@ %0A if (err -or ) %7B%0A th @@ -2803,34 +2803,32 @@ throw err -or ;%0A %7D%0A%0A @@ -2832,16 +2832,43 @@ +start(instance);%0A /* metadata @@ -2882,21 +2882,24 @@ teMedia( -media +instance , functi @@ -2991,27 +2991,8 @@ %7D%0A%0A - start();%0A @@ -2994,24 +2994,26 @@ %0A %7D); +*/ %0A %7D);%0A @@ -3031,19 +3031,23 @@ %7D%0A start( +null );%0A%7D);%0A
9e4782c4e52a4d6c17a9e4d98fdf55a3eb80b264
Fix typo
public/js/todos.js
public/js/todos.js
let updateID; $(document).ready(() => { $('#newDialog').dialog({ title: 'Add New Todo', autoOpen: false, modal: true, show: { effect: 'blind', duration: 1000 }, hide: { effect: 'blind', duration: 1000 }, buttons: [{ text: 'Add', click: function() { let data = $('#new-form-data').serialize(); postNewTodo(data) $(this).dialog('close') } }] }); $('#updateDialog').dialog({ title: 'Update Todo', autoOpen: false, modal: true, show: { effect: 'blind', duration: 1000 }, hide: { effect: 'blind', duration: 1000 }, buttons: [{ text: 'Update', click: function() { let data = $('#update-form-data').serialize(); updateTodo(updateID, data) $(this).dialog('close') } }] }); $('#opener').click(() => { $('#newDesc').val('') $('#newDialog').dialog('open'); }) // Click listener for todo items $('ul').click(() => { var target = $(event.target) // console.log(target) if (target.hasClass('list-item')) { target.toggleClass('completed') } else if (target.hasClass('fa-trash-o')) { var id = target[0].closest('li').id deleteTodo(id) } else if (target[0].className == 'fa fa-pencil') { var description = target[0].closest('li').innerText updateID = target[0].closest('li').id $('#updateDialog').dialog('open') $('#updDesc').val(description) } }) }) const postNewTodo = (data) => { $.post({ url: 'http://localhost:3000/api/todos', data: data, dataType: 'json', headers: { 'Content-Type':'application/json' } }) .done((response) => { const html = `<li class="list-item" id=${response.id}><span id="trash"><i class="fa fa-trash-o"></i></span> ${response.description}<span id="pencil"><i class="fa fa-pencil"></i></span></li>` $(html).hide().appendTo('ul').fadeIn(1000); }) .fail((err) => { console.log(`It failed ${err.message}`) }) } const deleteTodo = (id) => { $.ajax({ url: `http://localhost:3000/api/todos/${id}`, type: 'delete', headers: { 'Content-Type':'application/json' } }) .done((response) => { $(document.getElementById(id)).fadeOut(500, () => { $(this).remove() }) }) .fail(err => console.log(err)) } const updateTodo = (id, data) => { $.ajax({ url: `http://localhost:3000/api/todos/${id}`, type: 'put', data: data, dataType: 'json' headers: { 'Content-Type':'application/json' } }) .done((response) => { $(document.getElementById(id))[0].childNodes[1].nodeValue = response.description }) .fail(err => console.log(err)) }
JavaScript
0.999999
@@ -2537,24 +2537,25 @@ Type: 'json' +, %0A headers
bab3e22ed1099f56f136b89e2bd08d4f6ff90fb9
fix typo in markdown instructions
examples/markdown/app.js
examples/markdown/app.js
var mercury = require('../../index') var h = mercury.h var inlineMdEditor = require('./component/inlineMdEditor') var sideBySideMdEditor = require('./component/sideBySideMdEditor') app.render = appRender module.exports = app function app() { var state = mercury.hash({ inlineEditor: inlineMdEditor({ placeholder: 'Enter some markdown...' }), sideBySideEditor: sideBySideMdEditor({ placeholder: 'Enter some markdown...', value: [ '#Hello World', '', '* sample', '* bullet', '* points' ].join('\n') }) }) return state } function appRender(state) { return h('.page', { style: { visibility: 'hidden' } }, [ h('link', { rel: 'stylesheet', href: '/mercury/examples/markdown/style.css' }), h('.content', [ h('h2', 'Side-by-side Markdown Editor'), h('p', 'Enter some markdown and click outside of the textarea to ' + 'see the parsed result. Click the output to edit again.'), sideBySideMdEditor.render(state.sideBySideEditor), h('h2', 'Inline Markdown Editor'), h('p', 'Enter some markdown and click outside of the textarea to ' + 'see the parsed result. Click the output to edit again.'), inlineMdEditor.render(state.inlineEditor) ]) ]) }
JavaScript
0.999005
@@ -836,44 +836,44 @@ own -and click outside of the textarea to +in the left pane and see it rendered ' + @@ -881,63 +881,33 @@ %09%09%09%09 -%09'see +'in the pa -rsed result. Click the output to edit again +ne on the right .'), @@ -1071,17 +1071,16 @@ to ' +%0A -%09 %09%09%09%09'see
8b333abd75138b854f7e729843088735aa41a1d9
Add license text
lib/globalize.js
lib/globalize.js
var path = require('path'); var SG = require('strong-globalize'); SG.SetRootDir(path.join(__dirname, '..'), {autonomousMsgLoading: 'all'}); module.exports = SG();
JavaScript
0.000001
@@ -1,12 +1,235 @@ +// Copyright IBM Corp. 2016. All Rights Reserved.%0A// Node module: loopback-connector-ibmdb%0A// This file is licensed under the Artistic License 2.0.%0A// License text available at https://opensource.org/licenses/Artistic-2.0%0A%0A var path = r
bd6e1ea40607b8ec35e65b12e5bf8801e4782926
Main is an abstract state
custom/gnap-angular/app/main/routes.config.js
custom/gnap-angular/app/main/routes.config.js
(function () { angular .module('gnap-example-app') .config(mainRouteConfig); mainRouteConfig.$inject = ['$stateProvider']; function mainRouteConfig($stateProvider) { $stateProvider .state('main', { templateUrl: 'app/main/main.html', controller: 'MainController' }); }; })();
JavaScript
0.999056
@@ -241,16 +241,48 @@ ain', %7B%0A + abstract: true,%0A
ba913c7f5dd2336eb945094c663bd4f8e40be8c6
fix typo
ChartGenerator/Repositories/UploadRepository.js
ChartGenerator/Repositories/UploadRepository.js
let Promise = require('bluebird') let model = require('../connect') let upload = function (id, table, path, field) { return new Promise((resolve, reject) => { model.knex(table + id).del().then(() => { let query = 'alter table ' + table + id + ' auto_increament = 1' return model.knex.raw(query) }).then(() => { let query = 'load data local infile \'' + path + '\' into table ' + table + id + ' (' + field + ')' return model.knex.raw(query) }).then(() => { resolve() }).catch(error => { console.log(error) reject() }) }) } module.exports = { upload: upload }
JavaScript
0.999991
@@ -256,23 +256,22 @@ + ' -auto_increament +AUTO_INCREMENT = 1
65ecb1ba9f3f5bda65cfe2972d93a6f47b0e5f3d
add existsPlugin
bin/use.js
bin/use.js
var path = require('path'); var os = require('os'); var util = require('util'); var cp = require('child_process'); var fs = require('fs'); var colors = require('colors/safe'); var fse = require('fs-extra2'); var getPluginPaths = require('../lib/plugins/module-paths').getPaths; /*eslint no-console: "off"*/ var pluginPaths = getPluginPaths(); var MAX_RULES_LEN = 1024 * 16; var CHECK_RUNNING_CMD = process.platform === 'win32' ? 'tasklist /fi "PID eq %s" | findstr /i "node.exe"' : 'ps -f -p %s | grep "node"'; function getHomedir() { //默认设置为`~`,防止Linux在开机启动时Node无法获取homedir return (typeof os.homedir == 'function' ? os.homedir() : process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME']) || '~'; } function isRunning(pid, callback) { pid ? cp.exec(util.format(CHECK_RUNNING_CMD, pid), function (err, stdout, stderr) { callback(!err && !!stdout.toString().trim()); }) : callback(false); } function showStartWhistleTips(storage) { console.log(colors.red('Please execute `w2 start' + (storage ? ' -S ' + storage : '') + '` to start whistle first.')); } function handleRules(filepath, callback, port) { var getRules = require(filepath); if (typeof getRules !== 'function') { return callback(getRules); } getRules(callback, { port: port, checkPlugin: checkPlugin }); } function getString(str) { return typeof str !== 'string' ? '' : str.trim(); } function checkPlugin(name) { if (!name || typeof name !== 'string') { return false; } for (var i, len = pluginPaths.length; i < len; i++) { try { if (fs.statSync(path.join(pluginPaths[i], name)).isDirectory()) { return true; } } catch(e) {} } } module.exports = function(filepath, storage) { var dataDir = path.resolve(getHomedir(), '.startingAppData'); var configFile = path.join(dataDir, encodeURIComponent('#' + (storage ? storage + '#' : ''))); if (!fs.existsSync(configFile)) { return showStartWhistleTips(storage); } var pid, options; try { var config = fse.readJsonSync(configFile); options = config.options; pid = options && config.pid; } catch(e) {} isRunning(pid, function(running) { if (!running) { return showStartWhistleTips(storage); } filepath = path.resolve(filepath || '.whistle.js'); var port = options.port > 0 ? options.port : 8899; handleRules(filepath, function(result) { if (!result) { console.log(colors.red('name and rules cannot be empty.')); return; } var name = getString(result.name); if (!name || name.length > 64) { console.log(colors.red('name cannot be empty and the length cannot exceed 64 characters.')); return; } var rules = getString(result.rules); if (rules.length > MAX_RULES_LEN) { console.log(colors.red('rules cannot be empty and the size cannot exceed 16k.')); return; } console.log(colors.green('[127.0.0.1:' + port + '] Setting successful.')); }, port); }); };
JavaScript
0
@@ -1302,21 +1302,22 @@ -check +exists Plugin: chec @@ -1312,21 +1312,22 @@ Plugin: -check +exists Plugin%0A @@ -1428,13 +1428,14 @@ ion -check +exists Plug @@ -1522,16 +1522,20 @@ r (var i + = 0 , len = @@ -1703,21 +1703,34 @@ %7B%7D%0A %7D%0A -%7D%0A + return false;%0A%7D%0A %0Amodule.
c9741e1e6dd01c987bd8f139c8359984dc4340f4
Switch to Bootstrap 4.4.1 (#4571)
scripts/benchmark-rule.js
scripts/benchmark-rule.js
'use strict'; /* eslint-disable no-console */ const Benchmark = require('benchmark'); const chalk = require('chalk'); const got = require('got'); const normalizeRuleSettings = require('../lib/normalizeRuleSettings'); const postcss = require('postcss'); const requireRule = require('../lib/requireRule'); const ruleName = process.argv[2]; const ruleOptions = process.argv[3]; const ruleContext = process.argv[4]; const ruleFunc = requireRule(ruleName); if (!ruleFunc) { throw new Error('You must specify a valid rule name'); } if (!ruleOptions) { throw new Error('You must specify rule options'); } const CSS_URL = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css'; let parsedOptions = ruleOptions; /* eslint-disable eqeqeq */ if ( ruleOptions[0] === '[' || parsedOptions === 'true' || parsedOptions === 'false' || Number(parsedOptions) == parsedOptions ) { parsedOptions = JSON.parse(ruleOptions); } /* eslint-enable eqeqeq */ const ruleSettings = normalizeRuleSettings(parsedOptions); const primary = ruleSettings[0]; const secondary = ruleSettings[1] || null; const context = ruleContext ? JSON.parse(ruleContext) : {}; const rule = ruleFunc(primary, secondary, context); const processor = postcss().use(rule); got(CSS_URL) .then((response) => { const bench = new Benchmark('rule test', { defer: true, fn: (deferred) => benchFn(response.body, () => deferred.resolve()), }); bench.on('complete', () => { console.log(`${chalk.bold('Mean')}: ${bench.stats.mean * 1000} ms`); console.log(`${chalk.bold('Deviation')}: ${bench.stats.deviation * 1000} ms`); }); bench.run(); }) .catch((error) => console.log('error:', error)); let firstTime = true; function benchFn(css, done) { processor .process(css, { from: undefined }) .then((result) => { if (firstTime) { firstTime = false; result.messages .filter((m) => m.stylelintType === 'invalidOption') .forEach((m) => { console.log(chalk.bold.yellow(`>> ${m.text}`)); }); console.log(`${chalk.bold('Warnings')}: ${result.warnings().length}`); } done(); }) .catch((err) => { console.log(err.stack); done(); }); } /* eslint-enable no-console */
JavaScript
0.000002
@@ -628,14 +628,17 @@ s:// -maxcdn +stackpath .boo @@ -665,13 +665,13 @@ rap/ -3.3.6 +4.4.1 /css
8ca13d62c489727fba132c0d010ded17e6168a3b
Fix load plugin
GameCenterPlugin.js
GameCenterPlugin.js
(function(window) { var GameCenter = function() { if(!localStorage.getItem('GameCenterLoggedin')) { cordova.exec("GameCenterPlugin.authenticateLocalPlayer"); } }; GameCenter.prototype = { authenticate: function() { cordova.exec("GameCenterPlugin.authenticateLocalPlayer"); }, showLeaderboard: function(category) { cordova.exec("GameCenterPlugin.showLeaderboard", category); }, reportScore: function(category, score) { cordova.exec("GameCenterPlugin.reportScore", category, score); }, showAchievements: function() { cordova.exec("GameCenterPlugin.showAchievements"); }, getAchievement: function(category) { cordova.exec("GameCenterPlugin.reportAchievementIdentifier", category, 100); }, }; GameCenter._userDidLogin = function() { localStorage.setItem('GameCenterLoggedin', 'true'); }; GameCenter._userDidSubmitScore = function() { alert('score submitted'); }; GameCenter._userDidFailSubmitScore = function() { alert('score error'); }; if(!window.plugins) window.plugins = {}; window.plugins.gamecenter = new GameCenter(); })(window);
JavaScript
0.000001
@@ -1052,16 +1052,56 @@ ;%0A %7D;%0A%0A + cordova.addConstructor(function() %7B%0A if(!wi @@ -1135,16 +1135,18 @@ s = %7B%7D;%0A + window @@ -1185,16 +1185,22 @@ nter();%0A + %7D);%0A %7D)(windo
fab44a50e336593152d341b181be09b28c4e2eb1
Update anti_spam.js
node_modules/discord-anti-spam/anti_spam.js
node_modules/discord-anti-spam/anti_spam.js
const authors = []; var warned = []; var banned = []; var messagelog = []; /** * Add simple spam protection to your discord server. * @param {Bot} bot - The discord.js CLient/bot * @param {object} options - Optional (Custom configuarion options) * @return {[type]} [description] */ module.exports = function (bot, options) { // Set options const warnBuffer = (options && options.prefix) || 7; const maxBuffer = (options && options.prefix) || 20; const interval = (options && options.interval) || 1000; const warningMessage = (options && options.warningMessage) || "stop spamming or I'll whack your head off."; const banMessage = (options && options.banMessage) || "has been banned for spamming, anyone else?"; const maxDuplicatesWarning = (options && options.duplicates || 7); const maxDuplicatesBan = (options && options.duplicates || 20); bot.on('message', msg => { if(msg.author.id != bot.user.id){ var now = Math.floor(Date.now()); authors.push({ "time": now, "author": msg.author.id }); messagelog.push({ "message": msg.content, "author": msg.author.id }); // Check how many times the same message has been sent. var msgMatch = 0; for (var i = 0; i < messagelog.length; i++) { if (messagelog[i].message == msg.content && (messagelog[i].author == msg.author.id) && (msg.author.id !== bot.user.id)) { msgMatch++; } } // Check matched count if (msgMatch == maxDuplicatesWarning && !warned.includes(msg.author.id)) { warn(msg, msg.author.id); } if (msgMatch == maxDuplicatesBan && !banned.includes(msg.author.id)) { ban(msg, msg.author.id); } matched = 0; for (var i = 0; i < authors.length; i++) { if (authors[i].time > now - interval) { matched++; if (matched == warnBuffer && !warned.includes(msg.author.id)) { warn(msg, msg.author.id); } else if (matched == maxBuffer) { if (!banned.includes(msg.author.id)) { ban(msg, msg.author.id); } } } else if (authors[i].time < now - interval) { authors.splice(i); warned.splice(warned.indexOf(authors[i])); banned.splice(warned.indexOf(authors[i])); } if (messagelog.length >= 200) { messagelog.shift(); } } } }); /** * Warn a user * @param {Object} msg * @param {string} userid userid */ function warn(msg, userid) { warned.push(msg.author.id); msg.channel.send("Stop spamming, " + msg.author + " continuing to spam will subsequently lead into a mute."); } /** * Ban a user by the user id * @param {Object} msg * @param {string} userid userid * @return {boolean} True or False */ }
JavaScript
0.000004
@@ -291,16 +291,55 @@ on%5D%0A */%0A +const Discord = require('discord.js');%0A module.e @@ -904,16 +904,595 @@ %7C%7C 20); +%0A const muteRole = client.guilds.get(message.guild.id).roles.find('name', %60SendMessage%60);%0A const modlog = client.channels.find('name', 'mod-log');%0A %0A const embed = new Discord.RichEmbed()%0A .setTimestamp()%0A .setColor(0x00ff00)%0A .setTitle(%22User Auto Muted%22)%0A .setThumbnail(%60$%7Buser.avatarURL%7D%60)%0A .setDescription(%60%5Cn%60)%0A .addField(%22Username:%22,%60$%7Bmsg.author%7D ($%7Bmsg.author.username%7D)%60,true)%0A .addField(%22Moderator:%22,%60Pie Bot%60, true)%0A .addField(%22Reason:%22,%60%5BAuto-Mute%5D Auto muted by system for spamming.%60, false)%0A .setFooter(%60User: $%7Buser.username%7D%60,%60$%7Buser.avatarURL%7D%60); %0A%0A bot. @@ -2321,38 +2321,195 @@ -ban(msg, msg.author.id +message.guild.member(msg.author).removeRole(muteRole)%0A client.channels.get(modlog.id).send(%7Bembed%7D).catch(console.error);%0A message.channel.send(%7Bembed%7D).catch(console.error );%0A
35bc583975026ea6e8cf7b81f50a745d0447d1ed
Use mouseleave instead of mouseout
scripts/display_people.js
scripts/display_people.js
var areasToDefine = 10; var dotMax = 0; var dotMin = 0; var dotAreas = []; var showActualValue = function() { var matrixDotElem = $(this); var val = matrixDotElem.attr('value') || '0'; $('.display-count .count-value').text(val); }; var hideActualValue = function() { $('.display-count .count-value').text('-'); }; var addHoverListeners = function() { $('.matrixdot').hover(showActualValue); $('.quadrant').mouseout(hideActualValue); }; var addMatrixClasses = function() { $('.matrixdot').each(function() { var arrIsIterated = false; var className; var dotElem = $(this); var dotElemValue = parseInt(dotElem.attr('value'), 10); var elemIsBelow = false; var i = 0; while(i < dotAreas.length) { elemIsBelow = dotElemValue < dotAreas[i]; arrIsIterated = i + 1 >= dotAreas.length; if (elemIsBelow || arrIsIterated) { className = i > 0 ? 'op-' + i + '0' : 'op-0'; dotElem.addClass(className); break; } i++; } }); }; var setDotsValues = function() { var area = 0; var i = 0; var dotsValues = []; var dotsValuesAvg = 0; var dotsValuesSum = 0; $('.matrixdot').each(function() { var val = parseInt($(this).attr('value'), 10) dotsValues.push(val); dotsValuesSum += val; }); dotsValuesAvg = Math.floor(dotsValuesSum / dotsValues.length * 10) / 10; $('.display-count .avg-value').text(dotsValuesAvg); dotMax = Math.max.apply(Math, dotsValues); while (i++ < areasToDefine) { area = Math.floor(dotMax / areasToDefine * i); dotAreas.push(area); } }; var displayMaxEntry = function() { $('.display-count .max-value').text(dotMax); }; $(document).ready(setDotsValues); $(document).ready(addHoverListeners); $(document).ready(addMatrixClasses); $(document).ready(displayMaxEntry);
JavaScript
0.000001
@@ -423,11 +423,13 @@ ouse -out +leave (hid
05699f0e5f4b3fea5eb44ee20ef2d0e52b21a4bc
Use strict
openseadragon-annotations.js
openseadragon-annotations.js
(function ($) { if (!$) { throw new Error('OpenSeadragon Annotations requires OpenSeadragon'); } $.Viewer.prototype.initializeAnnotations = function (options) { var options = $.extend({ viewer: this }, options); this.addHandler('open', annotations.onOpen.bind(annotations)); this.annotations = this.annotations || annotations.initialize(options); return this; }; var annotations = { initialize: function (options) { $.extend(this, { state: move.initialize(), controls: controls.initialize({ imagePath: options.imagePath || '' }) }, options); this.controls.addHandler('add', function (button) { this.viewer.addControl(button.element, { anchor: $.ControlAnchor.BOTTOM_LEFT }); }.bind(this)); return this; }, onOpen: function () { this.overlay = overlay.initialize({ viewer: this.viewer }); this.viewer.addHandler('animation', function () { var width = this.overlay.el.clientWidth; var height = this.overlay.el.clientHeight; var viewPort = '0 0 ' + width + ' ' + height; var svg = this.overlay.el.querySelector('svg'); svg.setAttribute('viewPort', viewPort); }.bind(this)); this.controls.add('move', true).addHandler('click', function () { this.viewer.setMouseNavEnabled(true); this.state = move.initialize(); }.bind(this)); this.controls.add('draw').addHandler('click', function () { this.viewer.setMouseNavEnabled(false); this.state = draw.initialize(); }.bind(this)); this.overlay.el.addEventListener('mousedown', function (e) { this.state.handleMouseDown(e, this.overlay); }.bind(this), false); this.overlay.el.addEventListener('mouseup', function (e) { this.state.handleMouseUp(e, this.overlay); }.bind(this), false); return this; } }; var state = { initialize: function (options) { $.extend(this, options); return this; }, handleMouseDown: function () { return this; }, handleMouseUp: function () { return this; } } var move = Object.create(state); var draw = $.extend(Object.create(state), { initialize: function (options) { $.extend(this, options); this._mouseTracker = function (e) { this.x = e.offsetX; this.y = e.offsetY; }.bind(this); return this; }, handleMouseDown: function (e, overlay) { if (!this._interval) { this.x = e.offsetX; this.y = e.offsetY; var svg = overlay.el.querySelector('svg'); var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('fill', 'none'); path.setAttribute('stroke', 'red'); path.setAttribute('stroke-width', '0.5'); path.setAttribute('stroke-linejoin', 'round'); path.setAttribute('stroke-linecap', 'round'); path.setAttribute('d', 'M' + this.x / overlay.el.clientWidth * 100 + ' ' + this.y / overlay.el.clientHeight * 100); svg.appendChild(path); overlay.el.addEventListener('mousemove', this._mouseTracker, false); this._interval = window.setInterval(function () { path.setAttribute('d', path.getAttribute('d') + ' L' + this.x / overlay.el.clientWidth * 100 + ' ' + this.y / overlay.el.clientHeight * 100); }.bind(this), 25); } e.stopPropagation(); return this; }, handleMouseUp: function (e, overlay) { overlay.el.removeEventListener('mousemove', this._mouseTracker); this._interval = clearInterval(this._interval); return this; } }); var controls = $.extend(new $.EventSource(), { initialize: function (options) { $.extend(this, options); this.list = {}; this.addHandler('click', this.onClick.bind(this)); return this; }, onClick: function (name) { for (var button in this.list) { if (this.list.hasOwnProperty(button)) { if (button === name) { this.list[button].imgDown.style.visibility = 'visible'; } else { this.list[button].imgDown.style.visibility = 'hidden'; } } } return this; }, add: function (name, active) { this.list[name] = new $.Button({ tooltip: name[0].toUpperCase() + name.substr(1), srcRest: this.imagePath + name + '_rest.png', srcGroup: this.imagePath + name + '_grouphover.png', srcHover: this.imagePath + name + '_hover.png', srcDown: this.imagePath + name + '_pressed.png', onClick: this.raiseEvent.bind(this, 'click', name) }); if (active) { this.list[name].imgDown.style.visibility = 'visible'; } this.raiseEvent('add', this.list[name]); return this.list[name]; }, get: function (name) { return this.list[name]; } }); var overlay = { initialize: function (options) { $.extend(this, options); this.el = document.createElement('div'); this.el.className = 'overlay'; var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('version', '1.1'); svg.setAttribute('width', '100%'); svg.setAttribute('height', '100%'); svg.setAttribute('preserveAspectRatio', 'none'); svg.setAttribute('viewBox', '0 0 100 100') svg.style.cursor = 'default'; this.el.appendChild(svg); var width = this.viewer.viewport.homeBounds.width; var height = this.viewer.viewport.homeBounds.height; this.viewer.addOverlay(this.el, new $.Rect(0, 0, width, height)); return this; } }; })(OpenSeadragon);
JavaScript
0.000083
@@ -1,16 +1,31 @@ +'use strict';%0A%0A (function ($) %7B%0A
bef994329ec6a7db0ee2c35ef13662ad508107a8
Remove unneeded js; set standard time on scroll; fix spacing and quotes
source/javascripts/scripts.js
source/javascripts/scripts.js
function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1); var sURLVariables = sPageURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParameterName = sURLVariables[i].split('='); if (sParameterName[0] == sParam) { return sParameterName[1]; } } } $(function() { var $ci = $('#ci-subt'), $tagLine = $('#tagline'), $hireUs = $('#hire-us'), $tabs = $('#tabs'), $imageLink = $('.image-link'), $tables = $('table'), internalNavigationEvent = 'onpopstate' in window ? 'popstate' : 'hashchange'; $("input").not("[type=submit]").jqBootstrapValidation(); if (getUrlParameter('s') == 'ph' && $ci.length) { $ci.append('<br><br>Hello, Product Hunters!<br><br> Get 75% off a GitLab.com bronze subscription forever! <br> Use the code: producthunt75'); } // Consultancy if ($tagLine.length && $hireUs.length) { $tagLine.addClass('animated fadeInLeft'); $hireUs.addClass('animated bounceIn'); } // Tabs if ($tabs.length) { var current = window.location.hash; $('.tab:not(' + current +')', $tabs).hide(); window.scrollTo(0, 0); $(".dropdown-menu a").on('click', function (e) { e.preventDefault(); var selText = $(this).text(), current = $(this).attr('href'); $(this).parents('.btn-group').find('.dropdown-toggle').html(selText +' <span class="caret"></span>'); $('.tab:not(' + current +')', $tabs).hide(); $(current).show(); window.location.replace(window.location.origin + window.location.pathname + current); window.scrollTo(0, 0); $(this).dropdown('toggle'); return false; }); } if ($imageLink.length) { $imageLink.magnificPopup({ type:'image' }); } if ($tables.length) { $tables.each(function () { var $table = $(this); $(this).wrap('<div class="table-responsive"></div>'); }); } var changeScrollPosition = function () { if (window.location.hash === '' || window.location.hash.indexOf('#stq=') === 0) { return; } var hash = window.location.hash, $el = $('a[name="' + hash.replace('#', '') + '"], ' + hash + ''), extraHeight = $('.navbar-header').outerHeight(), $qnav = $('#qnav'); if ($qnav.length) { extraHeight += $qnav.outerHeight() - 2; } if ($el.length) { $(window).scrollTop($el.offset().top - extraHeight); } } $(window).on('load ' + internalNavigationEvent, function () { setTimeout(changeScrollPosition, 10); }); // Search var $search = $('.js-search'), $searchIcon = $('.js-search-icon'); $('.js-search-icon').on('click', function () { $searchIcon.parent().addClass('is-open is-focused'); setTimeout(function () { $search.focus(); }, 350); }) $search.on('keyup', function (e) { if (e.which === 13) { // Trigger a search by changing hash window.location.hash = '#stq=' + $(this).val() } }).on('focus', function () { $(this).parent().addClass('is-focused'); }).on('blur', function () { $(this).parent().removeClass('is-focused'); });; // Sticky dev cycle nav $(".cycle-icon-row").removeClass('stuck'); $(document).scroll(function(){ var navHeight = $('.navbar-fixed-top').height(); var devCycleNavHeight = $('.cycle-icon-row').height(); var $iconNav = $('.cycle-icon-row'); var scroll = $(window).scrollTop(); if ($iconNav.is(':visible')) { if (scroll > 0) { $iconNav.removeClass('stuck'); } if (scroll >= $iconNav.offset().top - navHeight) { $iconNav.addClass('stuck'); } if (scroll >= $('.idea-to-production').offset().top) { $iconNav.removeClass('stuck'); } var $currentSection; $('.cycle-vertical .step').each(function() { var divPosition = $(this).offset().top - navHeight - (devCycleNavHeight * 3.5); $('.cycle-icon-row .step').removeClass('active'); if (divPosition - 1 < scroll) { $currentSection = $(this); } if ($currentSection) { var id = $currentSection.attr("id"); $('.cycle-icon-row .step').removeClass('active'); $("[href='#" + id + "']").addClass('active'); } }) } }); // Animate scroll to icon var animateScroll = function(targetPos) { var currentPos = window.pageYOffset || document.documentElement.scrollTop; var distance = Math.abs(currentPos - targetPos); var speed = 1; var time = distance / speed; $('body,html').animate({scrollTop: targetPos}, time); }; $('.cycle-icon-row .step').click(function(e) { e.preventDefault(); var anchor = $(this).attr('href'); animateScroll($(anchor).offset().top - 200); }); });
JavaScript
0
@@ -4161,12 +4161,12 @@ ttr( -%22id%22 +'id' );%0A @@ -4181,85 +4181,26 @@ $(' -.cycle-icon-row .step').removeClass('active');%0A $(%22 +a %5Bhref= -'#%22 +%22#' + id + %22'%5D%22 @@ -4199,12 +4199,12 @@ d + -%22'%5D%22 +'%22%5D' ).ad @@ -4285,301 +4285,8 @@ con%0A - var animateScroll = function(targetPos) %7B%0A var currentPos = window.pageYOffset %7C%7C document.documentElement.scrollTop;%0A var distance = Math.abs(currentPos - targetPos);%0A var speed = 1;%0A var time = distance / speed;%0A%0A $('body,html').animate(%7BscrollTop: targetPos%7D, time);%0A %7D;%0A%0A $( @@ -4314,22 +4314,28 @@ p'). +on(' click -( +', function (e) @@ -4330,20 +4330,20 @@ function + (e) - %7B%0A e. @@ -4356,25 +4356,24 @@ tDefault();%0A -%0A var anch @@ -4407,21 +4407,51 @@ -animateScroll +$('html, body').animate(%7B%0A scrollTop: ($(a @@ -4476,16 +4476,29 @@ p - 200) +%0A %7D, 1000) ;%0A %7D);%0A
095b29e56f17c6c2b065e7efb62fa707cd0e35d0
Rename `context` to `qualifier`.
prolific.logger/logger.js
prolific.logger/logger.js
var prolific = require('prolific') function Logger (context) { this.context = context this._path = ('.' + context).split('.') } ; [ 'error', 'warn', 'info', 'debug', 'trace' ].forEach(function (level) { Logger.prototype[level] = function (name, properties) { prolific.json(this._path, level, this.context, name, properties) } }) Logger.createLogger = function (context) { return new Logger(context) } module.exports = Logger
JavaScript
0.000073
@@ -46,23 +46,25 @@ Logger ( -context +qualifier ) %7B%0A @@ -72,25 +72,29 @@ his. -context = context +qualifier = qualifier %0A @@ -114,23 +114,25 @@ ('.' + -context +qualifier ).split( @@ -320,23 +320,25 @@ l, this. -context +qualifier , name,
a0f8b1e72bab4738006a790364ab66d24b8cd917
fix template literals.
tests/functional_test.js
tests/functional_test.js
/* eslint no-undefined: 0 */ 'use strict'; const path = require('path'); const assert = require('assert'); const https = require('https'); const walk = require('fs-walk'); const async = require('async'); const semver = require('semver'); const digest = require('../lib/helpers.js').sri.digest; const helpers = require('./test_helper.js'); const config = helpers.config(); const expectedHeaders = { 'accept-ranges': 'bytes', 'access-control-allow-origin': '*', 'cache-control': undefined, 'connection': 'Keep-Alive', 'content-length': undefined, 'content-type': undefined, 'date': undefined, 'etag': undefined, 'last-modified': undefined, 'vary': 'Accept-Encoding', 'x-cache': undefined, 'x-hello-human': 'Say hello back! @getBootstrapCDN on Twitter' }; const responses = {}; function request(uri, cb) { // return memoized response to avoid making the same http call twice if (Object.prototype.hasOwnProperty.call(responses, uri)) { return cb(responses[uri]); } // build memoized response return helpers.preFetch(uri, (res) => { responses[uri] = res; cb(res); }, https); } function assertSRI(uri, sri, done) { request(uri, (response) => { assert.equal(200, response.statusCode); const expected = digest(response.body, true); assert.equal(expected, sri); done(); }); } const s3include = ['content-type']; function assertHeader(uri, header, value) { if (typeof process.env.TEST_S3 !== 'undefined' && !s3include.includes(header)) { it.skip(`has ${header}`); } else { it(`has ${header}`, (done) => { request(uri, (response) => { assert.equal(200, response.statusCode); assert(Object.prototype.hasOwnProperty.call(response.headers, header), 'Expected: ${header} in: ${Object.keys(response.headers).join(", ")}'); if (typeof value !== 'undefined') { assert.equal(response.headers[header], value); } else if (expectedHeaders[header]) { assert.equal(response.headers[header], expectedHeaders[header]); } done(); }); }); } } describe('functional', () => { config.bootstrap.forEach((self) => { describe(helpers.domainCheck(self.javascript), () => { const uri = helpers.domainCheck(self.javascript); Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'application/javascript; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, self.javascriptSri, done); }); }); describe(helpers.domainCheck(self.stylesheet), () => { const uri = helpers.domainCheck(self.stylesheet); Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'text/css; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, self.stylesheetSri, done); }); }); }); describe('bootswatch3', () => { config.bootswatch3.themes.forEach((theme) => { const uri = helpers.domainCheck(config.bootswatch3.bootstrap .replace('SWATCH_VERSION', config.bootswatch3.version) .replace('SWATCH_NAME', theme.name)); describe(uri, () => { Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'text/css; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, theme.sri, done); }); }); }); }); describe('bootswatch4', () => { config.bootswatch4.themes.forEach((theme) => { const uri = helpers.domainCheck(config.bootswatch4.bootstrap .replace('SWATCH_VERSION', config.bootswatch4.version) .replace('SWATCH_NAME', theme.name)); describe(uri, () => { Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'text/css; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, theme.sri, done); }); }); }); }); describe('bootlint', () => { config.bootlint.forEach((self) => { const uri = helpers.domainCheck(self.javascript); describe(uri, () => { Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'application/javascript; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, self.javascriptSri, done); }); }); }); }); describe('fontawesome', () => { config.fontawesome.forEach((self) => { const uri = helpers.domainCheck(self.stylesheet); describe(uri, () => { Object.keys(expectedHeaders).forEach((header) => { assertHeader(uri, header); }); assertHeader(uri, 'content-type', 'text/css; charset=utf-8'); it('has integrity', (done) => { assertSRI(uri, self.stylesheetSri, done); }); }); }); }); describe('public/**/*.*', () => { // Build File List const whitelist = [ 'bootlint', 'bootstrap', 'bootswatch', 'font-awesome', 'twitter-bootstrap', 'css', 'js' ]; const publicURIs = []; walk.filesSync(path.join(__dirname, '..', 'public'), (base, name) => { let root = base.split(`${path.sep}public${path.sep}`)[1]; // ensure file is in whitelisted directory if (typeof root === 'undefined' || !whitelist.includes(root.split(path.sep)[0])) { return; } // replace Windows backslashes with forward ones root = root.replace(/\\/g, '/'); const domain = helpers.domainCheck('https://stackpath.bootstrapcdn.com/'); const uri = `${domain + root}/${name}`; const ext = helpers.extension(name); // ignore unknown / unsupported types if (typeof helpers.CONTENT_TYPE_MAP[ext] === 'undefined') { return; } // ignore twitter-bootstrap versions after 2.3.2 if (uri.includes('twitter-bootstrap')) { const m = uri.match(/(\d+\.\d+\.\d+)/); // err on the side of testing things that can't be abstracted if (m && m[1] && semver.valid(m[1]) && semver.gt(m[1], '2.3.2')) { return; // don't add the file } } publicURIs.push(uri); }); // Run Tests async.eachSeries(publicURIs, (uri, callback) => { describe(uri, () => { it('content-type', (done) => { request(uri, (response) => { assert.equal(200, response.statusCode, 'file missing or forbidden'); helpers.assert.contentType(uri, response.headers['content-type']); done(); callback(); }); }); }); }); }); });
JavaScript
0
@@ -1896,17 +1896,17 @@ -' +%60 Expected @@ -1962,15 +1962,15 @@ oin( -%22, %22)%7D' +', ')%7D%60 );%0A%0A
9a29cf1bd0a38741d37e66168ba3c3a48d3e1f55
Stop logging full websocket buffer to fix infinite loop
src/legacy/js/classes/_websocket.js
src/legacy/js/classes/_websocket.js
var websocket = { socket: null, retrySocketDelay: 1, buffer: new Map(), messageCounter: 0, hasConnected: false, reconnectAttempts: 0, open: function() { console.info("Trying to open websocket..."); websocket.socket = new WebSocket(location.protocol.replace(/^http/, 'ws') + location.host + "/florence/websocket"); websocket.reconnectAttempts++; websocket.socket.onopen = function() { console.info("Websocket has been opened"); websocket.hasConnected = true; websocket.retrySocketDelay = 1; websocket.buffer.forEach(function(message) { websocket.socket.send(message); }); // FIXME we should be logging that the socket is open - but there's a horrible cyclical dependency on startup atm } websocket.socket.onerror = function() { console.error("Error opening websocket"); } websocket.socket.onmessage = function(message) { message = JSON.parse(message.data); if (message.type === "version") { // TODO Not being used yet to check version but should replace existing implementation at some point Florence.version = message.payload.version; return; } if (message.type !== "ack") { return; } websocket.buffer.delete(parseInt(message.payload)); } websocket.socket.onclose = function() { console.info("Websocket has been closed"); websocket.retrySocketDelay *= 2; if (websocket.retrySocketDelay >= 300000) { websocket.retrySocketDelay = 300000; } if (!websocket.hasConnected && websocket.reconnectAttempts >= 100) { console.info("Unable to connect websocket after 100 attempts, so stop retrying websocket"); return; } setTimeout(() => { // setTimeout sets 'this' to window wrapping 'this.open()' in a lambda function // (rather than passing it inline), stops it. // Ref: https://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback websocket.open(); }, websocket.retrySocketDelay); } }, send: function(message) { websocket.messageCounter++; message = websocket.messageCounter + ":" + message; if (websocket.buffer.size >= 50) { console.warn(`Websocket buffer has reached it's limit, so message will not be sent to server. Message: \n`, message); log.add(log.eventTypes.socketBufferFull); // This has to be excluded from being sent to the server or else we'll have an infinite loop return; } websocket.buffer.set(websocket.messageCounter, message); if (websocket.socket.readyState === 1) { websocket.socket.send(message); } } };
JavaScript
0.000013
@@ -2686,16 +2686,18 @@ +// log.add(
d9a37d8dbbc30730c28194826e390bca24170e6d
修改 context 参数类型
src/base.js
src/base.js
define(function (require, exports, module) { /** * 基类 * * @module Base */ 'use strict'; var Class = require('class'), Events = require('events'); var Aspect = require('./aspect'); /** * 基类 * * 实现 事件订阅 与 Aspect (AOP) * * @class Base * @constructor * @implements Events * @implements Aspect * * @example * ``` * // 创建子类 * var SomeBase = Base.extend({ * someMethod: function () { * this.fire('someEvent'); * } * }); * // 实例化 * var someBase = new SomeBase({ * events: { * someEvent: function () { * console.log('someEvent fired'); * } * } * }); * // 调用方法 * someBase.someMethod(); * // 控制台将输出: * // someEvent fired * ``` */ var Base = Class.create({ /** * 初始化函数,将自动执行;执行参数初始化与订阅事件初始化 * * @method initialize * @param {Object} options 参数 */ initialize: function (options) { Base.superclass.initialize.apply(this, arguments); // 初始化参数 this.__options = mergeDefaults(this, options || {}); // 初始化订阅事件 this.initEvents(); }, mixins: [Events.prototype, Aspect.prototype], /** * 默认参数,子类自动继承并覆盖 * * @property {Object} defaults * @type {Object} */ defaults: { }, /** * 存取状态 * * @method state * @param {Number} [state] 状态值 * @return {Mixed} 当前状态值或当前实例 */ state: function (state) { if (state === undefined) { return this.__state; } this.__state = state; return this; }, /** * 存取初始化后的数据/参数,支持多级存取, * 如:this.option('rules/remote') 对应于 { rules: { remote: ... } } * * @method option * @param {String} [key] 键 * @param {Mixed} [value] 值 * @param {Object} [context] 上下文 * @return {Mixed} 整个参数列表或指定参数值 */ option: function (key, value, context, override) { var options = context || this.__options; if (key === undefined) { return options; } function get () { var keyArr = key.split('/'); while ((key = keyArr.shift())) { if (options.hasOwnProperty(key)) { options = options[key]; } else { return undefined; } } return options; } function set () { var keyMap = {}; function recruit (obj, arr) { key = arr.shift(); if (key) { obj[key] = recruit({}, arr); return obj; } return value; } recruit(keyMap, key.split('/')); copy(options, keyMap, override); } function isObj (obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } function copy (target, source, override) { var p, obj; for (p in source) { obj = source[p]; if (!override && isObj(obj)) { isObj(target[p]) || (target[p] = {}); copy(target[p], obj, false); } else { target[p] = obj; } } } if (isObj(key)) { copy(options, key, override); } else { if (value === undefined) { return get(); } else { set(); } } return this; }, /** * 事件订阅,以及AOP * * @method initEvents * @param {Object|Function} [events] 事件订阅列表 * @return {Object} 当前实例 */ initEvents: function (events) { var self = this; events || (events = this.option('events')); if (!events) { return this; } $.each(events, function (event, callback) { var match; if (typeof callback === 'string') { callback = self[callback]; } if (typeof callback !== 'function') { return true; } match = /^(before|after):(\w+)$/.exec(event); if (match) { // AOP self[match[1]](match[2], callback); } else { // Subscriber self.on(event, callback); } }); return this; }, /** * 销毁当前组件实例 * @method destroy */ destroy: function () { var prop; // 移除事件订阅 this.off(); // 移除属性 for (prop in this) { if (this.hasOwnProperty(prop)) { delete this[prop]; } } this.destroy = function() { }; } }); function mergeDefaults(instance, options) { var arr = [options], proto = instance.constructor.prototype; while (proto) { if (proto.hasOwnProperty('defaults')) { arr.unshift(proto.defaults); } proto = proto.constructor.superclass; } arr.unshift(true, {}); return $.extend.apply(null, arr); } module.exports = Base; });
JavaScript
0.000001
@@ -1624,22 +1624,22 @@ @param %7B -Object +String %7D %5Bconte @@ -1765,18 +1765,43 @@ context -%7C%7C +? this.__options%5Bcontext%5D : this.__
948f797a7129bcad17ed03de23c5f59c9ab182ae
clean up repetitive styles
GraphQLWebClient.js
GraphQLWebClient.js
import React from 'react'; import GraphQLQueryInput from './GraphQLQueryInput'; import GraphQLQueryResults from './GraphQLQueryResults'; var parentDivStyle = { display: "flex", flexWrap: "wrap" }; var divStyle = { margin: "auto", width: "49%", border: "1px dotted #ccc" }; var divStyleQuerying = { margin: "auto", width: "49%", border: "1px solid #aaa" }; var divStylePreQuerying = { margin: "auto", width: "49%", border: "1px solid #000" }; var styles = [divStyle, divStylePreQuerying, divStyleQuerying]; export default class GraphQLWebClient extends React.Component { defaultProps: { extraheaders: [] } constructor(props) { super(props); this.state = { query: this.props.defaultQuery, queryState: 0, response: `(no response received yet)` }; this.queryEvent = null; this.queryDelay = 500; this.xhr = null; } onInputChange(value) { window.location.hash = value; this.setState({query: value}); if (this.props.autoRun) {this.queryBackend(); } } componentDidMount() { this.queryBackend(); } componentWillReceiveProps(nextProps) { if (nextProps.defaultQuery !== this.props.defaultQuery) { this.setState({query: nextProps.defaultQuery}); } if (!this.props.autoRun && nextProps.autoRun) {this.queryBackend(); } } setQueryState(newState) { if (this.props.onQueryState) { this.props.onQueryState(newState); } this.setState({queryState: newState}); } queryBackend() { var queryDelay = this.queryDelay; if (this.queryEvent !== null) { clearTimeout(this.queryEvent); } if (this.xhr !== null) { this.xhr.abort(); } else { queryDelay = 0; } this.setQueryState(1); this.queryEvent = setTimeout(() => { this.setQueryState(2); var xhr = new XMLHttpRequest(); xhr.open('get', `${this.props.endpoint}?q=${encodeURIComponent(this.state.query)}`, true); xhr.setRequestHeader('X-Trace-Id', '1'); if (this.props.showParseResult) { xhr.setRequestHeader('X-GraphQL-Only-Parse', '1'); } this.props.extraHeaders.forEach((h) => { xhr.setRequestHeader(h[0], h[1]); }); xhr.onload = () => { this.setState({response: xhr.responseText}); this.setQueryState(0); }; xhr.send(); this.xhr = xhr; }, queryDelay); } render() { return ( <div style={parentDivStyle}> <div style={divStyle}> <GraphQLQueryInput query={this.state.query} onChange={this.onInputChange.bind(this)} /> </div> <div style={styles[this.state.queryState]}> <GraphQLQueryResults results={this.state.response} /> </div> </div> ); } }
JavaScript
0.000002
@@ -305,44 +305,8 @@ = %7B -%0A margin: %22auto%22,%0A width: %2249%25%22,%0A bor @@ -326,17 +326,17 @@ id #aaa%22 -%0A + %7D;%0Avar d @@ -361,44 +361,8 @@ = %7B -%0A margin: %22auto%22,%0A width: %2249%25%22,%0A bor @@ -382,20 +382,110 @@ id #000%22 -%0A + %7D;%0A +Object.assign(divStyleQuerying, divStyle);%0AObject.assign(divStylePreQuerying, divStyle);%0A%0A var styl
4b4f33d6e5bced25e2c883efe28ec354826503f7
Annotate that Impromptu extends EventEmitter.
lib/impromptu.js
lib/impromptu.js
var EventEmitter = require('events').EventEmitter var fs = require('fs') var path = require('path') var util = require('util') var _ = require('underscore') // Load our own package.json var npmConfig = require('../package.json') /** * The base Impromptu class. * @constructor */ function Impromptu() { EventEmitter.call(this) this.config = new Impromptu.Config() this.config.set('root', Impromptu.DEFAULT_CONFIG_DIR) this.log = new Impromptu.Log(this) this.color = new Impromptu.Color(this) this.repository = new Impromptu.RepositoryFactory(this) this.db = new Impromptu.DB(this) this.module = new Impromptu.ModuleFactory(this) this.plugin = new Impromptu.PluginFactory(this) this.prompt = new Impromptu.Prompt(this) this.setMaxListeners(200) } util.inherits(Impromptu, EventEmitter) Impromptu.VERSION = npmConfig.version Impromptu.DEFAULT_CONFIG_DIR = process.env.IMPROMPTU_DIR || ("" + process.env.HOME + "/.impromptu") // Utilities. Impromptu.Config = require('./config') Impromptu.Error = require('./error') Impromptu.exec = require('./exec') // APIs. Impromptu.Color = require('./color') Impromptu.Cache = require('./cache/base') Impromptu.Cache.Shim = require('./cache/shim') Impromptu.Cache.Instance = require('./cache/instance') Impromptu.Cache.Global = require('./cache/global') Impromptu.Cache.Directory = require('./cache/directory') Impromptu.Cache.Repository = require('./cache/repository') Impromptu.DB = require('./db') Impromptu.Log = require('./log') Impromptu.ModuleFactory = require('./module') Impromptu.PluginFactory = require('./plugin') Impromptu.Prompt = require('./prompt') Impromptu.RepositoryFactory = require('./repository') Impromptu.prototype.version = function() { return Impromptu.VERSION } Impromptu.prototype.exec = Impromptu.exec Impromptu.prototype.load = function() { // Ensure the prompt is compiled. // Double-check that nothing has changed since Impromptu was instantiated. if (!this._compilePrompt()) return this // Load the prompt file. try { var prompt = require(this.path('compiledPrompt')) if (typeof prompt.call === 'function') { this._prompt = prompt } else { this._error('needs-function', 'Your prompt file should export a function.', new Error()) } } catch (err) { this._error('javascript', 'Your prompt file triggered a JavaScript error.', err) } } Impromptu.prototype.build = function(done) { if (this._prompt) { try { this.emit('build') this._prompt.call(this, Impromptu, this.prompt.section) } catch (err) { this._error('javascript', 'Your prompt method triggered a JavaScript error.', err) } } this.prompt.build(done) return this } Impromptu.prototype.refresh = function(done) { this.emit('refresh') return this } Impromptu.prototype.fallback = function(message) { message = message ? '[' + message + '] ' : '' return message + (process.cwd()) + ' $ ' } Impromptu.prototype.path = function (name) { var root = this.config.get('root') switch (name) { case 'root': return root case 'sources': return [root + '/prompt.coffee', root + '/prompt.js'] case 'tmp': return root + '/tmp' case 'compiledPrompt': return this.path('tmp') + '/prompt.js' case 'log': return root + '/impromptu-debug.log' case 'serverPid': var serverId = this.config.get('serverId') return serverId ? this.path('tmp') + '/server-' + serverId + '.pid' : '' case 'nodeModules': return root + '/node_modules' } } // Returns true if the compiled prompt file exists. Impromptu.prototype._compilePrompt = function() { var sourcePromptPath = _.find(this.path('sources'), function(path) { return fs.existsSync(path) }) // Make sure we have a source prompt. // If we don't find a prompt file, bail. if (!sourcePromptPath) return false // Check whether the compiled prompt exists and is up to date. var compiledPromptPath = this.path('compiledPrompt') if (fs.existsSync(compiledPromptPath)) { var sourceMtime = fs.statSync(sourcePromptPath).mtime var compiledMtime = fs.statSync(compiledPromptPath).mtime if (sourceMtime < compiledMtime) return true } // Ensure the compiled prompt directory exists. var compiledDir = path.dirname(compiledPromptPath) if (!fs.existsSync(compiledDir)) fs.mkdir(compiledDir) // If your prompt is already JS, just copy it over. if (/\.js$/.test(sourcePromptPath)) { fs.createReadStream(sourcePromptPath).pipe(fs.createWriteStream(compiledPromptPath)) return true // If you're using CoffeeScript, load the CoffeeScript module to compile and cache it. } else if (/\.coffee$/.test(sourcePromptPath)) { // Clear any pre-existing CoffeeScript compiler errors. // We only care about whether the most recent compilation succeeded. this._clearError('coffeescript') // Allow `.coffee` files in `require()`. var coffee = require('coffee-script') try { var compiledJs = coffee.compile(fs.readFileSync(sourcePromptPath).toString()) fs.writeFileSync(compiledPromptPath, compiledJs) return true } catch (err) { this._error('coffeescript', 'Your prompt file is not valid CoffeeScript.', err) } return false } } Impromptu.prototype._error = function(name, content, err) { this.prompt.section("error:message:" + name, { content: content, background: 'red', foreground: 'white' }) this.prompt.section("error:instructions:" + name, { content: "\nDetails can be found in " + this.path('log') + "\n", options: { newlines: true } }) this.log.error(content, err) } Impromptu.prototype._clearError = function(name) { this.prompt.section("error:message:" + name, { content: '' }) this.prompt.section("error:instructions:" + name, { content: '' }) } /** * Expose an instance of Impromptu by default. * * For testing, we can override the global instance using the `setGlobalInstance` method. * Otherwise, you should just treat this instance as global, as if the following block read: * `module.exports = new Impromptu()` */ ; (function () { var globalImpromptuInstance = new Impromptu() Impromptu.prototype.setGlobalImpromptu = function (impromptuInstance) { if (impromptuInstance instanceof Impromptu) { globalImpromptuInstance = impromptuInstance } } Object.defineProperty(module, 'exports', { get: function () { return globalImpromptuInstance } }) }())
JavaScript
0
@@ -1,24 +1,18 @@ var -E +e vent -Emitter +s = requi @@ -27,21 +27,8 @@ ts') -.EventEmitter %0Avar @@ -255,16 +255,50 @@ tructor%0A + * @extends %7Bevents.EventEmitter%7D%0A */%0Afunc @@ -318,16 +318,23 @@ u() %7B%0A +events. EventEmi @@ -816,16 +816,23 @@ romptu, +events. EventEmi
c5fcba8fb7a34d4b9d3615dedd3f1191abd4e416
fix the fetch question select option
scripts/fetch-question.js
scripts/fetch-question.js
const { writeFileSync, closeSync, openSync } = require('fs'); const { execSync } = require('child_process'); const { resolve } = require('path'); const { get } = require('request'); const { load } = require('cheerio'); const { prompt } = require('inquirer'); const { info } = require('better-console'); const { clearConsole, traverseNode, unicodeToChar, createFiles } = require('./file-utils.js'); const ALGORITHM_URL = `https://leetcode.com/api/problems/algorithms/`; const QUESTION_URL = slug => `https://leetcode.com/problems/${slug}/`; const SUBMISSION_PATH = slug => resolve(__dirname, `../submissions/*${slug}.js`); const difficultyMap = { 1: 'Easy', 2: 'Medium', 3: 'Hard' }; const questionTitle = question => { let { difficulty, paid_only, stat } = question; let { question_id, question__title, total_acs, total_submitted } = stat; let { level } = question.difficulty; return `${question_id}\t${difficultyMap[level]}\t${(total_acs / total_submitted * 100).toString().slice(0, 4)}%\t${question__title}`; }; const questionOption = question => { let { paid_only, stat } = question; if (paid_only) return { name: questionTitle(question), disabled: 'Paid only' }; let { question__article__slug, question__title_slug } = stat; let slug = question__title_slug || question__article__slug; try { execSync(`ls ${SUBMISSION_PATH(slug)}`, { stdio: 'ignore' }); return { name: questionTitle(question), disabled: 'Solved' }; } catch (e) { return questionTitle(question); }; }; const mapTitleToQuestion = questions => questions.reduce((pre, curr) => { pre[questionTitle(curr)] = curr; return pre; }, {}); const getQuestions = url => new Promise((resolve, reject) => { get(url).on('response', res => { res.setEncoding('utf8'); let chunk = ''; res.on('data', data => chunk += data); res.on('error', err => reject(err)); res.on('end', () => resolve(JSON.parse(chunk).stat_status_pairs)); }); }); const showQuestionSelection = questions => { titleQuestionMap = mapTitleToQuestion(questions); return prompt({ type : 'list', name : 'title', message : 'Which problem do you want to solve?', choices : questions.map(questionOption) }); }; const getInfosFromPagedata = $ => { eval($('script').toArray().find(elem => { return elem.children.length && elem.children[0].data.includes('pageData'); }).children[0].data); return { slug : pageData.questionTitleSlug, code : pageData.codeDefinition.find(definition => 'javascript' === definition.value).defaultCode, description : $('meta[name=description]')[0].attribs['content'] }; }; const getQuestionContent = title => new Promise((resolve, reject) => { let question = titleQuestionMap[title]; let { question__article__slug, question__title_slug } = question.stat; let selectedQuestionSlug = question__title_slug || question__article__slug; get(QUESTION_URL(selectedQuestionSlug)).on('response', res => { let chunk = ''; res.on('data', data => chunk += data); res.on('error', err => reject(err)); res.on('end', () => { resolve(getInfosFromPagedata(load(chunk))); }); }); }); const actionToQuestion = question => { let { slug, code, description } = question; info(`\n${description}`); prompt({ type : 'list', name : 'action', message : 'Do you want to solve the problem?', choices : ['Yes', 'No'] }).then(answer => { switch (answer.action) { case 'Yes': createFiles(slug, code); return; case 'No': SelectAndSolve(); return; default: return; } }); }; const SelectAndSolve = () => { clearConsole(); getQuestions(ALGORITHM_URL).then( questions => showQuestionSelection(questions), err => Promise.reject(err) ).then( answer => getQuestionContent(answer.title), err => Promise.reject(err) ).then( question => actionToQuestion(question) ); }; SelectAndSolve();
JavaScript
0.999866
@@ -594,18 +594,15 @@ %60../ -submission +problem s/*$ @@ -607,16 +607,22 @@ *$%7Bslug%7D +/index .js%60);%0A%0A