commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
aab260ab6dc15fe3b39dd5a29ea6fa9bd57decba
shoot.js
shoot.js
var http = require('http'); var phantom=require('node-phantom-simple'); http.createServer(function (req, res) { phantom.create(function(err,ph) { return ph.createPage(function(err, page) { return page.open(req.url.slice(1), function(err, status) { //Wait for a bit for AJAX content to load on the page. Better solution? setTimeout(function() { page.renderBase64("PNG", function(error, result){ var imageBuffer = new Buffer(result, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': imageBuffer.length}); res.end(imageBuffer); }); }, 2000); }); }); }); }).listen(1337, '127.0.0.1'); console.log('Server running at port 1337');
var http = require('http'); var phantom=require('node-phantom-simple'); http.createServer(function (req, res) { phantom.create(function(err,ph) { return ph.createPage(function(err, page) { return page.open(req.url.slice(1), function(err, status) { //Wait for a bit for AJAX content to load on the page. Better solution? setTimeout(function() { page.renderBase64("PNG", function(error, result){ var imageBuffer = new Buffer(result, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': imageBuffer.length}); res.end(imageBuffer); ph.exit() }); }, 2000); }); }); }); }).listen(1337, '127.0.0.1'); console.log('Server running at port 1337');
Exit phantomJS after every screenshot to kill phantom process
Exit phantomJS after every screenshot to kill phantom process
JavaScript
mit
weld-io/screenshooter
--- +++ @@ -13,6 +13,7 @@ 'Content-Type': 'image/png', 'Content-Length': imageBuffer.length}); res.end(imageBuffer); + ph.exit() }); }, 2000); });
965cda3443193e8dfaaf9132af38d98bc523b28f
tweet.js
tweet.js
const fs = require('fs') const Twit = require('twit') const config = require('./config') const quotes = JSON.parse(fs.readFileSync('./data/backup-2016-11-03.json', 'utf8')) const T = new Twit(config.oauth_creds) function randomQuote () { return quotes[Math.floor(Math.random() * quotes.length)] } function tweetMessage (quote) { let msg = quote.msg + '\n' + quote.src T.post('statuses/update', {status: msg}, (err, res) => { if (err) { console.error('--->>>') console.error(msg) console.error(quote) console.dir(err) } else { console.log('tweet succeed.') console.log(res.text) } }) } tweetMessage(randomQuote())
const quotes = JSON.parse(require('fs').readFileSync('./data/backup-2016-11-03.json', 'utf8')) const config = require('./config') const Twit = require('twit') const T = new Twit(config.oauth_creds) function randomQuote () { return quotes[Math.floor(Math.random() * quotes.length)] } function tweetMessage (quote) { let msg = quote.msg + '\n' + quote.src T.post('statuses/update', {status: msg}, (err, res) => { if (err) { console.error('--->>>') console.error(msg) console.error(quote) console.dir(err) } else { console.log('tweet succeed at ', new Date()) console.log(res.text) } }) } tweetMessage(randomQuote())
Clean up code and add timestamp
Clean up code and add timestamp
JavaScript
mit
ntalbs/tweetbot-js,ntalbs/tweetbot-js
--- +++ @@ -1,8 +1,6 @@ -const fs = require('fs') +const quotes = JSON.parse(require('fs').readFileSync('./data/backup-2016-11-03.json', 'utf8')) +const config = require('./config') const Twit = require('twit') -const config = require('./config') - -const quotes = JSON.parse(fs.readFileSync('./data/backup-2016-11-03.json', 'utf8')) const T = new Twit(config.oauth_creds) function randomQuote () { @@ -18,7 +16,7 @@ console.error(quote) console.dir(err) } else { - console.log('tweet succeed.') + console.log('tweet succeed at ', new Date()) console.log(res.text) } })
6fa08345946bcf8052931053697869626441b1c4
twish.js
twish.js
var util = require('util') , twitter = require('twitter') , Stream = require('stream') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true local.context.repl = local local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) var twish = new twitter(keys) //twish.get('/statuses/show/183682338646011904.json', function(data){ //console.log(data) //}) //twish.stream('statuses/sample', function(stream){ twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ process.stdout.write(JSON.stringify(data, null, ' ')) }, 500) }) }) module.exports = twish
var util = require('util') , twitter = require('twitter') , Stream = require('stream') , repl = require('repl') , keys = require('./keys') , local = repl.start() , first = true local.context.repl = local local.defineCommand('tweet', function(tweet){ twish .verifyCredentials(function(data) { console.log(util.inspect(data)) }) .updateStatus(tweet, function(data) { console.log(util.inspect(data)) }) }) local.commands['.tweet'].help = 'Tweet as currently signed in user' var twish = new twitter(keys) //twish.get('/statuses/show/183682338646011904.json', function(data){ //console.log(data) //}) //twish.stream('statuses/sample', function(stream){ twish.stream('user', {track:'gkatsev', delimited:20}, function(stream){ stream.on('data', function(data){ if(first){ first = false return } setTimeout(function(){ process.stdout.write(JSON.stringify(data, null, ' ')) }, 500) }) }) module.exports = twish
Add help text for the tweet command
Add help text for the tweet command
JavaScript
mit
gkatsev/twish
--- +++ @@ -17,7 +17,7 @@ console.log(util.inspect(data)) }) }) - +local.commands['.tweet'].help = 'Tweet as currently signed in user' var twish = new twitter(keys) //twish.get('/statuses/show/183682338646011904.json', function(data){
7bc64c9528715065c2b6318c32666b7f596e963b
lib/watch.js
lib/watch.js
const chokidar = require('chokidar') const compile = require('./compiler').run module.exports = function () { const watcher = chokidar.watch(process.cwd(), { ignored: /dist|layouts|.DS_Store/ }) console.log('Watching for changes...') process.on('SIGINT', function () { watcher.close() process.exit(0) }) watcher.on('change', (which) => { const paths = new function () { this.full = which this.relative = this.full.replace(process.cwd(), '').replace('scss', 'css') } compile(paths, () => { console.log('File ' + paths.relative.gray + ' changed, rebuilt finished') }) }) }
const chokidar = require('chokidar') const path = require('path') const walk = require('walk') const compile = require('./compiler').run function finished (paths) { console.log('File ' + paths.relative.gray + ' changed, rebuilt finished') } module.exports = function () { const watcher = chokidar.watch(process.cwd(), { ignored: /dist|.DS_Store/ }) console.log('Watching for changes...') process.on('SIGINT', function () { watcher.close() process.exit(0) }) watcher.on('change', (which) => { var dir = path.dirname(which) var lastSlash = dir.lastIndexOf('/') dir = dir.substring(lastSlash + 1) const Paths = function () { this.full = which this.relative = this.full.replace(process.cwd(), '').replace('scss', 'css') } if (dir === 'layouts') { const walker = walk.walk(process.cwd() + '/pages') walker.on('file', function (root, fileStat, next) { var newPaths = new Paths newPaths.full = path.resolve(root, fileStat.name) newPaths.relative = newPaths.full.replace(process.cwd(), '') compile(newPaths, next) }) walker.on('end', function() { finished(new Paths) }) return } const originals = new Paths compile(originals, finished(originals)) }) }
Rebuild pages if their layout changes
Rebuild pages if their layout changes
JavaScript
mit
leo/cory,leo/cory
--- +++ @@ -1,9 +1,15 @@ const chokidar = require('chokidar') +const path = require('path') +const walk = require('walk') const compile = require('./compiler').run + +function finished (paths) { + console.log('File ' + paths.relative.gray + ' changed, rebuilt finished') +} module.exports = function () { const watcher = chokidar.watch(process.cwd(), { - ignored: /dist|layouts|.DS_Store/ + ignored: /dist|.DS_Store/ }) console.log('Watching for changes...') @@ -14,13 +20,36 @@ }) watcher.on('change', (which) => { - const paths = new function () { + var dir = path.dirname(which) + var lastSlash = dir.lastIndexOf('/') + + dir = dir.substring(lastSlash + 1) + + const Paths = function () { this.full = which this.relative = this.full.replace(process.cwd(), '').replace('scss', 'css') } - compile(paths, () => { - console.log('File ' + paths.relative.gray + ' changed, rebuilt finished') - }) + if (dir === 'layouts') { + const walker = walk.walk(process.cwd() + '/pages') + + walker.on('file', function (root, fileStat, next) { + var newPaths = new Paths + + newPaths.full = path.resolve(root, fileStat.name) + newPaths.relative = newPaths.full.replace(process.cwd(), '') + + compile(newPaths, next) + }) + + walker.on('end', function() { + finished(new Paths) + }) + + return + } + + const originals = new Paths + compile(originals, finished(originals)) }) }
d08c1787c718d78fd5d806df139fe7d2d8657663
src/utils/d3/render_axis_label.js
src/utils/d3/render_axis_label.js
export default function({ renderedXAxis, renderedYAxis, xLabel, yLabel, width }) { let _y = this.axis == 'y' let axis = _y ? renderedYAxis : renderedXAxis if (axis) { let label = _y ? yLabel : xLabel let _label = axis.append('text') .attr('class', 'label') .attr('y', 15) .style('text-anchor', 'end') .text(label) if (_y) { _label .attr('transform', 'rotate(-90)') } else { _label .attr('x', width) } } }
export default function({ renderedXAxis, renderedYAxis, xLabel, yLabel, width }) { let _y = this.axis == 'y' let axis = _y ? renderedYAxis : renderedXAxis if (axis) { let label = _y ? yLabel : xLabel let _label = axis.append('text') .attr('class', 'label') .style('text-anchor', 'end') .text(label) if (_y) { _label .attr('y', 15) .attr('transform', 'rotate(-90)') } else { _label .attr('y', -6) .attr('x', width) } } }
Fix rendering of x-Axis labels
Fix rendering of x-Axis labels
JavaScript
mit
simonwoerpel/d3-playbooks,correctiv/d3-riot-charts,correctiv/d3-riot-charts,simonwoerpel/d3-playbooks,simonwoerpel/d3-playbooks
--- +++ @@ -12,15 +12,16 @@ let label = _y ? yLabel : xLabel let _label = axis.append('text') .attr('class', 'label') - .attr('y', 15) .style('text-anchor', 'end') .text(label) if (_y) { _label + .attr('y', 15) .attr('transform', 'rotate(-90)') } else { _label + .attr('y', -6) .attr('x', width) } }
1bc439d42e0352f7cb2f6c153cafc45f874bb7ae
eg/photoresistor.js
eg/photoresistor.js
var five = require("../lib/johnny-five.js"), board, photoresistor; board = new five.Board(); board.on("ready", function() { // Create a new `photoresistor` hardware instance. photoresistor = new five.Sensor({ pin: "A2", freq: 250 }); // Inject the `sensor` hardware into // the Repl instance's context; // allows direct command line access board.repl.inject({ pot: photoresistor }); // "read" get the current reading from the photoresistor photoresistor.on("read", function( err, value ) { console.log( this.value ); }); }); // References // // http://nakkaya.com/2009/10/29/connecting-a-photoresistor-to-an-arduino/
var five = require("../lib/johnny-five.js"), board, photoresistor; board = new five.Board(); board.on("ready", function() { // Create a new `photoresistor` hardware instance. photoresistor = new five.Sensor({ pin: "A2", freq: 250 }); // Inject the `sensor` hardware into // the Repl instance's context; // allows direct command line access board.repl.inject({ pot: photoresistor }); // "read" get the current reading from the photoresistor photoresistor.on("read", function() { console.log( this.value ); }); }); // References // // http://nakkaya.com/2009/10/29/connecting-a-photoresistor-to-an-arduino/
Remove err, value in favor of this.value
[fix] Remove err, value in favor of this.value
JavaScript
mit
kod3r/johnny-five,cumbreras/rv,joelunmsm2003/arduino,garrows/johnny-five,kod3r/johnny-five,AnnaGerber/johnny-five
--- +++ @@ -19,7 +19,7 @@ }); // "read" get the current reading from the photoresistor - photoresistor.on("read", function( err, value ) { + photoresistor.on("read", function() { console.log( this.value ); }); });
697891dcbd2cacf1af72a166ddb29a7afdd73832
lib/errors/invalid-channel-name.js
lib/errors/invalid-channel-name.js
var extend = req('/lib/utilities/extend'), BaseError = req('/lib/errors/base'), ErrorCodes = req('/lib/constants/error-codes'), ErrorReasons = req('/lib/constants/error-reasons'), createMessage = req('/lib/utilities/create-message'), ReplyNumerics = req('/lib/constants/reply-numerics'), Commands = req('/lib/constants/commands'); class InvalidChannelNameError extends BaseError { getBody() { switch (this.reason) { case ErrorReasons.OMITTED: return 'You must specify a channel name'; case ErrorReasons.INVALID_CHARACTERS: return 'Invalid channel name: ' + this.getChannelName(); case ErrorReasons.NOT_FOUND: return 'Channel did not exist: ' + this.getChannelName(); default: return 'Invalid channel name: ' + this.reason; } } getChannelName() { return this.value; } toMessage() { var command = this.getCommand(); switch (command) { case Commands.MODE: let message = createMessage(ReplyNumerics.ERR_NOSUCHCHANNEL); return message.setChannelName(this.getValue()); default: throw new Error('implement'); } } } extend(InvalidChannelNameError.prototype, { code: ErrorCodes.INVALID_CHANNEL_NAME }); module.exports = InvalidChannelNameError;
var extend = req('/lib/utilities/extend'), BaseError = req('/lib/errors/base'), ErrorCodes = req('/lib/constants/error-codes'), ErrorReasons = req('/lib/constants/error-reasons'), createMessage = req('/lib/utilities/create-message'), ReplyNumerics = req('/lib/constants/reply-numerics'), Commands = req('/lib/constants/commands'); class InvalidChannelNameError extends BaseError { getBody() { switch (this.reason) { case ErrorReasons.OMITTED: return 'You must specify a channel name'; case ErrorReasons.INVALID_CHARACTERS: return 'Invalid channel name: ' + this.getChannelName(); case ErrorReasons.NOT_FOUND: return 'Channel did not exist: ' + this.getChannelName(); default: return 'Invalid channel name: ' + this.reason; } } getChannelName() { return this.value; } toMessage() { var command = this.getCommand(); switch (command) { case Commands.JOIN: case Commands.MODE: case Commands.PART: let message = createMessage(ReplyNumerics.ERR_NOSUCHCHANNEL); return message.setChannelName(this.getValue()); default: throw new Error('implement'); } } } extend(InvalidChannelNameError.prototype, { code: ErrorCodes.INVALID_CHANNEL_NAME }); module.exports = InvalidChannelNameError;
Add handling to InvalidChannelNameError for generating reply messages for several other commands
Add handling to InvalidChannelNameError for generating reply messages for several other commands
JavaScript
isc
burninggarden/pirc,burninggarden/pirc
--- +++ @@ -32,7 +32,9 @@ var command = this.getCommand(); switch (command) { + case Commands.JOIN: case Commands.MODE: + case Commands.PART: let message = createMessage(ReplyNumerics.ERR_NOSUCHCHANNEL); return message.setChannelName(this.getValue());
4865ba39496d72c951e783cebdfd00cc4ce571b4
packages/kittik-parser/src/index.js
packages/kittik-parser/src/index.js
const nearley = require('nearley'); const grammar = require('./grammar/grammar'); const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); module.exports = function parse(input) { return parser.feed(input); }
const nearley = require('nearley'); const grammar = require('./grammar/grammar'); module.exports = function parse(input) { const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); return parser.feed(input).finish().results[0]; };
Fix issue with sharing states between different parsings
Fix issue with sharing states between different parsings
JavaScript
mit
kittikjs/kittik
--- +++ @@ -1,7 +1,7 @@ const nearley = require('nearley'); const grammar = require('./grammar/grammar'); -const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); module.exports = function parse(input) { - return parser.feed(input); -} + const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); + return parser.feed(input).finish().results[0]; +};
997b979d1bd1367e783fbe0b60ce4d13865509c6
lib/utilities/ember-cli-version.js
lib/utilities/ember-cli-version.js
'use strict'; var fs = require('fs'); var path = require('path'); module.exports = function () { var output = [require('../../package.json').version]; var gitPath = path.join(__dirname, '..','..','.git'); var headFilePath = path.join(gitPath, 'HEAD'); try { if (fs.existsSync(headFilePath)) { var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); var branchPath = path.join(gitPath, headFile.split(' ')[1].trim()); output.push(branchName); var branchSHA = fs.readFileSync(branchPath); output.push(branchSHA.slice(0,10)); } } catch (err) { console.error(err.stack); } return output.join('-'); };
'use strict'; var fs = require('fs'); var path = require('path'); module.exports = function () { var output = [require('../../package.json').version]; var gitPath = path.join(__dirname, '..','..','.git'); var headFilePath = path.join(gitPath, 'HEAD'); try { if (fs.existsSync(headFilePath)) { var branchSHA; var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); var refPath = headFile.split(' ')[1]; if (refPath) { var branchPath = path.join(gitPath, refPath.trim()); branchSHA = fs.readFileSync(branchPath); } else { branchSHA = branchName; } output.push(branchName); output.push(branchSHA.slice(0,10)); } } catch (err) { console.error(err.stack); } return output.join('-'); };
Trim error were thrown when linked ember-cli had deatched HEAD.
Trim error were thrown when linked ember-cli had deatched HEAD. If the contents of the ./git/HEAD file does not return a ref path, it's a SHA value so that is what will be used.
JavaScript
mit
alefteris/ember-cli,taras/ember-cli,raytiley/ember-cli,typeoneerror/ember-cli,Turbo87/ember-cli,thoov/ember-cli,jonathanKingston/ember-cli,yaymukund/ember-cli,samselikoff/ember-cli,johnotander/ember-cli,Turbo87/ember-cli,tobymarsden/ember-cli,twokul/ember-cli,sivakumar-kailasam/ember-cli,coderly/ember-cli,gmurphey/ember-cli,szines/ember-cli,BrianSipple/ember-cli,eoinkelly/ember-cli,xcambar/ember-cli,xiujunma/ember-cli,sivakumar-kailasam/ember-cli,mohlek/ember-cli,raycohen/ember-cli,ballPointPenguin/ember-cli,johanneswuerbach/ember-cli,BrianSipple/ember-cli,code0100fun/ember-cli,kamalaknn/ember-cli,tsing80/ember-cli,joostdevries/ember-cli,code0100fun/ember-cli,blimmer/ember-cli,akatov/ember-cli,supabok/ember-cli,mschinis/ember-cli,josemarluedke/ember-cli,quaertym/ember-cli,eliotsykes/ember-cli,jasonmit/ember-cli,rondale-sc/ember-cli,maxcal/ember-cli,martypenner/ember-cli,maxcal/ember-cli,rtablada/ember-cli,williamsbdev/ember-cli,josemarluedke/ember-cli,rtablada/ember-cli,kriswill/ember-cli,romulomachado/ember-cli,mixonic/ember-cli,trentmwillis/ember-cli,rondale-sc/ember-cli,xcambar/ember-cli,ianstarz/ember-cli,scalus/ember-cli,typeoneerror/ember-cli,xcambar/ember-cli,nathanhammond/ember-cli,calderas/ember-cli,nruth/ember-cli,yaymukund/ember-cli,taras/ember-cli,princeofdarkness76/ember-cli,seanpdoyle/ember-cli,code0100fun/ember-cli,jcope2013/ember-cli,martypenner/ember-cli,nathanhammond/ember-cli,mixonic/ember-cli,alefteris/ember-cli,nruth/ember-cli,givanse/ember-cli,jrjohnson/ember-cli,scalus/ember-cli,lazybensch/ember-cli,quaertym/ember-cli,ef4/ember-cli,twokul/ember-cli,dukex/ember-cli,csantero/ember-cli,noslouch/ember-cli,slindberg/ember-cli,coderly/ember-cli,rickharrison/ember-cli,coderly/ember-cli,fpauser/ember-cli,acorncom/ember-cli,ServiceTo/ember-cli,gfvcastro/ember-cli,pixelhandler/ember-cli,kanongil/ember-cli,selvagsz/ember-cli,johnotander/ember-cli,joaohornburg/ember-cli,johnotander/ember-cli,mschinis/ember-cli,kriswill/ember-cli,buschtoens/ember-cli,jgwhite/ember-cli,johanneswuerbach/ember-cli,szines/ember-cli,felixrieseberg/ember-cli,michael-k/ember-cli,Turbo87/ember-cli,mschinis/ember-cli,romulomachado/ember-cli,acorncom/ember-cli,rot26/ember-cli,jcope2013/ember-cli,rodyhaddad/ember-cli,runspired/ember-cli,xtian/ember-cli,gmurphey/ember-cli,cibernox/ember-cli,ef4/ember-cli,eliotsykes/ember-cli,greyhwndz/ember-cli,princeofdarkness76/ember-cli,xtian/ember-cli,gfvcastro/ember-cli,cibernox/ember-cli,tsing80/ember-cli,lazybensch/ember-cli,jcope2013/ember-cli,beatle/ember-cli,HeroicEric/ember-cli,pangratz/ember-cli,tobymarsden/ember-cli,Restuta/ember-cli,rodyhaddad/ember-cli,EricSchank/ember-cli,ianstarz/ember-cli,michael-k/ember-cli,thoov/ember-cli,calderas/ember-cli,eccegordo/ember-cli,bmac/ember-cli,rot26/ember-cli,eoinkelly/ember-cli,olegdovger/ember-cli,abuiles/ember-cli,scalus/ember-cli,joostdevries/ember-cli,williamsbdev/ember-cli,jonathanKingston/ember-cli,marcioj/ember-cli,alexdiliberto/ember-cli,martypenner/ember-cli,slindberg/ember-cli,rtablada/ember-cli,xiujunma/ember-cli,jonathanKingston/ember-cli,alexdiliberto/ember-cli,blimmer/ember-cli,raytiley/ember-cli,marcioj/ember-cli,pzuraq/ember-cli,acorncom/ember-cli,josemarluedke/ember-cli,mschinis/ember-cli,trentmwillis/ember-cli,michael-k/ember-cli,kategengler/ember-cli,trabus/ember-cli,mixonic/ember-cli,greyhwndz/ember-cli,searls/ember-cli,akatov/ember-cli,joliss/ember-cli,kriswill/ember-cli,dosco/ember-cli,rot26/ember-cli,samselikoff/ember-cli,ianstarz/ember-cli,ef4/ember-cli,thoov/ember-cli,twokul/ember-cli,pixelhandler/ember-cli,tobymarsden/ember-cli,makepanic/ember-cli,jayphelps/ember-cli,seawatts/ember-cli,nruth/ember-cli,josemarluedke/ember-cli,marcioj/ember-cli,elwayman02/ember-cli,csantero/ember-cli,dschmidt/ember-cli,joaohornburg/ember-cli,coderly/ember-cli,mixonic/ember-cli,xiujunma/ember-cli,kanongil/ember-cli,dschmidt/ember-cli,ServiceTo/ember-cli,joostdevries/ember-cli,samselikoff/ember-cli,patocallaghan/ember-cli,sivakumar-kailasam/ember-cli,jrjohnson/ember-cli,scalus/ember-cli,jonathanKingston/ember-cli,kamalaknn/ember-cli,seawatts/ember-cli,kriswill/ember-cli,cibernox/ember-cli,ro0gr/ember-cli,ember-cli/ember-cli,trentmwillis/ember-cli,jcope2013/ember-cli,lazybensch/ember-cli,givanse/ember-cli,selvagsz/ember-cli,mattmarcum/ember-cli,balinterdi/ember-cli,eccegordo/ember-cli,pangratz/ember-cli,acorncom/ember-cli,selvagsz/ember-cli,maxcal/ember-cli,xiujunma/ember-cli,eccegordo/ember-cli,dukex/ember-cli,rot26/ember-cli,jasonmit/ember-cli,HeroicEric/ember-cli,bevacqua/ember-cli,pixelhandler/ember-cli,martndemus/ember-cli,raytiley/ember-cli,fpauser/ember-cli,makepanic/ember-cli,mike-north/ember-cli,szines/ember-cli,jasonmit/ember-cli,mohlek/ember-cli,ro0gr/ember-cli,lancedikson/ember-cli,runspired/ember-cli,pangratz/ember-cli,mohlek/ember-cli,abuiles/ember-cli,alefteris/ember-cli,mike-north/ember-cli,williamsbdev/ember-cli,quaertym/ember-cli,mike-north/ember-cli,selvagsz/ember-cli,johanneswuerbach/ember-cli,pixelhandler/ember-cli,buschtoens/ember-cli,ianstarz/ember-cli,jayphelps/ember-cli,comlaterra/ember-cli,kamalaknn/ember-cli,beatle/ember-cli,EricSchank/ember-cli,typeoneerror/ember-cli,patocallaghan/ember-cli,joaohornburg/ember-cli,dukex/ember-cli,martndemus/ember-cli,airportyh/ember-cli,nruth/ember-cli,joliss/ember-cli,chadhietala/ember-cli,fpauser/ember-cli,makepanic/ember-cli,eliotsykes/ember-cli,zanemayo/ember-cli,taras/ember-cli,szines/ember-cli,oss-practice/ember-cli,kellyselden/ember-cli,searls/ember-cli,ember-cli/ember-cli,EricSchank/ember-cli,joliss/ember-cli,ember-cli/ember-cli,greyhwndz/ember-cli,bevacqua/ember-cli,Turbo87/ember-cli,airportyh/ember-cli,chadhietala/ember-cli,seanpdoyle/ember-cli,HeroicEric/ember-cli,romulomachado/ember-cli,seanpdoyle/ember-cli,beatle/ember-cli,zanemayo/ember-cli,abuiles/ember-cli,trabus/ember-cli,gfvcastro/ember-cli,jgwhite/ember-cli,bevacqua/ember-cli,tsing80/ember-cli,blimmer/ember-cli,zanemayo/ember-cli,quaertym/ember-cli,makepanic/ember-cli,xcambar/ember-cli,lancedikson/ember-cli,BrianSipple/ember-cli,pzuraq/ember-cli,xtian/ember-cli,aceofspades/ember-cli,cibernox/ember-cli,yapplabs/ember-cli,beatle/ember-cli,nathanhammond/ember-cli,eccegordo/ember-cli,igorT/ember-cli,alexdiliberto/ember-cli,lazybensch/ember-cli,gmurphey/ember-cli,eliotsykes/ember-cli,trabus/ember-cli,DanielOchoa/ember-cli,seawatts/ember-cli,rwjblue/ember-cli,lancedikson/ember-cli,patocallaghan/ember-cli,greyhwndz/ember-cli,dosco/ember-cli,olegdovger/ember-cli,yaymukund/ember-cli,DanielOchoa/ember-cli,Restuta/ember-cli,kanongil/ember-cli,martndemus/ember-cli,nathanhammond/ember-cli,joostdevries/ember-cli,csantero/ember-cli,rickharrison/ember-cli,alexdiliberto/ember-cli,csantero/ember-cli,DanielOchoa/ember-cli,bevacqua/ember-cli,samselikoff/ember-cli,balinterdi/ember-cli,runspired/ember-cli,olegdovger/ember-cli,akatov/ember-cli,martndemus/ember-cli,alefteris/ember-cli,ballPointPenguin/ember-cli,rtablada/ember-cli,yaymukund/ember-cli,joliss/ember-cli,HeroicEric/ember-cli,bmac/ember-cli,lancedikson/ember-cli,yapplabs/ember-cli,ballPointPenguin/ember-cli,dosco/ember-cli,calderas/ember-cli,joaohornburg/ember-cli,kamalaknn/ember-cli,searls/ember-cli,princeofdarkness76/ember-cli,airportyh/ember-cli,kellyselden/ember-cli,ro0gr/ember-cli,asakusuma/ember-cli,mike-north/ember-cli,pzuraq/ember-cli,ef4/ember-cli,jasonmit/ember-cli,felixrieseberg/ember-cli,jgwhite/ember-cli,code0100fun/ember-cli,seanpdoyle/ember-cli,Restuta/ember-cli,romulomachado/ember-cli,jgwhite/ember-cli,taras/ember-cli,dosco/ember-cli,sivakumar-kailasam/ember-cli,trabus/ember-cli,marcioj/ember-cli,zanemayo/ember-cli,mattmarcum/ember-cli,airportyh/ember-cli,rodyhaddad/ember-cli,raycohen/ember-cli,eoinkelly/ember-cli,ballPointPenguin/ember-cli,gmurphey/ember-cli,elwayman02/ember-cli,martypenner/ember-cli,ServiceTo/ember-cli,blimmer/ember-cli,searls/ember-cli,olegdovger/ember-cli,calderas/ember-cli,igorT/ember-cli,akatov/ember-cli,mohlek/ember-cli,princeofdarkness76/ember-cli,EricSchank/ember-cli,comlaterra/ember-cli,Restuta/ember-cli,williamsbdev/ember-cli,jayphelps/ember-cli,johanneswuerbach/ember-cli,givanse/ember-cli,felixrieseberg/ember-cli,runspired/ember-cli,gfvcastro/ember-cli,johnotander/ember-cli,eoinkelly/ember-cli,comlaterra/ember-cli,tsing80/ember-cli,twokul/ember-cli,ro0gr/ember-cli,trentmwillis/ember-cli,noslouch/ember-cli,kellyselden/ember-cli,oss-practice/ember-cli,patocallaghan/ember-cli,comlaterra/ember-cli,tobymarsden/ember-cli,BrianSipple/ember-cli,DanielOchoa/ember-cli,raytiley/ember-cli,maxcal/ember-cli,kategengler/ember-cli,aceofspades/ember-cli,rodyhaddad/ember-cli,fpauser/ember-cli,supabok/ember-cli,dukex/ember-cli,typeoneerror/ember-cli,ServiceTo/ember-cli,kellyselden/ember-cli,kanongil/ember-cli,asakusuma/ember-cli,xtian/ember-cli,michael-k/ember-cli,noslouch/ember-cli,thoov/ember-cli,noslouch/ember-cli,seawatts/ember-cli,pzuraq/ember-cli,givanse/ember-cli,pangratz/ember-cli,abuiles/ember-cli,jayphelps/ember-cli
--- +++ @@ -10,13 +10,20 @@ try { if (fs.existsSync(headFilePath)) { + var branchSHA; var headFile = fs.readFileSync(headFilePath, {encoding: 'utf8'}); var branchName = headFile.split('/').slice(-1)[0].trim(); - var branchPath = path.join(gitPath, headFile.split(' ')[1].trim()); + var refPath = headFile.split(' ')[1]; + + if (refPath) { + var branchPath = path.join(gitPath, refPath.trim()); + branchSHA = fs.readFileSync(branchPath); + } else { + branchSHA = branchName; + } output.push(branchName); - var branchSHA = fs.readFileSync(branchPath); output.push(branchSHA.slice(0,10)); } } catch (err) {
4b0dba9f6f2998d8f41e302b7775d7db1088eebf
test/js/main.js
test/js/main.js
;(function($) { // initalize Editable Editable.init({ log: false }); $(document).ready(function() { var tooltip = $('<div class="selection-tip" style="display:none;">How may I help?</div>') $(document.body).append(tooltip); $("article>div>p, article>div li").editable(); Editable.focus(function(el) { console.log('Focus event handler was triggered on', el); }).blur(function(el) { console.log('Blur event handler was triggered on', el); // todo: this should not be necessary here tooltip.hide(); }).selection(function(el, selection) { if (selection) { coords = selection.getCoordinates() // position tooltip var top = coords.top - tooltip.outerHeight() - 15; var left = coords.left + (coords.width / 2) - (tooltip.outerWidth() / 2); tooltip.show().css('top', top).css('left', left); } else { tooltip.hide(); } }); }); })(jQuery);
;(function($) { // initalize Editable Editable.init({ log: false }); var setupTooltip = function() { var tooltip = $('<div class="selection-tip" style="display:none;">How may I help?</div>') $(document.body).append(tooltip); Editable.selection(function(el, selection) { if (selection) { coords = selection.getCoordinates() // position tooltip var top = coords.top - tooltip.outerHeight() - 15; var left = coords.left + (coords.width / 2) - (tooltip.outerWidth() / 2); tooltip.show().css('top', top).css('left', left); } else { tooltip.hide(); } }).blur(function(el) { // todo: this should not be necessary here tooltip.hide(); }); }; $(document).ready(function() { $("article>div>p, article>div li").editable(); setupTooltip(); }); })(jQuery);
Clean up js for index.html a bit
Clean up js for index.html a bit
JavaScript
mit
nickbalestra/editable.js,upfrontIO/editable.js
--- +++ @@ -6,21 +6,11 @@ }); - $(document).ready(function() { + var setupTooltip = function() { var tooltip = $('<div class="selection-tip" style="display:none;">How may I help?</div>') $(document.body).append(tooltip); - $("article>div>p, article>div li").editable(); - Editable.focus(function(el) { - console.log('Focus event handler was triggered on', el); - - }).blur(function(el) { - console.log('Blur event handler was triggered on', el); - - // todo: this should not be necessary here - tooltip.hide(); - - }).selection(function(el, selection) { + Editable.selection(function(el, selection) { if (selection) { coords = selection.getCoordinates() @@ -31,6 +21,16 @@ } else { tooltip.hide(); } + }).blur(function(el) { + // todo: this should not be necessary here + tooltip.hide(); }); + }; + + + $(document).ready(function() { + $("article>div>p, article>div li").editable(); + setupTooltip(); }); + })(jQuery);
7911d5b49fe8068c248ab8db98484bfca6e4ef2a
config/webpack.alias.js
config/webpack.alias.js
var path = require('path'); var rootPath = path.join(__dirname, '..') module.exports = { '~': path.join(rootPath, 'src', 'client'), '~server': path.join(rootPath, 'src', 'server'), '~root': rootPath, 'react': 'preact-compat', 'react-dom': 'preact-compat' }
var path = require('path'); var rootPath = path.join(__dirname, '..') module.exports = { '~': path.join(rootPath, 'src', 'client'), '~server': path.join(rootPath, 'src', 'server'), '~root': rootPath }
Remove preact for now. Problems with event bubbling.
(config): Remove preact for now. Problems with event bubbling.
JavaScript
mit
AdamSalma/Lurka,AdamSalma/Lurka
--- +++ @@ -4,7 +4,5 @@ module.exports = { '~': path.join(rootPath, 'src', 'client'), '~server': path.join(rootPath, 'src', 'server'), - '~root': rootPath, - 'react': 'preact-compat', - 'react-dom': 'preact-compat' + '~root': rootPath }
3e958fa5d4764fcb9babce9f0892e92ec44e5be8
parsers/utils/read-bounding-box.js
parsers/utils/read-bounding-box.js
'use strict' module.exports = function readBoundingBox (buffer, offset) { const Xmin = buffer.readDoubleLE(offset, true) const Ymin = buffer.readDoubleLE(offset + 8, true) const Xmax = buffer.readDoubleLE(offset + 16, true) const Ymax = buffer.readDoubleLE(offset + 24, true) return {Xmin, Ymin, Xmax, Ymax} }
'use strict' module.exports = function readBoundingBox (buffer, offset) { const xMin = buffer.readDoubleLE(offset, true) const yMin = buffer.readDoubleLE(offset + 8, true) const xMax = buffer.readDoubleLE(offset + 16, true) const yMax = buffer.readDoubleLE(offset + 24, true) return {xMin, yMin, xMax, yMax} }
Change caseing to conform with shp header
Change caseing to conform with shp header
JavaScript
isc
emilbayes/shapefile-reader
--- +++ @@ -1,9 +1,9 @@ 'use strict' module.exports = function readBoundingBox (buffer, offset) { - const Xmin = buffer.readDoubleLE(offset, true) - const Ymin = buffer.readDoubleLE(offset + 8, true) - const Xmax = buffer.readDoubleLE(offset + 16, true) - const Ymax = buffer.readDoubleLE(offset + 24, true) - return {Xmin, Ymin, Xmax, Ymax} + const xMin = buffer.readDoubleLE(offset, true) + const yMin = buffer.readDoubleLE(offset + 8, true) + const xMax = buffer.readDoubleLE(offset + 16, true) + const yMax = buffer.readDoubleLE(offset + 24, true) + return {xMin, yMin, xMax, yMax} }
36dfba6a30405b584b1e0a1de2d6dcf0285aef4d
app/assets/javascripts/agreement.js
app/assets/javascripts/agreement.js
/* jslint browser: true */ /* global $ */ (function(){ var makeCloneable = function(selector) { var scope = $(selector); var update_remove_one_visibility = function() { var hidden = scope.find('.cloneable').length < 2; scope.find('.remove-one').toggleClass('hidden', hidden); }; update_remove_one_visibility(); scope.find('.add-one').click(function(e) { e.preventDefault(); var newContent = scope.find('.cloneable:first').clone(); scope.find('.cloneable:last').after(newContent); scope.find('.cloneable:last input[type="text"]').val(''); update_remove_one_visibility(); }); scope.find('.remove-one').click(function(e) { e.preventDefault(); scope.find('.cloneable:last').remove(); update_remove_one_visibility(); }); }; $(document).ready(function() { makeCloneable('#budgetary-responsibilities'); }); })();
/* jslint browser: true */ /* global $ */ (function(){ var makeCloneable = function(selector) { var scope = $(selector); var update_remove_one_visibility = function() { var hidden = scope.find('.cloneable').length < 2; scope.find('.remove-one').toggleClass('hidden', hidden); }; update_remove_one_visibility(); scope.find('.add-one').click(function(e) { e.preventDefault(); var newContent = scope.find('.cloneable:first').clone(); scope.find('.cloneable:last').after(newContent); scope.find('.cloneable:last input[type="text"]').val(''); scope.find('.cloneable:last textarea').text(''); update_remove_one_visibility(); }); scope.find('.remove-one').click(function(e) { e.preventDefault(); scope.find('.cloneable:last').remove(); update_remove_one_visibility(); }); }; $(document).ready(function() { makeCloneable('#budgetary-responsibilities'); }); })();
Clear textarea in cloned row
Clear textarea in cloned row
JavaScript
mit
ministryofjustice/scs_appraisals,ministryofjustice/scs_appraisals,ministryofjustice/scs_appraisals
--- +++ @@ -18,6 +18,7 @@ scope.find('.cloneable:last').after(newContent); scope.find('.cloneable:last input[type="text"]').val(''); + scope.find('.cloneable:last textarea').text(''); update_remove_one_visibility(); });
2d7fd5806d088578ac94b8a520ca315821933dd0
src/Timer.js
src/Timer.js
'use strict'; export class Timer { constructor() { this.reset(); } /** * Start the timer */ start() { if(this._ran) throw new Error('timer already ran. use reset() first'); if(this._running) throw new Error('timer currently running'); this._hrtime = process.hrtime(); this._running = true; } /** * Stop the timer */ stop() { if(!this._running) throw new Error('timer not running'); this._hrtime = process.hrtime(this._hrtime); this._runtime = (this._hrtime[0] * 1000) + (this._hrtime[1] / 1000000); this._running = false; this._ran = true; } /** * Get the timer's time */ time() { if(!this._ran) throw new Error('timer not ran yet'); if(this._running) throw new Error('timmer currently running'); return this._runtime; } /** * Return true if the timer has ran and finished */ isFinished() { return this._ran; } /** * Rest timer variables */ reset() { this._hrtime = null; this._runtime = 0; this._running = false; this._ran = false; } }
'use strict'; export class Timer { constructor() { this.reset(); } /** * Start the timer */ start() { if(this._ran) throw new Error('timer already ran. use reset() first'); if(this._running) throw new Error('timer currently running'); this._running = true; this._hrtime = process.hrtime(); } /** * Stop the timer */ stop() { if(!this._running) throw new Error('timer not running'); this._hrtime = process.hrtime(this._hrtime); this._runtime = (this._hrtime[0] * 1000) + (this._hrtime[1] / 1000000); this._running = false; this._ran = true; } /** * Get the timer's time */ time() { if(!this._ran) throw new Error('timer not ran yet'); if(this._running) throw new Error('timmer currently running'); return this._runtime; } /** * Return true if the timer has ran and finished */ isFinished() { return this._ran; } /** * Rest timer variables */ reset() { this._hrtime = null; this._runtime = 0; this._running = false; this._ran = false; } }
Move running flag to before htrtime start
Move running flag to before htrtime start
JavaScript
mit
MichielvdVelde/yet-another-timer
--- +++ @@ -11,8 +11,8 @@ start() { if(this._ran) throw new Error('timer already ran. use reset() first'); if(this._running) throw new Error('timer currently running'); + this._running = true; this._hrtime = process.hrtime(); - this._running = true; } /**
3da6799c282bf4dba3d73443f8e119a54069661e
ember/ember-cli-build.js
ember/ember-cli-build.js
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. return app.toTree(); };
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { storeConfigInMeta: false, }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. return app.toTree(); };
Store config in JS file
ember/config: Store config in JS file
JavaScript
agpl-3.0
shadowoneau/skylines,skylines-project/skylines,shadowoneau/skylines,Harry-R/skylines,kerel-fs/skylines,RBE-Avionik/skylines,Turbo87/skylines,Turbo87/skylines,skylines-project/skylines,RBE-Avionik/skylines,Turbo87/skylines,skylines-project/skylines,shadowoneau/skylines,kerel-fs/skylines,skylines-project/skylines,kerel-fs/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,Harry-R/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Harry-R/skylines
--- +++ @@ -4,7 +4,7 @@ module.exports = function(defaults) { var app = new EmberApp(defaults, { - // Add options here + storeConfigInMeta: false, }); // Use `app.import` to add additional libraries to the generated
1e0e180c569366def74863d95a98bd147d7bc4d9
public/js/controllers/createpage.js
public/js/controllers/createpage.js
angular.module('createPageController.controller', []) .controller('createPageController', function($scope, $http, $routeParams, $location, pageService) { $scope.message = "first"; $scope.name = $routeParams.name; $scope.createPage = function(pass) { pageService.createPage($routeParams.name, pass).success(function(res) { $location.path('/' + $routeParams.name); }); }; });
angular.module('createPageController.controller', []) .controller('createPageController', function($scope, $http, $routeParams, $location, pageService) { $scope.message = "first"; $scope.name = $routeParams.name; pageService.getPage($routeParams.name).success(function() { $location.path('/' + $routeParams.name); }); $scope.createPage = function(pass) { pageService.createPage($routeParams.name, pass).success(function(res) { $location.path('/' + $routeParams.name); }); }; });
Create page will redirect to full page if already created
Create page will redirect to full page if already created
JavaScript
mit
coffee-cup/pintical,coffee-cup/pintical,coffee-cup/pintical
--- +++ @@ -2,6 +2,10 @@ .controller('createPageController', function($scope, $http, $routeParams, $location, pageService) { $scope.message = "first"; $scope.name = $routeParams.name; + + pageService.getPage($routeParams.name).success(function() { + $location.path('/' + $routeParams.name); + }); $scope.createPage = function(pass) { pageService.createPage($routeParams.name, pass).success(function(res) {
60bb8cc0d566e0e16a8c0df321647a532a553303
js/init.js
js/init.js
$(function(){ readFileIntoBuffer(batotoJSONFile, function(buffer){ if (buffer){ batotoJSON = JSON.parse(buffer); if ('chapters' in batotoJSON){ $.each(batotoJSON.chapters, function(index, val) { addRowToTable(val); }); } } $("#urlEntry").keypress(function (e) { if (e.which == 13){ var val = $(this).val(); parseUrl(val); $(this).val(''); return false; } }); if (isReadClipboard()){ readClipboard(); } }); }); function readClipboard(){ var data = clipboard.readText(); console.log('Clipboard: '+data); if (data.length > 0 && batotoRegex.test(data)){ console.log('test succeeded'); clipboard.writeText(''); //Clear clipboard, so we don't parse the same url twice var matches = data.match(batotoRegex); console.log(matches); var len = matches.length; for (var index = 0; i < len; index++){ parseUrl(matches[index]); } } setTimeout(readClipboard,1000); }
$(function(){ readFileIntoBuffer(batotoJSONFile, function(buffer){ if (buffer){ batotoJSON = JSON.parse(buffer); if ('chapters' in batotoJSON){ $.each(batotoJSON.chapters, function(index, val) { addRowToTable(val); }); } } $("#urlEntry").keypress(function (e) { if (e.which == 13){ var val = $(this).val(); parseUrl(val); $(this).val(''); return false; } }); if (isReadClipboard()){ readClipboard(); } checkRssFeed(true); }); }); function readClipboard(){ var data = clipboard.readText(); console.log('Clipboard: '+data); if (data.length > 0 && batotoRegex.test(data)){ console.log('test succeeded'); clipboard.writeText(''); //Clear clipboard, so we don't parse the same url twice var matches = data.match(batotoRegex); console.log(matches); var len = matches.length; for (var index = 0; i < len; index++){ parseUrl(matches[index]); } } setTimeout(readClipboard,1000); }
Check RSS feed on startup
Check RSS feed on startup
JavaScript
mit
koroshiya/batoto-downloader-node,koroshiya/batoto-downloader-node
--- +++ @@ -24,6 +24,8 @@ readClipboard(); } + checkRssFeed(true); + }); });
a9692fdee6f63e4891b419fa9fa6cfafbe932df9
js/main.js
js/main.js
document .querySelectorAll('pre') .forEach(node => { node.title = 'Copy to clipboard'; node.classList.add('copy'); node.onclick = function (event) { navigator.clipboard.writeText(event.target.innerText); }; }); (function () { const themes = [ 'light', 'dark', 'markdown' ]; let theme = localStorage.getItem('theme') || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); const updateTheme = function () { document.body.className = theme; if (theme === 'markdown') { document.querySelectorAll('img').forEach(node => { node.dataset.src = node.src; node.src = ''; }); } else { document.querySelectorAll('img').forEach(node => { node.src = node.dataset.src || node.src; }); } }; updateTheme(); const themeSwitch = document.getElementById('theme-switch'); themeSwitch.style.display = null; themeSwitch.onclick = function () { theme = themes[(themes.indexOf(theme) + 1) % themes.length]; localStorage.setItem('theme', theme); updateTheme(); }; }()); (function () { if (navigator.doNotTrack === '1' || localStorage.getItem('dnt')) return; const payload = { location: document.location.pathname, referrer: document.referrer }; fetch( 'https://log.lusmo.re/api/log', { method: 'POST', body: JSON.stringify(payload) } ); }());
document .querySelectorAll('pre') .forEach(node => { node.title = 'Copy to clipboard'; node.classList.add('copy'); node.onclick = function (event) { navigator.clipboard.writeText(event.target.innerText); }; }); (function () { const themes = [ 'light', 'dark', 'markdown' ]; let theme = localStorage.getItem('theme') || (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); const updateTheme = function () { document.body.className = theme; if (theme === 'markdown') { document.querySelectorAll('img').forEach(node => { node.dataset.src = node.src; node.src = ''; }); } else { document.querySelectorAll('img').forEach(node => { node.src = node.dataset.src || node.src; }); } }; updateTheme(); const themeSwitch = document.getElementById('theme-switch'); themeSwitch.style.display = null; themeSwitch.onclick = function () { theme = themes[(themes.indexOf(theme) + 1) % themes.length]; localStorage.setItem('theme', theme); updateTheme(); }; }()); (function () { if (navigator.doNotTrack === '1' || localStorage.getItem('dnt')) return; const payload = { location: document.location.pathname, referrer: document.referrer }; navigator.sendBeacon( 'https://log.lusmo.re/api/log', JSON.stringify(payload) ); }());
Switch from fetch to beacon
Switch from fetch to beacon
JavaScript
mit
CurtisLusmore/curtislusmore.github.io,CurtisLusmore/curtislusmore.github.io
--- +++ @@ -40,11 +40,8 @@ location: document.location.pathname, referrer: document.referrer }; - fetch( + navigator.sendBeacon( 'https://log.lusmo.re/api/log', - { - method: 'POST', - body: JSON.stringify(payload) - } + JSON.stringify(payload) ); }());
e32b9ccef5f15115650112b723eaa4e4346ae9c5
js/main.js
js/main.js
// TODO: don't just assume this is the homepage, account for the fact that the user might be visiting #blog/something // And don't forget to window.addEventListener('hashchange', () => {}, false) window.fetch('blog/manifest.json') .then(res => res.json()) .then(manifest => { const articleEls = manifest.map(meta => { const articleEl = document.createElement('article') const heading = document.createElement('h4') heading.textContent = meta.title articleEl.appendChild(heading) const previewParagraphs = meta.preview.split('\n').map(p => { const pEl = document.createElement('p') pEl.textContent = p return pEl }) for (let paragraph of previewParagraphs) { articleEl.appendChild(paragraph) } const readMore = document.createElement('a') readMore.textContent = 'Read more' readMore.className = 'read-more' readMore.href = '#blog/' + encodeURIComponent(meta.date) articleEl.appendChild(readMore) }) const blogEl = document.getElementById('blog') blogEl.innerHTML = '' // Remove the old content which tells users that the blog hasn't loaded yet for (let articleEl of articleEls) { blogEl.appendChild(articleEl) } })
Write some of the code for loading blog posts
Write some of the code for loading blog posts
JavaScript
isc
jamescostian/jamescostian.com,jamescostian/jamescostian.com,jamescostian/jamescostian.github.io,jamescostian/jamescostian.com,jamescostian/jamescostian.github.io
--- +++ @@ -0,0 +1,30 @@ +// TODO: don't just assume this is the homepage, account for the fact that the user might be visiting #blog/something +// And don't forget to window.addEventListener('hashchange', () => {}, false) +window.fetch('blog/manifest.json') + .then(res => res.json()) + .then(manifest => { + const articleEls = manifest.map(meta => { + const articleEl = document.createElement('article') + const heading = document.createElement('h4') + heading.textContent = meta.title + articleEl.appendChild(heading) + const previewParagraphs = meta.preview.split('\n').map(p => { + const pEl = document.createElement('p') + pEl.textContent = p + return pEl + }) + for (let paragraph of previewParagraphs) { + articleEl.appendChild(paragraph) + } + const readMore = document.createElement('a') + readMore.textContent = 'Read more' + readMore.className = 'read-more' + readMore.href = '#blog/' + encodeURIComponent(meta.date) + articleEl.appendChild(readMore) + }) + const blogEl = document.getElementById('blog') + blogEl.innerHTML = '' // Remove the old content which tells users that the blog hasn't loaded yet + for (let articleEl of articleEls) { + blogEl.appendChild(articleEl) + } + })
dbeda452160fac9be0157de82a91a8db44b09e49
src/js/actions/actions.js
src/js/actions/actions.js
import AppDispatcher from '../dispatchers/dispatcher'; import AppConstants from '../constants/constants'; export default { switchView: viewType => { AppDispatcher.dispatch({ actionType: AppConstants.SWITCH_VIEW, payload: {viewType} }); }, addField: () => { AppDispatcher.dispatch({ actionType: AppConstants.ADD_FIELD }); }, removeField: key => { AppDispatcher.dispatch({ actionType: AppConstants.REMOVE_FIELD, payload: {key} }); }, addInputValue: ({key, value}) => { AppDispatcher.dispatch({ actionType: AppConstants.ADD_INPUT_VALUE, payload: {key, value} }); }, setEnable: enable => { AppDispatcher.dispatch({ actionType: AppConstants.SET_ENABLE, payload: {enable} }); }, setAutoUpdate: autoUpdate => { AppDispatcher.dispatch({ actionType: AppConstants.SET_AUTO_UPDATE, payload: {autoUpdate} }); }, setUpdateFrequency: updateFrequency => { AppDispatcher.dispatch({ actionType: AppConstants.SET_UPDATE_FREQUENCY, payload: {updateFrequency} }); }, saveConfiguration: () => { AppDispatcher.dispatch({ actionType: AppConstants.SAVE_CONFIGURATION }); } }
import AppDispatcher from '../dispatchers/dispatcher'; import AppConstants from '../constants/constants'; export default { switchView: viewType => { AppDispatcher.dispatch({ actionType: AppConstants.SWITCH_VIEW, payload: {viewType} }); }, addField: () => { AppDispatcher.dispatch({ actionType: AppConstants.ADD_FIELD }); }, removeField: key => { AppDispatcher.dispatch({ actionType: AppConstants.REMOVE_FIELD, payload: {key} }); }, addInputValue: ({key, value}) => { AppDispatcher.dispatch({ actionType: AppConstants.ADD_INPUT_VALUE, payload: {key, value} }); }, addIgnoredStyleSheetKey: ({key, value}) => { AppDispatcher.dispatch({ actionType: AppConstants.ADD_IGNORED_STYLESHEET, payload: {key, value} }); }, setEnable: enable => { AppDispatcher.dispatch({ actionType: AppConstants.SET_ENABLE, payload: {enable} }); }, setAutoUpdate: autoUpdate => { AppDispatcher.dispatch({ actionType: AppConstants.SET_AUTO_UPDATE, payload: {autoUpdate} }); }, setUpdateFrequency: updateFrequency => { AppDispatcher.dispatch({ actionType: AppConstants.SET_UPDATE_FREQUENCY, payload: {updateFrequency} }); }, saveConfiguration: () => { AppDispatcher.dispatch({ actionType: AppConstants.SAVE_CONFIGURATION }); } }
Add action to ignore original stylesheets
Add action to ignore original stylesheets
JavaScript
mit
dashukin/StyleMe,dashukin/StyleMe
--- +++ @@ -26,6 +26,12 @@ payload: {key, value} }); }, + addIgnoredStyleSheetKey: ({key, value}) => { + AppDispatcher.dispatch({ + actionType: AppConstants.ADD_IGNORED_STYLESHEET, + payload: {key, value} + }); + }, setEnable: enable => { AppDispatcher.dispatch({ actionType: AppConstants.SET_ENABLE,
13023a53e718d2b46b83bde5277c19dae31d3f1a
.template-lintrc.js
.template-lintrc.js
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': false, 'self-closing-void-elements': false, 'img-alt-attributes': false, 'link-rel-noopener': false, 'invalid-interactive': false, 'inline-link-to': false, 'style-concatenation': false, 'triple-curlies': false, 'deprecated-each-syntax': false, } };
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': true, 'self-closing-void-elements': false, 'img-alt-attributes': false, 'link-rel-noopener': false, 'invalid-interactive': false, 'inline-link-to': true, 'style-concatenation': true, 'triple-curlies': false, 'deprecated-each-syntax': true, } };
Enable rules that already pass
Enable rules that already pass These rules pass with our current codebase and require no changes.
JavaScript
mit
stopfstedt/frontend,thecoolestguy/frontend,gabycampagna/frontend,djvoa12/frontend,dartajax/frontend,jrjohnson/frontend,gboushey/frontend,ilios/frontend,gabycampagna/frontend,ilios/frontend,thecoolestguy/frontend,stopfstedt/frontend,jrjohnson/frontend,gboushey/frontend,dartajax/frontend,djvoa12/frontend
--- +++ @@ -9,14 +9,14 @@ 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, - 'nested-interactive': false, + 'nested-interactive': true, 'self-closing-void-elements': false, 'img-alt-attributes': false, 'link-rel-noopener': false, 'invalid-interactive': false, - 'inline-link-to': false, - 'style-concatenation': false, + 'inline-link-to': true, + 'style-concatenation': true, 'triple-curlies': false, - 'deprecated-each-syntax': false, + 'deprecated-each-syntax': true, } };
2b90b97ccf3ac38efcdb756d6cceda88eb153779
src/daily-prices/DailyPricesCard.js
src/daily-prices/DailyPricesCard.js
import React, { PureComponent, PropTypes } from 'react'; import DailyPricesTable from './DailyPricesTable'; export default class DailyPricesCard extends PureComponent { static propTypes = { dailyPrices: PropTypes.array.isRequired, }; render() { const { dailyPrices } = this.props; return ( <div className="daily-prices-card scrollable"> <DailyPricesTable dailyPrices={dailyPrices} /> </div> ); } }
import React, { PureComponent, PropTypes } from 'react'; import DailyPricesTable from './DailyPricesTable'; import EmptySlate from '../containers/EmptySlate'; export default class DailyPricesCard extends PureComponent { static propTypes = { dailyPrices: PropTypes.array.isRequired, }; render() { const { dailyPrices } = this.props; return ( <div className="daily-prices-card scrollable"> {dailyPrices.length === 0 ? <EmptySlate img="img/daily-prices.svg" text="Daily prices data not available" /> : <DailyPricesTable dailyPrices={dailyPrices} />} </div> ); } }
Add empty slate for cases where daily prices is not allowed
Add empty slate for cases where daily prices is not allowed
JavaScript
mit
nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen
--- +++ @@ -1,5 +1,6 @@ import React, { PureComponent, PropTypes } from 'react'; import DailyPricesTable from './DailyPricesTable'; +import EmptySlate from '../containers/EmptySlate'; export default class DailyPricesCard extends PureComponent { @@ -12,7 +13,9 @@ return ( <div className="daily-prices-card scrollable"> - <DailyPricesTable dailyPrices={dailyPrices} /> + {dailyPrices.length === 0 ? + <EmptySlate img="img/daily-prices.svg" text="Daily prices data not available" /> : + <DailyPricesTable dailyPrices={dailyPrices} />} </div> ); }
f01a19cab57161665f147619251a1a7c671063ef
template/src/support/hooks.js
template/src/support/hooks.js
'use strict'; const dateFormat = require('dateformat'); const { defineSupportCode } = require('cucumber'); defineSupportCode(function ({ Before, After }) { Before(function () { browser.deleteCookie(); faker.locale = browser.options.locale; }); After(function (scenario) { // Delete cached data files const regexPathData = /src\/support\/data/; for (const key in require.cache) { if (require.cache[key] && key.match(regexPathData)) { delete require.cache[key]; } } if (scenario.isFailed()) { const errorDate = dateFormat(new Date(), 'yyyy-mm-dd-HHMMss'); return browser.saveScreenshot(`./output/errorShots/screenshot-error-${errorDate}.png`); } return Promise.resolve(); }); });
'use strict'; const dateFormat = require('dateformat'); const { defineSupportCode } = require('cucumber'); defineSupportCode(function ({ Before, After }) { Before(function () { browser.deleteCookie(); faker.locale = browser.options.locale; }); After(function (scenario) { if (scenario.isFailed()) { const errorDate = dateFormat(new Date(), 'yyyy-mm-dd-HHMMss'); return browser.saveScreenshot(`./output/errorShots/screenshot-error-${errorDate}.png`); } return Promise.resolve(); }); });
Remove now useless cache deletion
Remove now useless cache deletion
JavaScript
mit
nespresso/ntaf,nespresso/ntaf,nespresso/ntaf
--- +++ @@ -11,14 +11,6 @@ }); After(function (scenario) { - // Delete cached data files - const regexPathData = /src\/support\/data/; - for (const key in require.cache) { - if (require.cache[key] && key.match(regexPathData)) { - delete require.cache[key]; - } - } - if (scenario.isFailed()) { const errorDate = dateFormat(new Date(), 'yyyy-mm-dd-HHMMss'); return browser.saveScreenshot(`./output/errorShots/screenshot-error-${errorDate}.png`);
123a6d0455f38a72a102e9f12db33ae6f44bd7e4
ui/src/dashboards/constants/templateControlBar.js
ui/src/dashboards/constants/templateControlBar.js
import _ from 'lodash' import calculateSize from 'calculate-size' export const minDropdownWidth = 146 export const maxDropdownWidth = 300 export const dropdownPadding = 30 const valueLength = a => _.size(a.value) export const calculateDropdownWidth = (values = []) => { const longest = _.maxBy(values, valueLength) const longestValuePixels = calculateSize(longest.value, { font: 'Monospace', fontSize: '12px', }).width + dropdownPadding if (longestValuePixels < minDropdownWidth) { return minDropdownWidth } if (longestValuePixels > maxDropdownWidth) { return maxDropdownWidth } return longestValuePixels }
import _ from 'lodash' import calculateSize from 'calculate-size' export const minDropdownWidth = 120 export const maxDropdownWidth = 330 export const dropdownPadding = 30 const valueLength = a => _.size(a.value) export const calculateDropdownWidth = (values = []) => { const longest = _.maxBy(values, valueLength) const longestValuePixels = calculateSize(longest.value, { font: 'Monospace', fontSize: '12px', }).width + dropdownPadding if (longestValuePixels < minDropdownWidth) { return minDropdownWidth } if (longestValuePixels > maxDropdownWidth) { return maxDropdownWidth } return longestValuePixels }
Expand min and max sizes for tempvar dropdowns
Expand min and max sizes for tempvar dropdowns
JavaScript
mit
li-ang/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,nooproblem/influxdb
--- +++ @@ -1,8 +1,8 @@ import _ from 'lodash' import calculateSize from 'calculate-size' -export const minDropdownWidth = 146 -export const maxDropdownWidth = 300 +export const minDropdownWidth = 120 +export const maxDropdownWidth = 330 export const dropdownPadding = 30 const valueLength = a => _.size(a.value)
060575102436e6bf62cf9d66ac702cbfee754d52
src/services/series.service.js
src/services/series.service.js
import axios from 'Axios' export default { getSeries () { return axios.get('http://api.tvmaze.com/search/shows?q=bad') } }
export default { getSeries: () => fetch('http://api.tvmaze.com/search/shows?q=bad').then(res => res.json()) }
Use fetch instead of axios as http client
Use fetch instead of axios as http client
JavaScript
apache-2.0
GregoryBevan/devfest-vuejs,GregoryBevan/devfest-vuejs
--- +++ @@ -1,7 +1,3 @@ -import axios from 'Axios' - export default { - getSeries () { - return axios.get('http://api.tvmaze.com/search/shows?q=bad') - } + getSeries: () => fetch('http://api.tvmaze.com/search/shows?q=bad').then(res => res.json()) }
fe83e7fd3c4891600761524509f201fe5f512d77
static/data/select.js
static/data/select.js
const options = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel', disabled: true }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' }, ]; const groupedOptions = [ { label: "Flavors", options: [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, ] }, { label: "Colors", options: [ { label: 'Red', value: 'red' }, { label: 'Green', value: 'green' }, { label: 'Blue', value: 'blue' }, ] } ]; export default options; export { groupedOptions, options, }
import userAvatar1 from "../avatars/1.png"; import userAvatar2 from "../avatars/2.png"; import userAvatar3 from "../avatars/3.png"; import userAvatar4 from "../avatars/4.png"; const options = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel', isDisabled: true }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' }, ]; const customOptions = [ { label: 'Jane Smith', value: 'jane_smith', avatar: userAvatar1 }, { label: 'Jenny', value: 'jenny', avatar: userAvatar4, isDisabled: true }, { label: 'John Doe', value: 'john_doe', avatar: userAvatar2 }, { label: 'Molly', value: 'molly', avatar: userAvatar3 }, ]; const groupedOptions = [ { label: "Flavors", options: [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla', isDisabled: true }, { label: 'Strawberry', value: 'strawberry' }, ] }, { label: "Colors", options: [ { label: 'Red', value: 'red' }, { label: 'Green', value: 'green' }, { label: 'Blue', value: 'blue' }, ] } ]; export default options; export { customOptions, groupedOptions, options, }
Extend the static demo data with customOptions
Extend the static demo data with customOptions
JavaScript
mit
teamleadercrm/teamleader-ui
--- +++ @@ -1,10 +1,22 @@ +import userAvatar1 from "../avatars/1.png"; +import userAvatar2 from "../avatars/2.png"; +import userAvatar3 from "../avatars/3.png"; +import userAvatar4 from "../avatars/4.png"; + const options = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, - { label: 'Caramel', value: 'caramel', disabled: true }, + { label: 'Caramel', value: 'caramel', isDisabled: true }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' }, +]; + +const customOptions = [ + { label: 'Jane Smith', value: 'jane_smith', avatar: userAvatar1 }, + { label: 'Jenny', value: 'jenny', avatar: userAvatar4, isDisabled: true }, + { label: 'John Doe', value: 'john_doe', avatar: userAvatar2 }, + { label: 'Molly', value: 'molly', avatar: userAvatar3 }, ]; const groupedOptions = [ @@ -12,7 +24,7 @@ label: "Flavors", options: [ { label: 'Chocolate', value: 'chocolate' }, - { label: 'Vanilla', value: 'vanilla' }, + { label: 'Vanilla', value: 'vanilla', isDisabled: true }, { label: 'Strawberry', value: 'strawberry' }, ] }, @@ -28,6 +40,7 @@ export default options; export { + customOptions, groupedOptions, options, }
f63cf7de2b9aac613121f8af8e56002bd9b48af1
app/model/Plate.js
app/model/Plate.js
'use strict'; function makeString(foods) { return foods.toString(); } function update () { var labelSprite = _.find(this.sprite.children, function(child) { return child instanceof Phaser.Text; }); if (labelSprite) { labelSprite.setText(makeString(this.foods)); } } var Plate = function Plate(foods, sprite) { this.foods = foods; this.sprite = sprite; update.call(this); }; Plate.prototype.update = update; module.exports = Plate;
'use strict'; function makeString(foods) { return foods.join('\n'); } function update () { var labelSprite = _.find(this.sprite.children, function(child) { return child instanceof Phaser.Text; }); if (labelSprite) { var label = makeString(this.foods); labelSprite.setText(label); labelSprite.y = 20 - 30 * this.foods.length; } } var Plate = function Plate(foods, sprite) { this.foods = foods; this.sprite = sprite; update.call(this); }; Plate.prototype.update = update; module.exports = Plate;
Print foods in a vertical stack
Print foods in a vertical stack
JavaScript
mit
sirugh/not-chef-gamejam2015,sirugh/not-chef-gamejam2015,smcclellan/not-chef-gamejam2015,smcclellan/not-chef-gamejam2015
--- +++ @@ -1,7 +1,7 @@ 'use strict'; function makeString(foods) { - return foods.toString(); + return foods.join('\n'); } function update () { @@ -10,7 +10,9 @@ }); if (labelSprite) { - labelSprite.setText(makeString(this.foods)); + var label = makeString(this.foods); + labelSprite.setText(label); + labelSprite.y = 20 - 30 * this.foods.length; } }
47781cc92922512b03003b132796f71aaced7226
tests/javascripts/support/helpers/utilities.js
tests/javascripts/support/helpers/utilities.js
// general helpers, not related to the DOM and usable in different contexts // turn a list of key=value pairs (like tuples) into data that can be sent via AJAX // taken from https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript // but requiring an array as input rather than a hash, to preserve order of pairs function getFormDataFromPairs (pairs) { const urlEncodedDataPairs = []; pairs.forEach(pair => { urlEncodedDataPairs.push(`${window.encodeURIComponent(pair[0])}=${window.encodeURIComponent(pair[1])}`); }); // Combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions. return urlEncodedDataPairs.join('&').replace(/%20/g, '+'); }; exports.getFormDataFromPairs = getFormDataFromPairs;
// general helpers, not related to the DOM and usable in different contexts // turn a list of key=value pairs (like tuples) into data that can be sent via AJAX // taken from https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript // but requiring an array as input rather than a hash, to preserve order of pairs function getFormDataFromPairs (pairs) { const urlEncodedDataPairs = []; pairs.forEach(pair => { urlEncodedDataPairs.push(`${window.encodeURIComponent(pair[0])}=${window.encodeURIComponent(pair[1])}`); }); return urlEncodedDataPairs.join('&'); }; exports.getFormDataFromPairs = getFormDataFromPairs;
Change treatment of space character in URLs
Change treatment of space character in URLs jQuery changed it from using '+' to '%20' between versions 1 and 3. This updates the test to match.
JavaScript
mit
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
--- +++ @@ -13,9 +13,7 @@ }); - // Combine the pairs into a single string and replace all %-encoded spaces to - // the '+' character; matches the behaviour of browser form submissions. - return urlEncodedDataPairs.join('&').replace(/%20/g, '+'); + return urlEncodedDataPairs.join('&'); };
717f3b9c6ab18ae8916f90bd69d66dd48b8c5834
wgaPipeline_jasmine/spec/testing_LinksToCoords.js
wgaPipeline_jasmine/spec/testing_LinksToCoords.js
var karyo; var links; describe("link_to_coords", function(){ beforeEach(function(done){ loadKaryoFile(karyoFile, function(data){ karyo_to_coords(data); karyo=data; loadLinkFile(linkFile, function(data){ links=data; done(); }); }); }); it("should test if links and karyo are defined when they are returned from their functions", function(){ expect(karyo).not.toBeDefined(); expect(links).not.toBeDefined(); }); });
var karyo; var links; describe("link_to_coords", function(){ beforeEach(function(done){ loadKaryoFile(karyoFile, function(data){ karyo_to_coords(data); karyo=data; loadLinkFile(linkFile, function(data){ links=data; done(); }); }); }); it("should test if links and karyo are defined when they are returned from their functions", function(){ expect(karyo).toBeDefined(); expect(links).toBeDefined(); }); });
Test jetzt erfolgreich: karyo und links sind definiert
Test jetzt erfolgreich: karyo und links sind definiert
JavaScript
mit
BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV,AliTVTeam/AliTV,BioInf-Wuerzburg/AliTV
--- +++ @@ -16,8 +16,8 @@ }); it("should test if links and karyo are defined when they are returned from their functions", function(){ - expect(karyo).not.toBeDefined(); - expect(links).not.toBeDefined(); + expect(karyo).toBeDefined(); + expect(links).toBeDefined(); }); });
c474931ac1086fd95590e83a514624c4af4d70f1
test/eigensheep/curry_test.js
test/eigensheep/curry_test.js
(function() { module("R.curry"); var curry = require('eigensheep/curry')['default']; var adder = function(a, b, c, d) { return a + b + c + d; }; var curriedAdder = curry(adder); test("the function can be invoked as normal", function() { equal(curriedAdder(1, 2, 3, 4), 10); }); test("the function can be invoked in parts", function() { equal(curriedAdder(1)(2, 3, 4), 10); equal(curriedAdder(1, 2, 3)(4), 10); }); test("additional arguments don't hurt", function() { equal(curriedAdder(1, 2, 3, 4, 5), 10); equal(curriedAdder(1, 2, 3)(4, 5), 10); }); })();
(function() { module("R.curry"); var curry = require('eigensheep/curry')['default']; var adder = function(a, b, c, d) { return a + b + c + d; }; var curriedAdder = curry(adder); test("the function can be invoked as normal", function() { equal(curriedAdder(1, 2, 3, 4), 10); }); test("the function can be invoked in parts", function() { equal(curriedAdder(1)(2, 3, 4), 10); equal(curriedAdder(1, 2, 3)(4), 10); }); test("additional arguments don't hurt", function() { equal(curriedAdder(1, 2, 3, 4, 5), 10); equal(curriedAdder(1, 2, 3)(4, 5), 10); }); test("an arity can be explicitly specified", function() { var unsplat = function(a, b, c) { return [a, b, c]; }; var unsplat2 = curry(unsplat, 2); deepEqual(unsplat2(1, 2), [1, 2, undefined]); deepEqual(unsplat2(1)(2), [1, 2, undefined]); }); test("extra arguments are still passed through when an arity is specified", function() { var unsplat = function(a, b, c) { return [a, b, c]; }; var unsplat2 = curry(unsplat, 2); deepEqual(unsplat2(1, 2, 3), [1, 2, 3]); }); })();
Test explicitly specifying an arity in curry
Test explicitly specifying an arity in curry
JavaScript
mit
markprzepiora/eigensheep,markprzepiora/eigensheep,markprzepiora/eigensheep
--- +++ @@ -20,4 +20,24 @@ equal(curriedAdder(1, 2, 3, 4, 5), 10); equal(curriedAdder(1, 2, 3)(4, 5), 10); }); + + test("an arity can be explicitly specified", function() { + var unsplat = function(a, b, c) { + return [a, b, c]; + }; + var unsplat2 = curry(unsplat, 2); + + deepEqual(unsplat2(1, 2), [1, 2, undefined]); + deepEqual(unsplat2(1)(2), [1, 2, undefined]); + + }); + + test("extra arguments are still passed through when an arity is specified", function() { + var unsplat = function(a, b, c) { + return [a, b, c]; + }; + var unsplat2 = curry(unsplat, 2); + + deepEqual(unsplat2(1, 2, 3), [1, 2, 3]); + }); })();
f64a9adb9b1d5e1aa942a4f7eee5b434fd6a3b98
view/business-process-submitted-certificate.js
view/business-process-submitted-certificate.js
// Single certificate submitted view 'use strict'; var db = require('mano').db , endsWith = require('es5-ext/string/#/ends-with') , documentView = require('./components/business-process-document') , renderDocumentHistory = require('./components/business-process-document-history'); exports._parent = require('./business-process-submitted-documents'); exports._dynamic = require('./utils/document-dynamic-matcher')('certificate'); exports._match = 'document'; exports['selection-preview'] = function () { var doc = this.document; insert(documentView(doc, this.businessProcess.certificates.uploaded, { sideContent: [ doc.overviewSection.toDOM(document, { disableHeader: false }), doc.dataForm.constructor !== db.FormSectionBase ? doc.dataForm.toDOM(document, { customFilter: function (resolved) { return !endsWith.call(resolved.observable.dbId, 'files/map'); }, disableHeader: false }) : null ], appendContent: renderDocumentHistory(doc) })); };
// Single certificate submitted view 'use strict'; var db = require('mano').db , endsWith = require('es5-ext/string/#/ends-with') , documentView = require('./components/business-process-document') , renderDocumentHistory = require('./components/business-process-document-history'); exports._parent = require('./business-process-submitted-documents'); exports._dynamic = require('./utils/document-dynamic-matcher')('certificate'); exports._match = 'document'; exports['selection-preview'] = function () { var doc = this.document; insert(documentView(doc, this.businessProcess.certificates.uploaded, { sideContent: [ doc.overviewSection.toDOM(document, { disableHeader: false }), doc.dataForm.constructor !== db.FormSectionBase ? doc.dataForm.toDOM(document, { customFilter: function (resolved) { return !endsWith.call(resolved.observable.dbId, 'files/map'); }, disableHeader: false }) : null, renderDocumentHistory(doc) ] })); };
Move doc history to proper place.
Move doc history to proper place.
JavaScript
mit
egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations
--- +++ @@ -22,8 +22,8 @@ return !endsWith.call(resolved.observable.dbId, 'files/map'); }, disableHeader: false - }) : null - ], - appendContent: renderDocumentHistory(doc) + }) : null, + renderDocumentHistory(doc) + ] })); };
1f4bdfcd158b55740cbd7cda3deb96d01705affd
packages/redux-saga-requests-react/src/connected-operation-container.js
packages/redux-saga-requests-react/src/connected-operation-container.js
import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import PropTypes from 'prop-types'; import OperationContainer from './operation-container'; const ConnectedOperationContainer = connect( (state, { operation, requestSelector, operationType, operationCreator }) => ({ operation: operation || (requestSelector ? requestSelector(state).operations[ operationType || operationCreator.toString() ] : state.network.mutations[operationType] || {}), }), (dispatch, ownProps) => ({ sendOperation: ownProps.operationCreator ? bindActionCreators(ownProps.operationCreator, dispatch) : null, }), ( stateProps, dispatchProps, { requestSelector, operationType, operationCreator, ...ownProps }, ) => ({ ...ownProps, ...stateProps, ...dispatchProps, }), )(OperationContainer); ConnectedOperationContainer.propTypes /* remove-proptypes */ = { ...OperationContainer.propTypes, operation: PropTypes.oneOfType([ PropTypes.shape({ error: PropTypes.any, pending: PropTypes.number.isRequired, }), PropTypes.objectOf( PropTypes.shape({ error: PropTypes.any, pending: PropTypes.number.isRequired, }), ), ]), requestSelector: PropTypes.func, operationType: PropTypes.string, operationCreator: PropTypes.func, }; export default ConnectedOperationContainer;
import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import PropTypes from 'prop-types'; import OperationContainer from './operation-container'; const ConnectedOperationContainer = connect( (state, { operation, requestSelector, operationType, operationCreator }) => ({ operation: operation || (requestSelector ? requestSelector(state).operations[ operationType || operationCreator.toString() ] : state.network.mutations[ operationType || operationCreator.toString() ] || {}), }), (dispatch, ownProps) => ({ sendOperation: ownProps.operationCreator ? bindActionCreators(ownProps.operationCreator, dispatch) : null, }), ( stateProps, dispatchProps, { requestSelector, operationType, operationCreator, ...ownProps }, ) => ({ ...ownProps, ...stateProps, ...dispatchProps, }), )(OperationContainer); ConnectedOperationContainer.propTypes /* remove-proptypes */ = { ...OperationContainer.propTypes, operation: PropTypes.oneOfType([ PropTypes.shape({ error: PropTypes.any, pending: PropTypes.number.isRequired, }), PropTypes.objectOf( PropTypes.shape({ error: PropTypes.any, pending: PropTypes.number.isRequired, }), ), ]), requestSelector: PropTypes.func, operationType: PropTypes.string, operationCreator: PropTypes.func, }; export default ConnectedOperationContainer;
Use operationCreator instead of operationType in ConnectedOperationContainer
Use operationCreator instead of operationType in ConnectedOperationContainer
JavaScript
mit
klis87/redux-saga-requests,klis87/redux-saga-requests
--- +++ @@ -12,7 +12,9 @@ ? requestSelector(state).operations[ operationType || operationCreator.toString() ] - : state.network.mutations[operationType] || {}), + : state.network.mutations[ + operationType || operationCreator.toString() + ] || {}), }), (dispatch, ownProps) => ({ sendOperation: ownProps.operationCreator
05f7622f3f57493e9ecf86be08e951c8f5390765
assets/js/index.js
assets/js/index.js
var $ = require("jquery"); // Initialize player and register event handler var Player = new MidiPlayer.Player(); var playTrack = function (filename, pk) { // Load a MIDI file MIDIjs.stop(); MIDIjs.play(filename); $("#play-" + pk).hide(); $("pause-" + pk).show(); } var pauseTrack = function (pk) { MIDIjs.stop(); $("pause-" + pk).hide(); $("play-" + pk).show(); }
var $ = require("jquery"); var playTrack = function (filename, pk) { // Load a MIDI file MIDIjs.stop(); MIDIjs.play(filename); $("#play-" + pk).hide(); $("pause-" + pk).show(); } var pauseTrack = function (pk) { MIDIjs.stop(); $("pause-" + pk).hide(); $("play-" + pk).show(); } export default { playTrack: playTrack, pauseTrack: pauseTrack };
Update midi player javascript file
Update midi player javascript file
JavaScript
mit
adrienbrunet/fanfare_cuc,adrienbrunet/fanfare_cuc,adrienbrunet/fanfare_cuc
--- +++ @@ -1,8 +1,4 @@ var $ = require("jquery"); - - -// Initialize player and register event handler -var Player = new MidiPlayer.Player(); var playTrack = function (filename, pk) { // Load a MIDI file @@ -18,3 +14,7 @@ $("play-" + pk).show(); } +export default { + playTrack: playTrack, + pauseTrack: pauseTrack +};
aef0d296c9820e6d0552cd8211ef8e6336687158
tasks/load-options.js
tasks/load-options.js
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013-2014 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'); module.exports = function (grunt, options) { var config = {}; options = options || {}; options.folder = grunt.config.get('load-options.folder') || options.folder || './grunt'; options.configFolders = options.configFolders || ['config', 'options']; options.taskFolders = options.taskFolders || ['tasks', 'aliases']; // Load configuration. options.configFolders.forEach(function (configFolder) { var src = options.folder + '/' + configFolder; if (grunt.file.exists(src) && grunt.file.isDir(src)) { var obj = requireDirectory(module, src); Object.keys(obj).forEach(function (prop) { config[prop] = (typeof obj[prop] === 'function') ? obj[prop](grunt) : obj[prop]; }); } }); grunt.initConfig(config); // Load tasks. options.taskFolders.forEach(function (taskFolder) { var src = options.folder + '/' + taskFolder; if (grunt.file.exists(src) && grunt.file.isDir(src)) { grunt.loadTasks(src); } }); };
/* * grunt-load-options * https://github.com/chriszarate/grunt-load-options * * Copyright (c) 2013-2014 Chris Zarate * Licensed under the MIT license. */ 'use strict'; var requireDirectory = require('require-directory'), path = require('path'); module.exports = function (grunt, options) { var config = {}; options = options || {}; options.folder = grunt.config.get('load-options.folder') || options.folder || './grunt'; options.configFolders = options.configFolders || ['config', 'options']; options.taskFolders = options.taskFolders || ['tasks', 'aliases']; // Load configuration. options.configFolders.forEach(function (configFolder) { var src = path.resolve(path.join(options.folder, configFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { var obj = requireDirectory(module, src); Object.keys(obj).forEach(function (prop) { config[prop] = (typeof obj[prop] === 'function') ? obj[prop](grunt) : obj[prop]; }); } }); grunt.initConfig(config); // Load tasks. options.taskFolders.forEach(function (taskFolder) { var src = path.resolve(path.join(options.folder, taskFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { grunt.loadTasks(src); } }); };
Fix for downstream require-directory issues, make paths system-independent
Fix for downstream require-directory issues, make paths system-independent
JavaScript
mit
chriszarate/grunt-load-options
--- +++ @@ -8,7 +8,8 @@ 'use strict'; -var requireDirectory = require('require-directory'); +var requireDirectory = require('require-directory'), + path = require('path'); module.exports = function (grunt, options) { @@ -21,7 +22,7 @@ // Load configuration. options.configFolders.forEach(function (configFolder) { - var src = options.folder + '/' + configFolder; + var src = path.resolve(path.join(options.folder, configFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { var obj = requireDirectory(module, src); Object.keys(obj).forEach(function (prop) { @@ -33,7 +34,7 @@ // Load tasks. options.taskFolders.forEach(function (taskFolder) { - var src = options.folder + '/' + taskFolder; + var src = path.resolve(path.join(options.folder, taskFolder)); if (grunt.file.exists(src) && grunt.file.isDir(src)) { grunt.loadTasks(src); }
ddbc5ef3b3de89ad2427f23b4a36dcaad21c39eb
devices/lg-request.js
devices/lg-request.js
module.exports = function (RED) { function LgtvRequestNode(n) { RED.nodes.createNode(this, n); var node = this; this.tv = n.tv; this.tvConn = RED.nodes.getNode(this.tv); if (this.tvConn) { this.tvConn.register(node); this.on('close', function (done) { node.tvConn.deregister(node, done); }); node.on('input', function (msg) { node.tvConn.request(msg.topic, msg.payload, function (err, res) { if (!err) { node.send({payload: res}); } else { node.send({payload: false}); } }); }); } else { this.error('No TV Configuration'); } } RED.nodes.registerType('lgtv-request2', LgtvRequestNode); };
module.exports = function (RED) { function LgtvRequest2Node(n) { RED.nodes.createNode(this, n); var node = this; this.tv = n.tv; this.tvConn = RED.nodes.getNode(this.tv); if (this.tvConn) { this.tvConn.register(node); this.on('close', function (done) { node.tvConn.deregister(node, done); }); node.on('input', function (msg) { node.tvConn.request(msg.topic, msg.payload, function (err, res) { if (!err) { node.send({payload: res}); } else { node.send({payload: false}); } }); }); } else { this.error('No TV Configuration'); } } RED.nodes.registerType('lgtv-request2', LgtvRequest2Node); };
Make sure the device is detected as catgory
Make sure the device is detected as catgory
JavaScript
apache-2.0
azureru/node-red-contrib-homereru,azureru/node-red-contrib-homereru
--- +++ @@ -1,5 +1,5 @@ module.exports = function (RED) { - function LgtvRequestNode(n) { + function LgtvRequest2Node(n) { RED.nodes.createNode(this, n); var node = this; this.tv = n.tv; @@ -26,5 +26,5 @@ this.error('No TV Configuration'); } } - RED.nodes.registerType('lgtv-request2', LgtvRequestNode); + RED.nodes.registerType('lgtv-request2', LgtvRequest2Node); };
af57e195b84651e372645260e663e631beddf441
benchmark/index.js
benchmark/index.js
'use strict' let Benchmark = require('benchmark') let memoize1 = require('./1') let underscore = require('underscore').memoize // // Fibonacci suite // let fibonacci = (n) => { return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2) } let memoized1 = memoize1(fibonacci) let memoizedUnderscore = underscore(fibonacci) let suiteFibonnaci = new Benchmark.Suite() suiteFibonnaci .add('vanilla', () => { fibonacci(15) }) .add('algorithm1', () => { memoized1(15) }) .add('underscore', () => { memoizedUnderscore(15) }) .on('cycle', (event) => { console.log(String(event.target)) }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({'async': true})
'use strict' let Benchmark = require('benchmark') let memoize1 = require('./1') let underscore = require('underscore').memoize let lodash = require('lodash').memoize // // Fibonacci suite // let fibonacci = (n) => { return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2) } let memoized1 = memoize1(fibonacci) let memoizedUnderscore = underscore(fibonacci) let memoizedLodash = lodash(fibonacci) let suiteFibonnaci = new Benchmark.Suite() suiteFibonnaci .add('vanilla', () => { fibonacci(15) }) .add('algorithm1', () => { memoized1(15) }) .add('underscore', () => { memoizedUnderscore(15) }) .add('lodash', () => { memoizedLodash(15) }) .on('cycle', (event) => { console.log(String(event.target)) }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').map('name')) }) .run({'async': true})
Add `lodash.memoize` to benchmark suite
Add `lodash.memoize` to benchmark suite
JavaScript
mit
caiogondim/fast-memoize.js,caiogondim/fast-memoize.js,caiogondim/fast-memoize,caiogondim/fast-memoize.js
--- +++ @@ -3,6 +3,7 @@ let Benchmark = require('benchmark') let memoize1 = require('./1') let underscore = require('underscore').memoize +let lodash = require('lodash').memoize // // Fibonacci suite @@ -14,6 +15,7 @@ let memoized1 = memoize1(fibonacci) let memoizedUnderscore = underscore(fibonacci) +let memoizedLodash = lodash(fibonacci) let suiteFibonnaci = new Benchmark.Suite() @@ -27,6 +29,9 @@ .add('underscore', () => { memoizedUnderscore(15) }) + .add('lodash', () => { + memoizedLodash(15) + }) .on('cycle', (event) => { console.log(String(event.target)) })
e95cafa6f6e690adc823cc97c556ece7152b171a
src/languages/c.js
src/languages/c.js
define(function() { // Export return function(Prism) { Prism.languages.c = Prism.languages.extend('clike', { 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g, 'operator': /[-+]{1,2}|!=?|&lt;{1,2}=?|&gt;{1,2}=?|\-&gt;|={1,2}|\^|~|%|(&amp;){1,2}|\|?\||\?|\*|\//g }); Prism.languages.insertBefore('c', 'keyword', { //property class reused for macro statements 'property': /#\s*[a-zA-Z]+/g }); }; });
define(function() { return function(Prism) { Prism.languages.c = Prism.languages.extend('clike', { 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g, 'operator': /[-+]{1,2}|!=?|&lt;{1,2}=?|&gt;{1,2}=?|\-&gt;|={1,2}|\^|~|%|(&amp;){1,2}|\|?\||\?|\*|\//g }); Prism.languages.insertBefore('c', 'keyword', { //property class reused for macro statements 'property': /#\s*[a-zA-Z]+/g }); }; });
Fix indentation of the C grammar
Fix indentation of the C grammar
JavaScript
mit
apiaryio/prism
--- +++ @@ -1,18 +1,13 @@ define(function() { - - // Export return function(Prism) { - Prism.languages.c = Prism.languages.extend('clike', { - 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g, - 'operator': /[-+]{1,2}|!=?|&lt;{1,2}=?|&gt;{1,2}=?|\-&gt;|={1,2}|\^|~|%|(&amp;){1,2}|\|?\||\?|\*|\//g + 'keyword': /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/g, + 'operator': /[-+]{1,2}|!=?|&lt;{1,2}=?|&gt;{1,2}=?|\-&gt;|={1,2}|\^|~|%|(&amp;){1,2}|\|?\||\?|\*|\//g }); Prism.languages.insertBefore('c', 'keyword', { - //property class reused for macro statements - 'property': /#\s*[a-zA-Z]+/g + //property class reused for macro statements + 'property': /#\s*[a-zA-Z]+/g }); - }; - });
b97d5db5d27749b1ae20e3fd45192c9997450597
src/lib/HttpApi.js
src/lib/HttpApi.js
export default class HttpApi { constructor (prefix = '') { this.prefix = prefix this.opts = { credentials: 'same-origin', headers: new Headers({ 'Content-Type': 'application/json', }) } return this.callApi } callApi = (method, url, opts = {}) => { opts = Object.assign({}, this.opts, opts) opts.method = method if (typeof opts.body === 'object') { opts.body = JSON.stringify(opts.body) } return fetch(`/api/${this.prefix}${url}`, opts) .then(res => { if (res.status >= 200 && res.status < 300) { // success if (res.headers.get('Content-Type').includes('application/json')) { return res.json() } else { return res } } // error return res.text().then(txt => { return Promise.reject(new Error(txt)) }) }) } }
export default class HttpApi { constructor (prefix = '') { this.prefix = prefix this.opts = { credentials: 'same-origin', headers: new Headers({ 'Content-Type': 'application/json', }) } return this.callApi } callApi = (method, url, opts = {}) => { opts = Object.assign({}, this.opts, opts) opts.method = method if (typeof opts.body === 'object') { opts.body = JSON.stringify(opts.body) } return fetch(`/api/${this.prefix}${url}`, opts) .then(res => { if (res.ok) { const type = res.headers.get('Content-Type') return (type && type.includes('application/json')) ? res.json() : res.text() } // error return res.text().then(txt => { return Promise.reject(new Error(txt)) }) }) } }
Fix response handling when Content-Type header not present
Fix response handling when Content-Type header not present
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
--- +++ @@ -21,13 +21,9 @@ return fetch(`/api/${this.prefix}${url}`, opts) .then(res => { - if (res.status >= 200 && res.status < 300) { - // success - if (res.headers.get('Content-Type').includes('application/json')) { - return res.json() - } else { - return res - } + if (res.ok) { + const type = res.headers.get('Content-Type') + return (type && type.includes('application/json')) ? res.json() : res.text() } // error
d0f56db2d7688b07a8b592a5c95e31a100048250
src/Elcodi/Admin/CoreBundle/Resources/public/js/modules/on-off-table.js
src/Elcodi/Admin/CoreBundle/Resources/public/js/modules/on-off-table.js
FrontendCore.define('on-off-table', ['devicePackage' ], function () { return { onStart: function () { FrontendCore.requireAndStart('notification'); $('.switch input').each( function(){ var oTarget = this; $(oTarget).change( function() { var sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value ; $.ajax({ url: sUrl, type: 'post' }).fail( function( response ) { var sMessage = response.responseJSON.message !== undefined ? response.responseJSON.message : 'Sorry, something was wrong.'; FrontendMediator.publish( 'notification', { type : 'ko', message: sMessage } ); $(oTarget).click(); }); }); }); } }; });
FrontendCore.define('on-off-table', ['devicePackage' ], function () { return { onStart: function () { FrontendCore.requireAndStart('notification'); $('.switch input').each( function(){ var oTarget = this; $(oTarget).change( function() { var oInput = this, sValue = oInput.checked, sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value; $.ajax({ url: sUrl, type: 'post' }).fail( function( response ) { if ( sValue === true ) { oInput.checked = false; } else { oInput.checked = true; } var sMessage = response.responseJSON.message !== undefined ? response.responseJSON.message : 'Sorry, something was wrong.'; FrontendMediator.publish( 'notification', { type : 'ko', message: sMessage } ); }); }); }); } }; });
Set the radio to the previous status if there is a fail
Set the radio to the previous status if there is a fail
JavaScript
mit
sottosviluppo/bamboo,deliberryeng/bamboo,corretgecom/bamboo,elcodi/bamboo,atresmediahf/bamboo,isigoogling/bamboo,atresmediahf/bamboo,deliberryeng/bamboo,atresmediahf/bamboo,corretgecom/bamboo,atresmediahf/bamboo,deliberryeng/bamboo,corretgecom/bamboo,isigoogling/bamboo,corretgecom/bamboo,elcodi/bamboo,sottosviluppo/bamboo,deliberryeng/bamboo,isigoogling/bamboo,corretgecom/bamboo,isigoogling/bamboo,sottosviluppo/bamboo,atresmediahf/bamboo,elcodi/bamboo,elcodi/bamboo,isigoogling/bamboo,deliberryeng/bamboo,sottosviluppo/bamboo,sottosviluppo/bamboo,elcodi/bamboo
--- +++ @@ -10,15 +10,24 @@ $(oTarget).change( function() { - var sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value ; + var oInput = this, + sValue = oInput.checked, + sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value; $.ajax({ url: sUrl, type: 'post' }).fail( function( response ) { + + if ( sValue === true ) { + oInput.checked = false; + } else { + oInput.checked = true; + } + var sMessage = response.responseJSON.message !== undefined ? response.responseJSON.message : 'Sorry, something was wrong.'; FrontendMediator.publish( 'notification', { type : 'ko', message: sMessage } ); - $(oTarget).click(); + }); }); });
8f3f7e876b5f214cdf5924eaf4d6c391ead8a1ba
server/cli/init/base_file_sources/world.js
server/cli/init/base_file_sources/world.js
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ 'use strict'; var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
/*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ var CustomWorld = (function () { var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); var HttpBackendProxy = require('http-backend-proxy'); var CustomWorld = function CustomWorld () { browser = protractor = require('protractor').getInstance(); httpBackend = new HttpBackendProxy(browser, { buffer: true }); By = protractor.By; chai.use(chaiAsPromised); expect = chai.expect; Promise = require('bluebird'); }; return CustomWorld; })(); module.exports = function () { this.World = function (callback) { var w = new CustomWorld(); return callback(w); }; return this.World; };
Kill this use strict for now
Kill this use strict for now Should explicitly assign to global at some point I guess.
JavaScript
mit
TradeMe/tractor,Galileo1/tractor,Galileo1/tractor,yemo/tractor,TradeMe/tractor,TradeMe/tractor,yemo/tractor
--- +++ @@ -1,5 +1,4 @@ /*global browser:true, protractor:true, httpBackend:true, By:true, expect:true, Promise:true */ -'use strict'; var CustomWorld = (function () { var chai = require('chai');
1c1e682bb062912c0b5d76115cd726d359029706
plugin.js
plugin.js
var format = require("util").format; var TennuEval = { requires: ["admin"], init: function(client, imports) { function handleEval(IRCMessage) { return imports.admin.isAdmin(IRCMessage.hostmask) .then(function (result) { if(!result){ adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); } if(IRCMessage.message.search(/^\>\>/) > -1){ return ("<<"+eval(IRCMessage.message.substr(2))).split('\n'); } }) }; function adminFail(nickname, hostname) { return { intent: 'notice', query: true, message: ['Restricted access.', format('Logged: %s@%s.', nickname, hostname)] }; } return { handlers: { "privmsg": handleEval, } }; } }; module.exports = TennuEval;
var format = require("util").format; var TennuEval = { requires: ["admin"], init: function(client, imports) { function handleEval(IRCMessage) { if (IRCMessage.message.search(/^\>\>/) === -1) { return; } return imports.admin.isAdmin(IRCMessage.hostmask) .then(function(result) { if (!result) { return adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); } return ("<<" + eval(IRCMessage.message.substr(2))).split('\n'); }) }; function adminFail(nickname, hostname) { return { intent: 'notice', query: true, message: ['Restricted access.', format('Logged: %s@%s.', nickname, hostname)] }; } return { handlers: { "privmsg": handleEval, } }; } }; module.exports = TennuEval;
Check for eval match and exit right away. Fix not returning error messages.
Check for eval match and exit right away. Fix not returning error messages.
JavaScript
isc
Tennu/tennu-eval
--- +++ @@ -5,15 +5,18 @@ init: function(client, imports) { function handleEval(IRCMessage) { + + if (IRCMessage.message.search(/^\>\>/) === -1) { + return; + } + return imports.admin.isAdmin(IRCMessage.hostmask) - .then(function (result) { - if(!result){ - adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); - } - if(IRCMessage.message.search(/^\>\>/) > -1){ - return ("<<"+eval(IRCMessage.message.substr(2))).split('\n'); - } - }) + .then(function(result) { + if (!result) { + return adminFail(IRCMessage.nickname, IRCMessage.hostmask.hostname); + } + return ("<<" + eval(IRCMessage.message.substr(2))).split('\n'); + }) }; function adminFail(nickname, hostname) {
72e95f22f4d2ac09c0a05712320fee5fb68e94cb
src/native-shim.js
src/native-shim.js
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** * This shim allows elements written in, or compiled to, ES5 to work on native * implementations of Custom Elements v1. It sets new.target to the value of * this.constructor so that the native HTMLElement constructor can access the * current under-construction element's definition. */ (function() { if ( // No Reflect, no classes, no need for shim because native custom elements // require ES2015 classes or Reflect. window.Reflect === undefined || window.customElements === undefined || // The webcomponentsjs custom elements polyfill doesn't require // ES2015-compatible construction (`super()` or `Reflect.construct`). window.customElements.hasOwnProperty('polyfillWrapFlushCallback') ) { return; } const BuiltInHTMLElement = HTMLElement; window.HTMLElement = function() { return Reflect.construct(BuiltInHTMLElement, [], this.constructor); }; Object.setPrototypeOf(HTMLElement.prototype, BuiltInHTMLElement.prototype); Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement); })();
/** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** * This shim allows elements written in, or compiled to, ES5 to work on native * implementations of Custom Elements v1. It sets new.target to the value of * this.constructor so that the native HTMLElement constructor can access the * current under-construction element's definition. */ (function() { if ( // No Reflect, no classes, no need for shim because native custom elements // require ES2015 classes or Reflect. window.Reflect === undefined || window.customElements === undefined || // The webcomponentsjs custom elements polyfill doesn't require // ES2015-compatible construction (`super()` or `Reflect.construct`). window.customElements.hasOwnProperty('polyfillWrapFlushCallback') ) { return; } const BuiltInHTMLElement = HTMLElement; window.HTMLElement = function() { return Reflect.construct(BuiltInHTMLElement, [], this.constructor); }; HTMLElement.prototype = BuiltInHTMLElement.prototype; HTMLElement.prototype.constructor = HTMLElement; Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement); })();
Fix how `HTMLElement.prototype` is set.
Fix how `HTMLElement.prototype` is set.
JavaScript
bsd-3-clause
webcomponents/polyfills,webcomponents/polyfills,webcomponents/polyfills
--- +++ @@ -30,6 +30,7 @@ window.HTMLElement = function() { return Reflect.construct(BuiltInHTMLElement, [], this.constructor); }; - Object.setPrototypeOf(HTMLElement.prototype, BuiltInHTMLElement.prototype); + HTMLElement.prototype = BuiltInHTMLElement.prototype; + HTMLElement.prototype.constructor = HTMLElement; Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement); })();
5ca116299cec3bb6283b568ed7f846c2cdff9c95
plugins/osm-quickedit/public/main.js
plugins/osm-quickedit/public/main.js
PluginsAPI.Map.addActionButton(function(options){ if (options.tiles.length > 0){ // TODO: pick the topmost layer instead // of the first on the list, to support // maps that display multiple tasks. var tile = options.tiles[0]; var url = window.location.protocol + "//" + window.location.host + tile.url.replace(/tiles\.json$/, "tiles/{zoom}/{x}/{ty}.png"); return React.createElement("button", { type: "button", className: "btn btn-sm btn-secondary", onClick: function(){ var mapLocation = options.map.getZoom() + "/" + options.map.getCenter().lat + "/" + options.map.getCenter().lng; window.location.href = "https://www.openstreetmap.org/edit?editor=id#map=" + mapLocation + "&background=custom:" + url; } }, React.createElement("i", {className: "far fa-map"}, ""), " OSM Digitize"); } });
PluginsAPI.Map.addActionButton(function(options){ if (options.tiles.length > 0){ // TODO: pick the topmost layer instead // of the first on the list, to support // maps that display multiple tasks. var tile = options.tiles[0]; var url = window.location.protocol + "//" + window.location.host + tile.url + "tiles/{zoom}/{x}/{y}.png"; return React.createElement("button", { type: "button", className: "btn btn-sm btn-secondary", onClick: function(){ var mapLocation = options.map.getZoom() + "/" + options.map.getCenter().lat + "/" + options.map.getCenter().lng; window.location.href = "https://www.openstreetmap.org/edit?editor=id#map=" + mapLocation + "&background=custom:" + url; } }, React.createElement("i", {className: "far fa-map"}, ""), " OSM Digitize"); } });
Adjust url from custom baselayer in OSM
Adjust url from custom baselayer in OSM
JavaScript
agpl-3.0
OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM,OpenDroneMap/WebODM
--- +++ @@ -7,7 +7,7 @@ var tile = options.tiles[0]; var url = window.location.protocol + "//" + window.location.host + - tile.url.replace(/tiles\.json$/, "tiles/{zoom}/{x}/{ty}.png"); + tile.url + "tiles/{zoom}/{x}/{y}.png"; return React.createElement("button", { type: "button",
57ca5764aff77fe57edc493da9dd00793f27d6c6
src/clients/servicebus/ServiceBusClient.js
src/clients/servicebus/ServiceBusClient.js
'use strict'; const Promise = require('promise'); const azure = require('azure-sb'); const asyncEachLimit = require('async/eachLimit'); const trackDependency = require('../appinsights/AppInsightsClient').trackDependency; const SERVICE_BUS_CONNECTION_STRING = process.env.FORTIS_SB_CONN_STR; const MAX_CONCURRENT_BATCHES = process.env.MAX_CONCURRENT_BATCHES || 50; let client = azure.createServiceBusService(SERVICE_BUS_CONNECTION_STRING); /** * @param {string} queue * @param {Array<string>} messages * @returns {Promise} */ function sendMessages(queue, messages) { return new Promise((resolve, reject) => { if (!client) return reject('Failed to create service bus service. No service bus connection string provided.'); if (!messages || !messages.length) { return reject('No messages to be sent to service bus.'); } asyncEachLimit(messages, MAX_CONCURRENT_BATCHES, (message, asyncCallback) => { try { message => ({ body: JSON.stringify(message) }); } catch (exception) { asyncCallback(exception); } try { client.sendQueueMessage(queue, message, (error) => { if (error) asyncCallback(error); else asyncCallback(); }); } catch (exception) { asyncCallback(exception); } }, (error) => { if (error) reject(error); else resolve(); }); }); } module.exports = { sendMessages: trackDependency(sendMessages, 'ServiceBus', 'send') };
'use strict'; const Promise = require('promise'); const azure = require('azure-sb'); const trackDependency = require('../appinsights/AppInsightsClient').trackDependency; const SERVICE_BUS_CONNECTION_STRING = process.env.FORTIS_SB_CONN_STR; let client = azure.createServiceBusService(SERVICE_BUS_CONNECTION_STRING); /** * @param {string} queue * @param {string} message * @returns {Promise} */ function sendMessage(queue, message) { return new Promise((resolve, reject) => { if (!client) return reject('Failed to create service bus service. No service bus connection string provided.'); if (!message || !message.length) { return reject('No message to be sent to service bus.'); } try { message => ({ body: JSON.stringify(message) }); } catch (exception) { return reject(exception); } try { client.sendQueueMessage(queue, message, (error) => { if (error) reject(error); else resolve(message); }); } catch (exception) { reject(exception); } }); } module.exports = { sendMessages: trackDependency(sendMessage, 'ServiceBus', 'send') };
Change to send one message.
Change to send one message.
JavaScript
mit
CatalystCode/project-fortis-services,CatalystCode/project-fortis-services
--- +++ @@ -2,49 +2,41 @@ const Promise = require('promise'); const azure = require('azure-sb'); -const asyncEachLimit = require('async/eachLimit'); const trackDependency = require('../appinsights/AppInsightsClient').trackDependency; const SERVICE_BUS_CONNECTION_STRING = process.env.FORTIS_SB_CONN_STR; -const MAX_CONCURRENT_BATCHES = process.env.MAX_CONCURRENT_BATCHES || 50; let client = azure.createServiceBusService(SERVICE_BUS_CONNECTION_STRING); /** * @param {string} queue - * @param {Array<string>} messages + * @param {string} message * @returns {Promise} */ -function sendMessages(queue, messages) { +function sendMessage(queue, message) { return new Promise((resolve, reject) => { if (!client) return reject('Failed to create service bus service. No service bus connection string provided.'); - if (!messages || !messages.length) { - return reject('No messages to be sent to service bus.'); + if (!message || !message.length) { + return reject('No message to be sent to service bus.'); } - asyncEachLimit(messages, MAX_CONCURRENT_BATCHES, (message, asyncCallback) => { - try { - message => ({ body: JSON.stringify(message) }); - } catch (exception) { - asyncCallback(exception); - } + try { + message => ({ body: JSON.stringify(message) }); + } catch (exception) { + return reject(exception); + } - try { - client.sendQueueMessage(queue, message, (error) => { - if (error) asyncCallback(error); - else asyncCallback(); - }); - } catch (exception) { - asyncCallback(exception); - } - }, - (error) => { - if (error) reject(error); - else resolve(); - }); + try { + client.sendQueueMessage(queue, message, (error) => { + if (error) reject(error); + else resolve(message); + }); + } catch (exception) { + reject(exception); + } }); } module.exports = { - sendMessages: trackDependency(sendMessages, 'ServiceBus', 'send') + sendMessages: trackDependency(sendMessage, 'ServiceBus', 'send') };
e67b8a59b85259ee8a1bedeb09ea773c78c2f546
Dnn.AdminExperience/Library/Dnn.PersonaBar.UI/admin/personaBar/scripts/config.js
Dnn.AdminExperience/Library/Dnn.PersonaBar.UI/admin/personaBar/scripts/config.js
'use strict'; define(['jquery'], function ($) { return { init: function () { var inIframe = window !== window.top && typeof window.top.dnn !== "undefined"; var tabId = inIframe ? window.top.dnn.getVar('sf_tabId') : ''; var siteRoot = inIframe ? window.top.dnn.getVar('sf_siteRoot') : ''; var antiForgeryToken = inIframe ? window.top.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var config = $.extend({}, { tabId: tabId, siteRoot: siteRoot, antiForgeryToken: antiForgeryToken }, inIframe ? window.parent['personaBarSettings'] : {}); return config; } }; });
'use strict'; define(['jquery'], function ($) { return { init: function () { var inIframe = window.parent && typeof window.parent.dnn !== "undefined"; var tabId = inIframe ? window.parent.dnn.getVar('sf_tabId') : ''; var siteRoot = inIframe ? window.parent.dnn.getVar('sf_siteRoot') : ''; var antiForgeryToken = inIframe ? window.parent.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var config = $.extend({}, { tabId: tabId, siteRoot: siteRoot, antiForgeryToken: antiForgeryToken }, inIframe ? window.parent['personaBarSettings'] : {}); return config; } }; });
Fix PersonaBar loading when within an iframe
Fix PersonaBar loading when within an iframe
JavaScript
mit
dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform
--- +++ @@ -2,11 +2,11 @@ define(['jquery'], function ($) { return { init: function () { - var inIframe = window !== window.top && typeof window.top.dnn !== "undefined"; + var inIframe = window.parent && typeof window.parent.dnn !== "undefined"; - var tabId = inIframe ? window.top.dnn.getVar('sf_tabId') : ''; - var siteRoot = inIframe ? window.top.dnn.getVar('sf_siteRoot') : ''; - var antiForgeryToken = inIframe ? window.top.document.getElementsByName('__RequestVerificationToken')[0].value : ''; + var tabId = inIframe ? window.parent.dnn.getVar('sf_tabId') : ''; + var siteRoot = inIframe ? window.parent.dnn.getVar('sf_siteRoot') : ''; + var antiForgeryToken = inIframe ? window.parent.document.getElementsByName('__RequestVerificationToken')[0].value : ''; var config = $.extend({}, { tabId: tabId,
298ad6c11d5d13b0b1e7bc4ce5a4739d1e95c471
src/str-replace.js
src/str-replace.js
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( _token, index >= 0 ? index + newToken.length : 0 ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
var replaceAll = function( oldToken ) { var configs = this; return { from: function( string ) { return { to: function( newToken ) { var _token; var index = -1; if ( configs.ignoringCase ) { _token = oldToken.toLowerCase(); while(( index = string .toLowerCase() .indexOf( _token, index === -1 ? 0 : index + newToken.length ) ) !== -1 ) { string = string .substring( 0, index ) + newToken + string.substring( index + newToken.length ); } return string; } return string.split( oldToken ).join( newToken ); } }; }, ignoreCase: function() { return replaceAll.call({ ignoringCase: true }, oldToken ); } }; }; module.exports = { all: replaceAll };
Remove a check that is probably useless
Remove a check that is probably useless
JavaScript
mit
FagnerMartinsBrack/str-replace
--- +++ @@ -13,8 +13,7 @@ .toLowerCase() .indexOf( _token, - index >= 0 ? - index + newToken.length : 0 + index === -1 ? 0 : index + newToken.length ) ) !== -1 ) { string = string
50b1d41ab3e2f2bb44a66ba9620ec164d119a5ea
addon/initializers/ember-run-after.js
addon/initializers/ember-run-after.js
/** @module ember-flexberry */ import Ember from 'ember'; /** Injects 'after' method into 'Ember.run' namespace. @for ApplicationInitializer @method emberRunAfter.initialize @param {<a href="http://emberjs.com/api/classes/Ember.Application.html">Ember.Application</a>} application Ember application. */ export function initialize(application) { Ember.run.after = function(context, condition, handler) { let checkIntervalId; let checkInterval = 50; // Wait for condition fulfillment. Ember.run(() => { checkIntervalId = window.setInterval(() => { let conditionFulfilled = false; try { conditionFulfilled = condition.call(context) === true; } catch (e) { // Exception occurred while evaluating condition. // Clear interval & rethrow error. window.clearInterval(checkIntervalId); throw e; } if (!conditionFulfilled) { return; } // Condition is fulfilled. // Stop interval. window.clearInterval(checkIntervalId); // Call handler. Ember.run(() => { handler.call(context); }); }, checkInterval); }); }; } export default { name: 'ember-run-after', initialize };
/** @module ember-flexberry */ import Ember from 'ember'; /** Injects 'after' method into 'Ember.run' namespace. @for ApplicationInitializer @method emberRunAfter.initialize */ export function initialize() { Ember.run.after = function(context, condition, handler) { const checkInterval = 50; const checkCondition = () => { if (condition.call(context) === true) { Ember.run(context, handler); } else { Ember.run.later(checkCondition, checkInterval); } }; Ember.run.later(checkCondition, checkInterval); }; } export default { name: 'ember-run-after', initialize };
Fix falling out of the ember run loop in run.after method
Fix falling out of the ember run loop in run.after method
JavaScript
mit
Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry
--- +++ @@ -9,41 +9,20 @@ @for ApplicationInitializer @method emberRunAfter.initialize - @param {<a href="http://emberjs.com/api/classes/Ember.Application.html">Ember.Application</a>} application Ember application. */ -export function initialize(application) { +export function initialize() { Ember.run.after = function(context, condition, handler) { - let checkIntervalId; - let checkInterval = 50; + const checkInterval = 50; - // Wait for condition fulfillment. - Ember.run(() => { - checkIntervalId = window.setInterval(() => { - let conditionFulfilled = false; + const checkCondition = () => { + if (condition.call(context) === true) { + Ember.run(context, handler); + } else { + Ember.run.later(checkCondition, checkInterval); + } + }; - try { - conditionFulfilled = condition.call(context) === true; - } catch (e) { - // Exception occurred while evaluating condition. - // Clear interval & rethrow error. - window.clearInterval(checkIntervalId); - throw e; - } - - if (!conditionFulfilled) { - return; - } - - // Condition is fulfilled. - // Stop interval. - window.clearInterval(checkIntervalId); - - // Call handler. - Ember.run(() => { - handler.call(context); - }); - }, checkInterval); - }); + Ember.run.later(checkCondition, checkInterval); }; }
2e72a48b0b0f20b3ded8ed85381369c1cd7864f9
desktop/app/shared/database/parse.js
desktop/app/shared/database/parse.js
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now() - ((Date.now() % 86400000) - (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
Resolve commit about local time
Resolve commit about local time
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
--- +++ @@ -21,7 +21,7 @@ const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); - let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000)); + let start = Date.now() - ((Date.now() % 86400000) - (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; }
32480a30114ed967058490d19f081080e3609ece
app/scripts/components/quotas/filters.js
app/scripts/components/quotas/filters.js
// @ngInject export function quotaName($filter) { var names = { floating_ip_count: gettext('Floating IP count'), vcpu: gettext('vCPU count'), ram: gettext('RAM'), storage: gettext('Storage'), vm_count: gettext('Virtual machines count'), instances: gettext('Instances count'), volumes: gettext('Volumes count'), snapshots: gettext('Snapshots count'), cost: gettext('Monthly cost'), }; return function(name) { if (names[name]) { return names[name]; } name = name.replace(/_/g, ' '); return $filter('titleCase')(name); }; } // @ngInject export function quotaValue($filter) { var filters = { ram: 'filesize', storage: 'filesize', backup_storage: 'filesize', cost: 'defaultCurrency', }; return function(value, name) { if (value == -1) { return '∞'; } var filter = filters[name]; if (filter) { return $filter(filter)(value); } else { return value; } }; }
// @ngInject export function quotaName($filter) { var names = { floating_ip_count: gettext('Floating IP count'), vcpu: gettext('vCPU count'), ram: gettext('RAM'), storage: gettext('Storage'), vm_count: gettext('Virtual machines count'), instances: gettext('Instances count'), volumes: gettext('Volumes count'), snapshots: gettext('Snapshots count'), cost: gettext('Monthly cost'), }; return function(name) { if (names[name]) { return names[name]; } name = name.replace(/_/g, ' '); return $filter('titleCase')(name); }; } // @ngInject export function quotaValue($filter) { var filters = { ram: 'filesize', storage: 'filesize', volumes_size: 'filesize', snapshots_size: 'filesize', backup_storage: 'filesize', cost: 'defaultCurrency', }; return function(value, name) { if (value == -1) { return '∞'; } var filter = filters[name]; if (filter) { return $filter(filter)(value); } else { return value; } }; }
Format volume and snapshot size quota using filesize filter [WAL-813].
Format volume and snapshot size quota using filesize filter [WAL-813].
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -25,6 +25,8 @@ var filters = { ram: 'filesize', storage: 'filesize', + volumes_size: 'filesize', + snapshots_size: 'filesize', backup_storage: 'filesize', cost: 'defaultCurrency', };
5752383d3cf7fa1d26c6b4815d07443bed7df4b3
client/lib/i18n.js
client/lib/i18n.js
// We save the user language preference in the user profile, and use that to set // the language reactively. If the user is not connected we use the language // information provided by the browser, and default to english. Meteor.startup(() => { Tracker.autorun(() => { const currentUser = Meteor.user(); let language; if (currentUser) { language = currentUser.profile && currentUser.profile.language; } if (!language) { if(navigator.languages) { language = navigator.languages[0]; } else { language = navigator.language || navigator.userLanguage; } } if (language) { TAPi18n.setLanguage(language); T9n.setLanguage(language); } if (language === 'zh') { TAPi18n.setLanguage('zh_CN'); T9n.setLanguage('zh_CN'); } }); });
// We save the user language preference in the user profile, and use that to set // the language reactively. If the user is not connected we use the language // information provided by the browser, and default to english. Meteor.startup(() => { Tracker.autorun(() => { const currentUser = Meteor.user(); let language; if (currentUser) { language = currentUser.profile && currentUser.profile.language; } if (!language) { if(navigator.languages) { language = navigator.languages[0]; } else { language = navigator.language || navigator.userLanguage; } } if (language) { TAPi18n.setLanguage(language); T9n.setLanguage(language); } }); });
Revert code that broke changing language.
Revert code that broke changing language.
JavaScript
mit
jtickle/wekan,johnleeming/wekan,oliver4u/sap-wekan,ddanssaert/wekan,libreboard/libreboard,ddanssaert/wekan,johnleeming/wekan,wekan/wekan,johnleeming/wekan,nztqa/wekan,oliver4u/sap-wekan,GhassenRjab/wekan,wekan/wekan,ddanssaert/wekan,wekan/wekan,jtickle/wekan,GhassenRjab/wekan,mario-orlicky/wekan,jtickle/wekan,GhassenRjab/wekan,oliver4u/sap-wekan,nztqa/wekan,wekan/wekan,mario-orlicky/wekan,mario-orlicky/wekan,libreboard/libreboard,nztqa/wekan,wekan/wekan,johnleeming/wekan
--- +++ @@ -22,10 +22,5 @@ TAPi18n.setLanguage(language); T9n.setLanguage(language); } - - if (language === 'zh') { - TAPi18n.setLanguage('zh_CN'); - T9n.setLanguage('zh_CN'); - } }); });
0bb02cf1a8ce93baf95460d7b80c9b8b5ea5886d
router.js
router.js
var api = require("./api"); module.exports = function(app) { // View endpoints app.get("/", function(req, res) { res.sendFile(__dirname + "/views/index.html"); }); // API endpoints app.get("/api/repo/calculate", function(req, res) { var repository = req.param("repository"); api.calculateRepoStupidity(repository, function(data) { if (typeof data !== "object") { res.send({ success: 0, message: data }); } else { res.send({ success: 1, data: data }); } }); }); app.get("/api/language/calculate", function(req, res) { var language = req.param("language"); api.calculateLanguageStupidity(language, function(data) { if (typeof data !== "object") { res.send({ success: 0, message: data }); } else { res.send({ success: 1, data: data }); } }); }); };
var api = require("./api"); module.exports = function(app) { // View endpoints app.get("/", function(req, res) { res.sendFile(__dirname + "/views/index.html"); }); // API endpoints app.get("/api/repo/calculate", function(req, res) { var repository = req.query.repository; api.calculateRepoStupidity(repository, function(data) { if (typeof data !== "object") { res.send({ success: 0, message: data }); } else { res.send({ success: 1, data: data }); } }); }); app.get("/api/language/calculate", function(req, res) { var language = req.query.language; api.calculateLanguageStupidity(language, function(data) { if (typeof data !== "object") { res.send({ success: 0, message: data }); } else { res.send({ success: 1, data: data }); } }); }); };
Use req.query instead of req.param
Use req.query instead of req.param
JavaScript
mit
james9909/github-stupidity,james9909/github-stupidity
--- +++ @@ -9,7 +9,7 @@ // API endpoints app.get("/api/repo/calculate", function(req, res) { - var repository = req.param("repository"); + var repository = req.query.repository; api.calculateRepoStupidity(repository, function(data) { if (typeof data !== "object") { res.send({ @@ -26,7 +26,7 @@ }); app.get("/api/language/calculate", function(req, res) { - var language = req.param("language"); + var language = req.query.language; api.calculateLanguageStupidity(language, function(data) { if (typeof data !== "object") { res.send({
1c331377c5b3ea958ea514c0b9c0a71b598fba19
packages/strapi-plugin-content-manager/admin/src/components/LimitSelect/index.js
packages/strapi-plugin-content-manager/admin/src/components/LimitSelect/index.js
/** * * LimitSelect * */ import React from 'react'; // import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { map } from 'lodash'; import styles from './styles.scss'; class LimitSelect extends React.Component { componentWillMount() { const id = _.uniqueId(); this.setState({ id }); } /** * Return the list of default values to populate the select options * * @returns {number[]} */ getOptionsValues() { return [10, 20, 50, 100]; } render() { return ( <form className="form-inline"> <div className={styles.selectWrapper}> <select onChange={this.props.handleChange} className={`form-control ${styles.select}`} id={this.state.id} value={this.props.limit} > {map(this.getOptionsValues(), (optionValue, key) => <option value={optionValue} key={key}>{optionValue}</option>)} </select> </div> <label className={styles.label} htmlFor={this.state.id}> <FormattedMessage id="content-manager.components.LimitSelect.itemsPerPage" /> </label> </form> ); } } LimitSelect.propTypes = { handleChange: PropTypes.func.isRequired, limit: PropTypes.number.isRequired, }; export default LimitSelect;
/** * * LimitSelect * */ import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { map } from 'lodash'; import styles from './styles.scss'; class LimitSelect extends React.Component { componentWillMount() { const id = _.uniqueId(); this.setState({ id }); } /** * Return the list of default values to populate the select options * * @returns {number[]} */ getOptionsValues() { return [10, 20, 50, 100]; } render() { return ( <form className="form-inline"> <div className={styles.selectWrapper}> <select onChange={this.props.handleChange} className={`form-control ${styles.select}`} id={this.state.id} value={this.props.limit} > {map(this.getOptionsValues(), (optionValue, key) => <option value={optionValue} key={key}>{optionValue}</option>)} </select> </div> <label className={styles.label} htmlFor={this.state.id}> <FormattedMessage id="content-manager.components.LimitSelect.itemsPerPage" /> </label> </form> ); } } LimitSelect.propTypes = { handleChange: PropTypes.func.isRequired, limit: PropTypes.number.isRequired, }; export default LimitSelect;
Access proptypes via prop-types packages instead of React in LimitSelect component
Access proptypes via prop-types packages instead of React in LimitSelect component
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
--- +++ @@ -5,7 +5,7 @@ */ import React from 'react'; -// import PropTypes from 'prop-types'; +import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { map } from 'lodash'; import styles from './styles.scss';
a7500bc515c0d5fe0b7d9c6f0286423385385f24
core/processing.js
core/processing.js
'use strict'; const core = require('./core.js'); const fd = require('./field.js'); const service = require('./../services/services.js'); /* * Fonction qui traite les réponses de type bonjour */ function processingGrettings(response) { core.prepareMessage(response); } function processingHour(response) { if(response != undefined && response.result != undefined && response.result.parameters != undefined && response.result.parameters.ville != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{heure}") != -1) { console.log("je passe là"); service.getTimeAt(response.result.parameters.ville, function(hour) { console.log(hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); core.prepareMessage(response.result.fulfillment.speech); }); } } else { core.prepareMessage(response.result.fulfillment.speech); } } exports.processingGrettings = processingGrettings; exports.processingHour = processingHour;
'use strict'; const core = require('./core.js'); const fd = require('./field.js'); const serv = require('./../services/services.js'); /* * Fonction qui traite les réponses de type bonjour */ function processingGrettings(response) { core.prepareMessage(response); } function processingHour(response) { if(response != undefined && response.result != undefined && response.result.parameters != undefined && response.result.parameters.ville != undefined) { var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{heure}") != -1) { console.log(response.result.parameters.ville); serv.getTimeAt(response.result.parameters.ville, function(hour) { console.log("Hour : " + hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); console.log(response.result.fulfillment.speech); core.prepareMessage(response.result.fulfillment.speech); }); } } else { core.prepareMessage(response.result.fulfillment.speech); } } exports.processingGrettings = processingGrettings; exports.processingHour = processingHour;
Debug pour recherche d'un bug
Debug pour recherche d'un bug
JavaScript
apache-2.0
ArnaudFavier/Chatbot-GrandLyon,ArnaudFavier/Chatbot-GrandLyon,ArnaudFavier/Chatbot-GrandLyon,ArnaudFavier/Chatbot-GrandLyon
--- +++ @@ -2,7 +2,7 @@ const core = require('./core.js'); const fd = require('./field.js'); -const service = require('./../services/services.js'); +const serv = require('./../services/services.js'); /* * Fonction qui traite les réponses de type bonjour @@ -17,12 +17,13 @@ var fields = fd.extractFields(response.result.fulfillment.speech); console.log(fields); if(fields.indexOf("{heure}") != -1) { - console.log("je passe là"); - service.getTimeAt(response.result.parameters.ville, function(hour) { - console.log(hour); + console.log(response.result.parameters.ville); + serv.getTimeAt(response.result.parameters.ville, function(hour) { + console.log("Hour : " + hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{heure}",hour); response.result.fulfillment.speech = fd.replaceField(response.result.fulfillment.speech, "{\"ville\":[\"" + response.result.parameters.ville + "\"]}", response.result.parameters.ville); + console.log(response.result.fulfillment.speech); core.prepareMessage(response.result.fulfillment.speech); }); }
e7e43e75e1278a2ecec4c58daea7332e455f690c
src/views/picker-views/base-picker-view.js
src/views/picker-views/base-picker-view.js
'use strict'; var BaseView = require('../base-view'); function BasePickerView() { BaseView.apply(this, arguments); this._initialize(); } BasePickerView.prototype = Object.create(BaseView.prototype); BasePickerView.prototype.constructor = BasePickerView; BasePickerView.prototype._initialize = function () { this.element = document.createElement('div'); this.element.className = 'braintree-dropin__picker-view'; this.element.setAttribute('tabindex', '0'); this.element.addEventListener('click', this._onSelect.bind(this), false); this.element.addEventListener('keydown', function (event) { if (event.which === 13) { this._onSelect(); } }.bind(this)); }; module.exports = BasePickerView;
'use strict'; var BaseView = require('../base-view'); function BasePickerView() { BaseView.apply(this, arguments); this._initialize(); } BasePickerView.prototype = Object.create(BaseView.prototype); BasePickerView.prototype.constructor = BasePickerView; BasePickerView.prototype._initialize = function () { this.element = document.createElement('div'); this.element.className = 'braintree-dropin__picker-view'; this.element.setAttribute('tabindex', '0'); this.element.addEventListener('click', this._onSelect.bind(this), false); this.element.addEventListener('keydown', function (event) { if (event.which === 13) { this._onSelect(event); } }.bind(this)); }; module.exports = BasePickerView;
Fix enter keydown events in picker views
Fix enter keydown events in picker views
JavaScript
mit
braintree/braintree-web-drop-in,braintree/braintree-web-drop-in,braintree/braintree-web-drop-in
--- +++ @@ -19,7 +19,7 @@ this.element.addEventListener('click', this._onSelect.bind(this), false); this.element.addEventListener('keydown', function (event) { - if (event.which === 13) { this._onSelect(); } + if (event.which === 13) { this._onSelect(event); } }.bind(this)); };
aae866ef90170797c34732a328a76e21a3ec5caf
server.js
server.js
var dgram = require('dgram'), LogPacket = require('./logpacket.js'); var server = dgram.createSocket('udp4'); var secret = ""; function getAddress(address) { return address.address + ':' + address.port; } server.on('listening', function() { console.log('Server listening on ' + getAddress(server.address())); }); server.on('message', function(message, remote) { var packet = LogPacket.parse(new Buffer(message), (secret.length > 0) ? secret : undefined); console.log(getAddress(remote) + " - " + packet.toString()); }); server.on('close', function() { console.log('Closed server'); }); server.bind(1337);
var dgram = require('dgram'), LogPacket = require('./logpacket.js'); var server = dgram.createSocket('udp4'); var secret = ''; function getAddress(address) { return address.address + ':' + address.port; } server.on('listening', function() { console.log('Server listening on ' + getAddress(server.address())); }); server.on('message', function(message, remote) { var value = 'Invalid packet'; try { var packet = LogPacket.parse(new Buffer(message), (secret.length > 0) ? secret : undefined); value = packet.toString(); } catch (e) { value = 'Invalid packet [' + e.message + ']'; } console.log(getAddress(remote) + ' - ' + value); }); server.on('close', function() { console.log('Closed server'); }); server.bind(1337);
Replace quotes and ensure errors are handled
Replace quotes and ensure errors are handled
JavaScript
agpl-3.0
jackwilsdon/logaddress-protocol,jackwilsdon/logaddress-protocol
--- +++ @@ -3,7 +3,7 @@ var server = dgram.createSocket('udp4'); -var secret = ""; +var secret = ''; function getAddress(address) { return address.address + ':' + address.port; @@ -14,8 +14,17 @@ }); server.on('message', function(message, remote) { - var packet = LogPacket.parse(new Buffer(message), (secret.length > 0) ? secret : undefined); - console.log(getAddress(remote) + " - " + packet.toString()); + + var value = 'Invalid packet'; + + try { + var packet = LogPacket.parse(new Buffer(message), (secret.length > 0) ? secret : undefined); + value = packet.toString(); + } catch (e) { + value = 'Invalid packet [' + e.message + ']'; + } + + console.log(getAddress(remote) + ' - ' + value); }); server.on('close', function() {
9a3ca9a92f43d339f0c4c26444681b2033d48d8b
server.js
server.js
var express = require('express'); var http = require('http'); var url = require('url'); var restify = require('express-restify-mongoose'); var mongoose = require('mongoose'); var Artist = require('./api/models/artist'); var Faq = require('./api/models/faq'); var News = require('./api/models/news'); var Program = require('./api/models/program'); var Stage = require('./api/models/stage'); var mongourl = process.env.MONGOLAB_URI || 'mongodb://localhost/festapp-dev'; mongoose.connect(mongourl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("Yay"); }); var app = express(); app.use('/public', express.static(__dirname + '/public')); restify.serve(app, Artist); restify.serve(app, Faq); restify.serve(app, News); restify.serve(app, Program); restify.serve(app, Stage); var port = Number(process.env.PORT || 8080); http.createServer(app).listen(port); console.log('Running at port '+port);
var express = require('express'); var http = require('http'); // var url = require('url'); var restify = require('express-restify-mongoose'); var mongoose = require('mongoose'); var Artist = require('./api/models/artist'); var Faq = require('./api/models/faq'); var News = require('./api/models/news'); var Program = require('./api/models/program'); var Stage = require('./api/models/stage'); var mongourl = process.env.MONGOLAB_URI || 'mongodb://localhost/festapp-dev'; mongoose.connect(mongourl); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log('Yay'); }); var app = express(); app.use('/public', express.static(__dirname + '/public')); restify.serve(app, Artist); restify.serve(app, Faq); restify.serve(app, News); restify.serve(app, Program); restify.serve(app, Stage); var port = Number(process.env.PORT || 8080); http.createServer(app).listen(port); console.log('Running at port '+port);
Fix issues found by jshint
Fix issues found by jshint
JavaScript
mit
futurice/sec-conference-server,futurice/festapp-server,0is1/festapp-server,futurice/sec-conference-server
--- +++ @@ -1,6 +1,6 @@ var express = require('express'); var http = require('http'); -var url = require('url'); +// var url = require('url'); var restify = require('express-restify-mongoose'); var mongoose = require('mongoose'); @@ -15,7 +15,7 @@ var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { - console.log("Yay"); + console.log('Yay'); }); var app = express();
716fbbcb0ef4792724bd42acec44abf11343b46e
server.js
server.js
// DEPENDENCIES var express = require('express'); var app = express(); var port = process.env.PORT || process.argv[2] || 8080; app.use(express.static('public')); app.listen(port); console.log(`I can hear you on port ${port}!`);
// DEPENDENCIES var express = require('express'); var app = express(); var port = process.env.PORT || 8080; app.use(express.static('public')); app.listen(port); console.log(`I can hear you on port ${port}!`); module.exports.port = port;
Remove ability to pass port as arg
Remove ability to pass port as arg Cucumber adds arguments to server start command which caused the port to be assigned to NaN and it would break the server.
JavaScript
mit
Mctalian/HydroZone,Mctalian/HydroZone
--- +++ @@ -2,9 +2,11 @@ var express = require('express'); var app = express(); -var port = process.env.PORT || process.argv[2] || 8080; +var port = process.env.PORT || 8080; app.use(express.static('public')); app.listen(port); console.log(`I can hear you on port ${port}!`); + +module.exports.port = port;
942fdb3a8fe2c59570b2311cd272d73be83da2dc
src/scripts/minify-json/one-file.js
src/scripts/minify-json/one-file.js
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; export function convertOneFile(fileName, destFileName) { const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)}); const minify = fileContent => minifyJson(fileContent) .catch(() => {throw new InvalidJsonString()}); const writeFile = minifiedJson => fileWritePromise(destFileName, minifiedJson) .catch(reason => {throw new InvalidFile(reason.path)}); return readFile .then(minify) .then(writeFile); } const minifyJson = content => new Promise((resolve, reject) => { try { resolve(JSON.stringify(JSON.parse(content))); } catch (e) { reject(e); } });
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); export function convertOneFile(fileName, destFileName) { const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)}); const minify = fileContent => minifyJson(fileContent) .catch(() => {throw new InvalidJsonString()}); const writeFile = minifiedJson => fileWritePromise(destFileName, minifiedJson) .catch(reason => {throw new InvalidFile(reason.path)}); return readFile .then(minify) .then(writeFile); } const minifyJson = content => new Promise((resolve, reject) => { try { resolve(JSON.stringify(JSON.parse(content))); } catch (e) { reject(e); } });
Move promisified functions out of the actual function that uses them.
Move promisified functions out of the actual function that uses them.
JavaScript
mit
cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki,cosmowiki/cosmowiki
--- +++ @@ -6,10 +6,10 @@ InvalidJsonString } from './errors'; +const fileReadPromise = promisify(fs.readFile); +const fileWritePromise = promisify(fs.writeFile); + export function convertOneFile(fileName, destFileName) { - const fileReadPromise = promisify(fs.readFile); - const fileWritePromise = promisify(fs.writeFile); - const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)});
4517e696d163c0cd45d8caf73f0e7efa1d52d192
chrome/common/extensions/docs/examples/extensions/benchmark/script.js
chrome/common/extensions/docs/examples/extensions/benchmark/script.js
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, the location changed and the // benchmark stalls. var benchmarkExtensionUrl = window.location.toString(); function sendTimesToExtension() { var times = window.chrome.loadTimes(); if (times.finishLoadTime != 0) { benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times}); } else { window.setTimeout(sendTimesToExtension, 100); } } function loadComplete() { // Only trigger for top-level frames (e.g. the one we benchmarked) if (window.parent == window) { sendTimesToExtension(); } } window.addEventListener("load", loadComplete);
// The port for communicating back to the extension. var benchmarkExtensionPort = chrome.extension.connect(); // The url is what this page is known to the benchmark as. // The benchmark uses this id to differentiate the benchmark's // results from random pages being browsed. // TODO(mbelshe): If the page redirects, the location changed and the // benchmark stalls. var benchmarkExtensionUrl = window.location.toString(); function sendTimesToExtension() { if (window.parent != window) { return; } var times = window.chrome.loadTimes(); // If the load is not finished yet, schedule a timer to check again in a // little bit. if (times.finishLoadTime != 0) { benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times}); } else { window.setTimeout(sendTimesToExtension, 100); } } // We can't use the onload event because this script runs at document idle, // which may run after the onload has completed. sendTimesToExtension();
Update the benchmark to use the document.readyState to measure page-completedness rather than the onload event. Extensions were moved from the pre-onload state to running at document idle some time ago.
Update the benchmark to use the document.readyState to measure page-completedness rather than the onload event. Extensions were moved from the pre-onload state to running at document idle some time ago. BUG=none TEST=none Review URL: http://codereview.chromium.org/397013 git-svn-id: http://src.chromium.org/svn/trunk/src@32076 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: e079f6bc95496920f7c70cd95adf734203430f47
JavaScript
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
--- +++ @@ -10,8 +10,14 @@ var benchmarkExtensionUrl = window.location.toString(); function sendTimesToExtension() { + if (window.parent != window) { + return; + } + var times = window.chrome.loadTimes(); + // If the load is not finished yet, schedule a timer to check again in a + // little bit. if (times.finishLoadTime != 0) { benchmarkExtensionPort.postMessage({message: "load", url: benchmarkExtensionUrl, values: times}); } else { @@ -19,11 +25,6 @@ } } -function loadComplete() { - // Only trigger for top-level frames (e.g. the one we benchmarked) - if (window.parent == window) { - sendTimesToExtension(); - } -} - -window.addEventListener("load", loadComplete); +// We can't use the onload event because this script runs at document idle, +// which may run after the onload has completed. +sendTimesToExtension();
3b26c3787bc7d5c560565c5c9c36cf2c02934617
app/create-feed-from-gtfs/service.js
app/create-feed-from-gtfs/service.js
import Ember from 'ember'; export default Ember.Service.extend({ store: Ember.inject.service(), feedModel: null, createOrFindFeedModel: function() { if (this.get('feedModel') == null) { var newFeedModel = this.get('store').createRecord('feed', { }); this.set('feedModel', newFeedModel); } return this.get('feedModel'); }, downloadGtfsArchiveAndParseIntoFeedModel: function() { return true; } });
import Ember from 'ember'; export default Ember.Service.extend({ store: Ember.inject.service(), feedModel: null, createOrFindFeedModel: function() { if (this.get('feedModel') == null) { var newFeedModel = this.get('store').createRecord('feed', { }); this.set('feedModel', newFeedModel); } return this.get('feedModel'); }, downloadGtfsArchiveAndParseIntoFeedModel: function() { var feedModel = this.createOrFindFeedModel(); // var url = 'http://www.caltrain.com/Assets/GTFS/caltrain/GTFS-Caltrain-Devs.zip'; var url = feedModel.get('url'); var adapter = this.get('store').adapterFor('fetch_info'); var fetch_info_url = adapter.urlPrefix()+'/fetch_info'; var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}}); promise.then(function(response) { response.operators.map(function(operator){ feedModel.addOperator(operator) }); }); return promise } });
Call remote 'fetch_info' on feed, return promise
Call remote 'fetch_info' on feed, return promise
JavaScript
mit
transitland/feed-registry,transitland/feed-registry
--- +++ @@ -11,6 +11,17 @@ return this.get('feedModel'); }, downloadGtfsArchiveAndParseIntoFeedModel: function() { - return true; + var feedModel = this.createOrFindFeedModel(); + // var url = 'http://www.caltrain.com/Assets/GTFS/caltrain/GTFS-Caltrain-Devs.zip'; + var url = feedModel.get('url'); + var adapter = this.get('store').adapterFor('fetch_info'); + var fetch_info_url = adapter.urlPrefix()+'/fetch_info'; + var promise = adapter.ajax(fetch_info_url, 'post', {data:{url:url}}); + promise.then(function(response) { + response.operators.map(function(operator){ + feedModel.addOperator(operator) + }); + }); + return promise } });
32d179e240ee52163820580ef6278be919cc4510
test/fixtures/Gruntfile-execArgv.js
test/fixtures/Gruntfile-execArgv.js
module.exports = function(grunt) { grunt.registerTask('default', function(text) { var done = this.async(); grunt.util.spawn({ grunt: true, args: ['--gruntfile', 'Gruntfile-execArgv-child.js'], }, function(err, result, code) { var matches = result.stdout.match(/^(OUTPUT: .*)/m); console.log(matches ? matches[1] : ''); done(); }); }); };
module.exports = function(grunt) { var util = require('../../'); grunt.registerTask('default', function(text) { var done = this.async(); util.spawn({ grunt: true, args: ['--gruntfile', 'Gruntfile-execArgv-child.js'], }, function(err, result, code) { var matches = result.stdout.match(/^(OUTPUT: .*)/m); console.log(matches ? matches[1] : ''); done(); }); }); };
Test with this "util" lib, not grunt.util.
Test with this "util" lib, not grunt.util.
JavaScript
mit
gruntjs/grunt-legacy-util
--- +++ @@ -1,8 +1,10 @@ module.exports = function(grunt) { + + var util = require('../../'); grunt.registerTask('default', function(text) { var done = this.async(); - grunt.util.spawn({ + util.spawn({ grunt: true, args: ['--gruntfile', 'Gruntfile-execArgv-child.js'], }, function(err, result, code) {
8acb433305414b07bff24dd4fa8a7fd229f52d78
tests/fixtures/project-1/mup.old.js
tests/fixtures/project-1/mup.old.js
var config = require('./mup.js'); config.meteor.path = '../helloapp-old'; delete config.meteor.docker.image; module.exports = config;
var config = require('./mup.js'); config.meteor = config.app; delete config.app; config.meteor.path = '../helloapp-old'; delete config.meteor.docker.image; module.exports = config;
Fix test for deploying Meteor 1.2
Fix test for deploying Meteor 1.2
JavaScript
mit
zodern/meteor-up,zodern/meteor-up
--- +++ @@ -1,4 +1,7 @@ var config = require('./mup.js'); + +config.meteor = config.app; +delete config.app; config.meteor.path = '../helloapp-old'; delete config.meteor.docker.image;
2dbcb4a41a72dbab74bf1089dec40de4e3db9c8c
examples/looker.js
examples/looker.js
/* * This script will automaticly look at the closest entity. * It checks for a near entity every tick. */ const mineflayer = require('mineflayer') if (process.argv.length < 4 || process.argv.length > 6) { console.log('Usage : node echo.js <host> <port> [<name>] [<password>]') process.exit(1) } const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4] ? process.argv[4] : 'looker', password: process.argv[5] }) bot.once('spawn', function () { setInterval(() => { var entity = nearestEntity() if (entity) { if (entity.type === 'player') { bot.lookAt(entity.position.offset(0, 1.6, 0)) } else if (entity.type === 'mob') { bot.lookAt(entity.position) } } }, 50) }) function nearestEntity (type) { let id, entity, dist const best = null const bestDistance = null for (id in bot.entities) { entity = bot.entities[id] if (type && entity.type !== type) continue if (entity === bot.entity) continue dist = bot.entity.position.distanceTo(entity.position) if (!best || dist < bestDistance) { best = entity bestDistance = dist } } return best }
/* * This script will automaticly look at the closest entity. * It checks for a near entity every tick. */ const mineflayer = require('mineflayer') if (process.argv.length < 4 || process.argv.length > 6) { console.log('Usage : node echo.js <host> <port> [<name>] [<password>]') process.exit(1) } const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4] ? process.argv[4] : 'looker', password: process.argv[5] }) bot.once('spawn', function () { setInterval(() => { var entity = nearestEntity() if (entity) { if (entity.type === 'player') { bot.lookAt(entity.position.offset(0, 1.6, 0)) } else if (entity.type === 'mob') { bot.lookAt(entity.position) } } }, 50) }) function nearestEntity (type) { let id, entity, dist let best = null let bestDistance = null for (id in bot.entities) { entity = bot.entities[id] if (type && entity.type !== type) continue if (entity === bot.entity) continue dist = bot.entity.position.distanceTo(entity.position) if (!best || dist < bestDistance) { best = entity bestDistance = dist } } return best }
Use let instead of const
Use let instead of const
JavaScript
mit
andrewrk/mineflayer,PrismarineJS/mineflayer
--- +++ @@ -31,8 +31,8 @@ function nearestEntity (type) { let id, entity, dist - const best = null - const bestDistance = null + let best = null + let bestDistance = null for (id in bot.entities) { entity = bot.entities[id]
31d8a90ac3898920dd34827a3705c211f10aad7a
examples/simple.js
examples/simple.js
var mdns = require('../'); var TIMEOUT = 5000; //5 seconds var browser = new mdns.createBrowser(); //defaults to mdns.ServiceType.wildcard //var browser = new mdns.Mdns(mdns.tcp("googlecast")); //var browser = mdns.createBrowser(mdns.tcp("workstation")); browser.on('ready', function onReady() { console.log('browser is ready'); browser.discover(); }); browser.on('update', function onUpdate(data) { console.log('data:', data); }); //stop after 60 seconds setTimeout(function onTimeout() { browser.stop(); }, TIMEOUT);
var mdns = require('../'); var TIMEOUT = 5000; //5 seconds var browser = new mdns.createBrowser(); //defaults to mdns.ServiceType.wildcard //var browser = new mdns.Mdns(mdns.tcp("googlecast")); //var browser = mdns.createBrowser(mdns.tcp("workstation")); browser.on('ready', function onReady() { console.log('browser is ready'); browser.discover(); }); browser.on('update', function onUpdate(data) { console.log('data:', data); }); //stop after 5 seconds setTimeout(function onTimeout() { browser.stop(); }, TIMEOUT);
Fix a typo in example
Fix a typo in example
JavaScript
apache-2.0
simphax/node-mdns-js,kmpm/node-mdns-js,guerrerocarlos/node-mdns-js,LinusU/node-mdns-js,winkapp/node-mdns-js,mdns-js/node-mdns-js,mrose17/node-mdns-js
--- +++ @@ -17,7 +17,7 @@ console.log('data:', data); }); -//stop after 60 seconds +//stop after 5 seconds setTimeout(function onTimeout() { browser.stop(); }, TIMEOUT);
fc14cd735390731314586aac48e16eaf6b6bf907
client/js/reducers/assessment_meta.js
client/js/reducers/assessment_meta.js
"use strict"; import { Constants as AssessmentMetaConstants } from '../actions/assessment_meta'; const initialState = {}; export default (state = initialState, action) => { switch(action.type){ case AssessmentConstants.LOAD_ASSESSMENT_META: state = _.cloneDeep(action.payload) break; default: } return state; };
"use strict"; import { Constants as AssessmentMetaConstants } from '../actions/assessment_meta'; const initialState = {}; export default (state = initialState, action) => { switch(action.type){ case AssessmentConstants.LOAD_ASSESSMENT_META: return action.payload; } return state; };
Fix not returning the state
Fix not returning the state
JavaScript
mit
atomicjolt/open_assessments,atomicjolt/open_assessments,atomicjolt/OpenAssessmentsClient,atomicjolt/OpenAssessmentsClient,atomicjolt/open_assessments,atomicjolt/OpenAssessmentsClient
--- +++ @@ -8,10 +8,7 @@ switch(action.type){ case AssessmentConstants.LOAD_ASSESSMENT_META: - state = _.cloneDeep(action.payload) - break; - default: - + return action.payload; } return state; };
74fa1b6458ab5097cae05541a9de411f0ea3d4d3
tests/unit/controllers/node-test.js
tests/unit/controllers/node-test.js
import { moduleFor, test } from 'ember-qunit'; import Ember from 'ember'; moduleFor('controller:nodes.detail.files.provider.file', 'Unit | Controller | file', { // Specify the other units that are required for this test. needs: ['controller:nodes.detail.index'] }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); }); test('add a file tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one']})); ctrl.set('model.save', function() {return;}); ctrl.send('addATag', 'new tag'); assert.deepEqual(ctrl.model.get('tags'), ['one', 'new tag']); }); test('remove a file tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one', 'two']})); ctrl.set('model.save', function() {return;}); ctrl.send('removeATag', 'one'); assert.deepEqual(ctrl.model.get('tags'), ['two']); });
import { moduleFor, test } from 'ember-qunit'; import Ember from 'ember'; moduleFor('controller:nodes.detail.files.provider.file', 'Unit | Controller | file', { // Specify the other units that are required for this test. needs: ['controller:nodes.detail.index'] }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); }); test('add a node tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one']})); ctrl.set('model.save', function() {return;}); ctrl.send('addATag', 'new tag'); assert.deepEqual(ctrl.model.get('tags'), ['one', 'new tag']); }); test('remove a node tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one', 'two']})); ctrl.set('model.save', function() {return;}); ctrl.send('removeATag', 'one'); assert.deepEqual(ctrl.model.get('tags'), ['two']); });
Make test name more accurate.
Make test name more accurate.
JavaScript
apache-2.0
CenterForOpenScience/ember-osf,hmoco/ember-osf,baylee-d/ember-osf,crcresearch/ember-osf,jamescdavis/ember-osf,baylee-d/ember-osf,cwilli34/ember-osf,chrisseto/ember-osf,pattisdr/ember-osf,jamescdavis/ember-osf,pattisdr/ember-osf,cwilli34/ember-osf,binoculars/ember-osf,crcresearch/ember-osf,CenterForOpenScience/ember-osf,hmoco/ember-osf,chrisseto/ember-osf,binoculars/ember-osf
--- +++ @@ -12,7 +12,7 @@ assert.ok(controller); }); -test('add a file tag', function(assert) { +test('add a node tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one']})); ctrl.set('model.save', function() {return;}); @@ -20,7 +20,7 @@ assert.deepEqual(ctrl.model.get('tags'), ['one', 'new tag']); }); -test('remove a file tag', function(assert) { +test('remove a node tag', function(assert) { var ctrl = this.subject(); ctrl.set('model', Ember.Object.create({tags: ['one', 'two']})); ctrl.set('model.save', function() {return;});
6bb7f608cde0494ed1d2bd4d328164d0d309b012
client/apollo/js/View/TrackList/Hierarchical.js
client/apollo/js/View/TrackList/Hierarchical.js
define([ "dojo/_base/declare", 'JBrowse/View/TrackList/Hierarchical' ], function(declare,Hierarchical) { return declare('WebApollo.View.TrackList.Hierarchical',Hierarchical, { addTracks: function( tracks, inStartup ) { console.log(tracks); alert('Hello World'); this.inherited(arguments); } }); });
define([ "dojo/_base/declare", 'JBrowse/View/TrackList/Hierarchical' ], function(declare,Hierarchical) { return declare('WebApollo.View.TrackList.Hierarchical',Hierarchical, { // Subclass method for track selector to remove webapollo specific tracks addTracks: function( tracks, inStartup ) { for(i=0;i<tracks.length;i++) { if(tracks[i].label=="Annotations" || tracks[i].label=="DNA") { tracks.splice(i,1); i=0;//restart for safety } } //call superclass this.inherited(arguments); } }); });
Complete the modified hierarchical track selector to remove the 'Annotations' and 'DNA' tracks
Complete the modified hierarchical track selector to remove the 'Annotations' and 'DNA' tracks
JavaScript
bsd-3-clause
erasche/Apollo,erasche/Apollo,erasche/Apollo,erasche/Apollo,erasche/Apollo
--- +++ @@ -5,9 +5,15 @@ function(declare,Hierarchical) { return declare('WebApollo.View.TrackList.Hierarchical',Hierarchical, { + // Subclass method for track selector to remove webapollo specific tracks addTracks: function( tracks, inStartup ) { - console.log(tracks); - alert('Hello World'); + for(i=0;i<tracks.length;i++) { + if(tracks[i].label=="Annotations" || tracks[i].label=="DNA") { + tracks.splice(i,1); + i=0;//restart for safety + } + } + //call superclass this.inherited(arguments); } });
ae747854cd84ba4de204c8d040a43e1c7634da02
js/markext.js
js/markext.js
marked.setOptions({ langPrefix: 'language-', highlight: function(code, lang) { if (!Prism.languages[lang]) { return code; } return Prism.highlight(code, Prism.languages[lang]); }, renderer: (function(){ var renderMin = new marked.Renderer(); renderMin.table = function(header, body) { return '<table class=\'table\'>\n' + '<thead>\n' + header + '</thead>\n' + '<tbody>\n' + body + '</tbody>\n' + '</table>\n'; }; return renderMin; })() }); var md = document.getElementById('md'); md.innerHTML = marked(md.getAttribute('data-md'));
marked.setOptions({ langPrefix: 'language-', highlight: function(code, lang) { if (!Prism.languages[lang]) { return code; } return Prism.highlight(code, Prism.languages[lang]); }, }); var md = document.getElementById('md'); md.innerHTML = marked(md.getAttribute('data-md')); (function() { var tables = document.querySelectorAll('table'); for (var i = 0, tableElement ; tableElement = tables[i++] ; ) { tableElement.className = 'table'; } })();
Move table class to postprocessing step
Move table class to postprocessing step We don't want to do this as part of markdown rendering, because it makes our XSS filter more complicated. In general, we do not want to allow the user to specify their own class attributes. So every class attribute generated by the renderer becomes a special case for the filter. The fewer of those, the better.
JavaScript
bsd-3-clause
tummychow/goose,tummychow/goose
--- +++ @@ -6,21 +6,14 @@ } return Prism.highlight(code, Prism.languages[lang]); }, - renderer: (function(){ - var renderMin = new marked.Renderer(); - renderMin.table = function(header, body) { - return '<table class=\'table\'>\n' - + '<thead>\n' - + header - + '</thead>\n' - + '<tbody>\n' - + body - + '</tbody>\n' - + '</table>\n'; - }; - return renderMin; - })() }); var md = document.getElementById('md'); md.innerHTML = marked(md.getAttribute('data-md')); + +(function() { + var tables = document.querySelectorAll('table'); + for (var i = 0, tableElement ; tableElement = tables[i++] ; ) { + tableElement.className = 'table'; + } +})();
1c5cf901d3b25dbfb913d665754662afe1802ca7
karma.conf.js
karma.conf.js
module.exports = function(config) { config.set({ frameworks: [ 'jasmine', 'karma-typescript' ], plugins: [ 'karma-typescript', 'karma-jasmine', 'karma-edge-launcher', 'karma-firefox-launcher', 'karma-chrome-launcher' ], files: [ './src/*.ts', './test/*.ts' ], exclude: [ "**/*.d.ts", "**/*.js", "./node_modules" ], preprocessors: { '**/*.ts': ['karma-typescript'] }, karmaTypescriptConfig: { tsconfig: "./test/tsconfig.json", }, reporters: [ 'progress', 'karma-typescript' ], browsers: [ // 'Edge', 'Firefox' ], port: 9876, singleRun: true, }) }
module.exports = function(config) { config.set({ frameworks: [ 'jasmine', 'karma-typescript' ], plugins: [ 'karma-typescript', 'karma-jasmine', 'karma-edge-launcher', 'karma-firefox-launcher', 'karma-chrome-launcher' ], files: [ './src/*.ts', './test/*.ts' ], exclude: [ "**/*.d.ts", "**/*.js", "./node_modules" ], preprocessors: { '**/*.ts': ['karma-typescript'] }, karmaTypescriptConfig: { tsconfig: "./test/tsconfig.json", }, reporters: [ 'progress', 'karma-typescript' ], browsers: [ // 'Edge', 'Firefox', 'Chrome', ], port: 9876, singleRun: true, logLevel: config.LOG_INFO, }) }
Use Chrome as well as Firefox for the unit tests
Use Chrome as well as Firefox for the unit tests
JavaScript
mit
arogozine/LinqToTypeScript,arogozine/LinqToTypeScript
--- +++ @@ -1,7 +1,7 @@ module.exports = function(config) { config.set({ frameworks: [ - 'jasmine', + 'jasmine', 'karma-typescript' ], plugins: [ @@ -29,8 +29,11 @@ reporters: [ 'progress', 'karma-typescript' ], browsers: [ // 'Edge', - 'Firefox' ], + 'Firefox', + 'Chrome', ], port: 9876, singleRun: true, + + logLevel: config.LOG_INFO, }) }
917ac4d1e0dadd7bdde9e92320c61cf881680aca
db/models/index.js
db/models/index.js
// This file makes all join table relationships var Sequelize = require('sequelize'); var sequelize = new Sequelize('escape', 'escape', 'escapeacft', { dialect: 'mariadb', host: 'localhost' }); // Any vairable that starts with a capital letter is a model var User = require('./users.js')(sequelize, Sequelize); var Bookmark = require('./bookmarks.js')(sequelize, Sequelize); var BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize); // BookmarkUsers join table: User.belongsToMany(Bookmark, { through: 'bookmark_users', foreignKey: 'user_id' }); Bookmark.belongsToMany(User, { through: 'bookmark_users', foreignKey: 'bookmark_id' }); // sequelize.sync({force: true}); sequelize.sync(); exports.User = User; exports.Bookmark = Bookmark; exports.BookmarkUsers = BookmarkUsers;
// This file makes all join table relationships var Sequelize = require('sequelize'); var sequelize = new Sequelize('escape', 'escape', 'escapeacft', { dialect: 'mariadb', host: 'localhost' }); // Any vairable that starts with a capital letter is a model var User = require('./users.js')(sequelize, Sequelize); var Bookmark = require('./bookmarks.js')(sequelize, Sequelize); var BookmarkUsers = require('./bookmarkUsers')(sequelize, Sequelize); // BookmarkUsers join table: User.belongsToMany(Bookmark, { through: 'bookmark_users', foreignKey: 'user_id' }); Bookmark.belongsToMany(User, { through: 'bookmark_users', foreignKey: 'bookmark_id' }); //Create missing tables, if any // sequelize.sync({force: true}); sequelize.sync(); exports.User = User; exports.Bookmark = Bookmark; exports.BookmarkUsers = BookmarkUsers;
Add comment for code clarity
Add comment for code clarity
JavaScript
mit
lowtalkers/escape-reality,lowtalkers/escape-reality,francoabaroa/escape-reality,francoabaroa/escape-reality
--- +++ @@ -21,7 +21,7 @@ foreignKey: 'bookmark_id' }); - +//Create missing tables, if any // sequelize.sync({force: true}); sequelize.sync();
952209625838f57d5977b1117c5a2ce461832ca1
test/index.js
test/index.js
'use strict'; var expect = require('chai').expect, fs = require('fs'), path = require('path'), rulesDir = path.join(__dirname, '../lib/rules/'), plugin = require('..'); describe('eslint-plugin-mocha', function () { var ruleFiles; before(function (done) { fs.readdir(rulesDir, function (error, files) { ruleFiles = files; done(error); }); }); it('should expose all rules', function () { ruleFiles.forEach(function (file) { var ruleName = path.basename(file, '.js'); expect(plugin).to.have.deep.property('rules.' + ruleName) .that.equals(require(rulesDir + ruleName)); }); }); });
'use strict'; var expect = require('chai').expect, fs = require('fs'), path = require('path'), rulesDir = path.join(__dirname, '../lib/rules/'), documentationDir = path.join(__dirname, '../docs/rules/'), plugin = require('..'); describe('eslint-plugin-mocha', function () { var ruleFiles; before(function (done) { fs.readdir(rulesDir, function (error, files) { ruleFiles = files; done(error); }); }); it('should expose all rules', function () { ruleFiles.forEach(function (file) { var ruleName = path.basename(file, '.js'); expect(plugin).to.have.deep.property('rules.' + ruleName) .that.equals(require(rulesDir + ruleName)); }); }); describe('documentation', function () { var documentationFiles; before(function (done) { fs.readdir(documentationDir, function (error, files) { documentationFiles = files; done(error); }); }); it('should have each rule documented', function () { ruleFiles.forEach(function (file) { var ruleName = path.basename(file, '.js'), expectedDocumentationFileName = ruleName + '.md'; expect(documentationFiles).to.contain(expectedDocumentationFileName); }); }); }); });
Add test to ensure each rule is documented
Add test to ensure each rule is documented
JavaScript
mit
lo1tuma/eslint-plugin-mocha,alecxe/eslint-plugin-mocha
--- +++ @@ -4,6 +4,7 @@ fs = require('fs'), path = require('path'), rulesDir = path.join(__dirname, '../lib/rules/'), + documentationDir = path.join(__dirname, '../docs/rules/'), plugin = require('..'); describe('eslint-plugin-mocha', function () { @@ -24,4 +25,24 @@ .that.equals(require(rulesDir + ruleName)); }); }); + + describe('documentation', function () { + var documentationFiles; + + before(function (done) { + fs.readdir(documentationDir, function (error, files) { + documentationFiles = files; + done(error); + }); + }); + + it('should have each rule documented', function () { + ruleFiles.forEach(function (file) { + var ruleName = path.basename(file, '.js'), + expectedDocumentationFileName = ruleName + '.md'; + + expect(documentationFiles).to.contain(expectedDocumentationFileName); + }); + }); + }); });
aa109d9e6f3055273dbf14a3b848d087a1929443
test/setup.js
test/setup.js
import GraphQLJSClient from '../src/graphql-client'; function recordTypes() { const types = GraphQLJSClient.trackedTypes(); if (typeof require === 'function') { const body = JSON.stringify({'profiled-types': types}, null, ' '); require('fs').writeFileSync('profiled-types.json', body); } else { console.log(types); // eslint-disable-line no-console } } before(() => { if (!GraphQLJSClient.startTracking) { return; } GraphQLJSClient.startTracking(); }); after(() => { if (!GraphQLJSClient.startTracking) { return; } GraphQLJSClient.pauseTracking(); recordTypes(); });
import GraphQLJSClient from '../src/graphql-client'; function recordTypes() { const types = GraphQLJSClient.trackedTypes(); if (typeof require === 'function') { const body = JSON.stringify({'profiled-types': types}, null, 2); require('fs').writeFileSync('profiled-types.json', body); } else { console.log(types); // eslint-disable-line no-console } } before(() => { if (!GraphQLJSClient.startTracking) { return; } GraphQLJSClient.startTracking(); }); after(() => { if (!GraphQLJSClient.startTracking) { return; } GraphQLJSClient.pauseTracking(); recordTypes(); });
Use a number instead of hard coded spaces in json stringify
Use a number instead of hard coded spaces in json stringify
JavaScript
mit
Shopify/js-buy-sdk,Shopify/js-buy-sdk
--- +++ @@ -4,7 +4,7 @@ const types = GraphQLJSClient.trackedTypes(); if (typeof require === 'function') { - const body = JSON.stringify({'profiled-types': types}, null, ' '); + const body = JSON.stringify({'profiled-types': types}, null, 2); require('fs').writeFileSync('profiled-types.json', body); } else {
53fd1667b7db63ecc4d8508000467361650fe008
lib/create.js
lib/create.js
'use strict'; var React = require('react'); var api = require('./protocols/api'); var config = require('./config'); var getFactory = require('./factories').getFactory; var getReport = require('./util/getReport'); function create(type, opts) { var factory = getFactory(type, opts); var Form = React.createClass({ // the public api returns `null` if validation failed // unless the optional boolean argument `raw` is set to `true` getValue: function (raw) { var result = this.refs.input.getValue(); if (raw === true) { return result; } if (result.isValid()) { return result.value; } return null; }, render: function () { var ctx = new api.Context({ auto: api.Auto.defaultValue, i18n: config.i18n, label: null, name: '', report: getReport(type), templates: config.templates, value: this.props.value }); var Component = factory(opts, ctx); return React.createElement(Component, { onChange: this.props.onChange, ref: 'input' }); } }); return Form; } module.exports = create;
'use strict'; var React = require('react'); var api = require('./protocols/api'); var config = require('./config'); var getFactory = require('./factories').getFactory; var getReport = require('./util/getReport'); function create(type, opts) { var factory = getFactory(type, opts); var Form = React.createClass({ displayName: 'Form', // the public api returns `null` if validation failed // unless the optional boolean argument `raw` is set to `true` getValue: function (raw) { var result = this.refs.input.getValue(); if (raw === true) { return result; } if (result.isValid()) { return result.value; } return null; }, render: function () { var ctx = new api.Context({ auto: api.Auto.defaultValue, i18n: config.i18n, label: null, name: '', report: getReport(type), templates: config.templates, value: this.props.value }); var Component = factory(opts, ctx); return React.createElement(Component, { onChange: this.props.onChange, ref: 'input' }); } }); return Form; } module.exports = create;
Set displayName for Form class
Set displayName for Form class
JavaScript
mit
ieugen/tcomb-form,ashwinrayaprolu1984/tcomb-form,CBIConsulting/tcomb-form,geminiyellow/tcomb-form,gcanti/tcomb-form,ashwinrayaprolu1984/tcomb-form,CBIConsulting/tcomb-form,mvlach/tcomb-form,johnraz/tcomb-form,geminiyellow/tcomb-form
--- +++ @@ -11,6 +11,8 @@ var factory = getFactory(type, opts); var Form = React.createClass({ + + displayName: 'Form', // the public api returns `null` if validation failed // unless the optional boolean argument `raw` is set to `true`
122bd75b6485218799923b25700a985fe6d78dba
ui/src/kapacitor/constants/index.js
ui/src/kapacitor/constants/index.js
export const defaultRuleConfigs = { deadman: { period: '10m', }, relative: { change: 'change', period: '1m', shift: '1m', operator: 'greater than', value: '90', }, threshold: { operator: 'greater than', value: '90', relation: 'once', percentile: '90', period: '1m', }, }; export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to']; // export const RELATIONS = ['once', 'more than ', 'less than']; export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d']; export const CHANGES = ['change', '% change']; export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d']; export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops']; export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
export const defaultRuleConfigs = { deadman: { period: '10m', }, relative: { change: 'change', period: '1m', shift: '1m', operator: 'greater than', value: '90', }, threshold: { operator: 'greater than', value: '90', relation: 'once', percentile: '90', period: '1m', }, }; export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to']; // export const RELATIONS = ['once', 'more than ', 'less than']; export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h']; export const CHANGES = ['change', '% change']; export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h']; export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops']; export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
Change all 1d to 24h
Change all 1d to 24h
JavaScript
mit
nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdata/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,li-ang/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdata/influxdb
--- +++ @@ -20,9 +20,9 @@ export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to']; // export const RELATIONS = ['once', 'more than ', 'less than']; -export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d']; +export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h']; export const CHANGES = ['change', '% change']; -export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d']; +export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h']; export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops']; export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
6f200fd0036eb919578245af5d616c6e65f40cd8
modules/shared/services/api/api-config.constant.js
modules/shared/services/api/api-config.constant.js
(function () { 'use strict'; angular .module('dpShared') .constant('API_CONFIG', { ROOT: 'https://api-acc.datapunt.amsterdam.nl/', AUTH: 'https://api.datapunt.amsterdam.nl/authenticatie/' }); })();
(function () { 'use strict'; angular .module('dpShared') .constant('API_CONFIG', { ROOT: 'https://api.datapunt.amsterdam.nl/', AUTH: 'https://api.datapunt.amsterdam.nl/authenticatie/' }); })();
Remove the reference to acc, now refers to prod again.
Remove the reference to acc, now refers to prod again.
JavaScript
mpl-2.0
Amsterdam/atlas,DatapuntAmsterdam/atlas,Amsterdam/atlas,Amsterdam/atlas,DatapuntAmsterdam/atlas,DatapuntAmsterdam/atlas,DatapuntAmsterdam/atlas_prototype,DatapuntAmsterdam/atlas_prototype,Amsterdam/atlas
--- +++ @@ -4,7 +4,7 @@ angular .module('dpShared') .constant('API_CONFIG', { - ROOT: 'https://api-acc.datapunt.amsterdam.nl/', + ROOT: 'https://api.datapunt.amsterdam.nl/', AUTH: 'https://api.datapunt.amsterdam.nl/authenticatie/' }); })();
391d8d28ef5dfd066b2995150bd45a1ba0857282
gulp/tasks/helpers.js
gulp/tasks/helpers.js
var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var config = require('../config'); gulp.task('watch', ['browserify:build', 'scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); gulp.task('build', ['browserify:build', 'scripts:build', 'sass:build', 'templates:build', 'views:build']); gulp.task('lint', ['scripts:lint']); gulp.task('clean', ['browserify:clean', 'scripts:clean', 'sass:clean', 'templates:clean']); gulp.task('serve', config.production ? null : ['watch'], function () { $.connect.server({ root: config.serve.root, livereload: !config.production, port: config.serve.port }); }); gulp.task('default', ['serve']);
var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var config = require('../config'); gulp.task('watch', ['scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); gulp.task('build', ['browserify:build', 'scripts:build', 'sass:build', 'templates:build', 'views:build']); gulp.task('lint', ['scripts:lint']); gulp.task('clean', ['browserify:clean', 'scripts:clean', 'sass:clean', 'templates:clean']); gulp.task('serve', config.production ? ['build'] : ['build', 'watch'], function () { $.connect.server({ root: config.serve.root, livereload: !config.production, port: config.serve.port }); }); gulp.task('default', ['serve']);
Add build to gulp serve task dependencies.
Add build to gulp serve task dependencies.
JavaScript
mit
Dramloc/angular-material-boilerplate,Dramloc/angular-material-boilerplate
--- +++ @@ -2,12 +2,12 @@ var $ = require('gulp-load-plugins')(); var config = require('../config'); -gulp.task('watch', ['browserify:build', 'scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); +gulp.task('watch', ['scripts:watch', 'sass:watch', 'templates:watch', 'views:watch']); gulp.task('build', ['browserify:build', 'scripts:build', 'sass:build', 'templates:build', 'views:build']); gulp.task('lint', ['scripts:lint']); gulp.task('clean', ['browserify:clean', 'scripts:clean', 'sass:clean', 'templates:clean']); -gulp.task('serve', config.production ? null : ['watch'], function () { +gulp.task('serve', config.production ? ['build'] : ['build', 'watch'], function () { $.connect.server({ root: config.serve.root, livereload: !config.production,
2de4d7adf1806d8126a151a3b1931d53d7ea6010
gulp_tasks/compile.js
gulp_tasks/compile.js
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ var gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', // TODO(danmane): add plottable to the typings registry after updating it // and remove this. 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ var gulp = require('gulp'); var ts = require('gulp-typescript'); var typescript = require('typescript'); var gutil = require('gulp-util'); var filter = require('gulp-filter'); var merge = require('merge2'); var tsProject = ts.createProject('./tsconfig.json', { typescript: typescript, noExternalResolve: true, // opt-in for faster compilation! }); module.exports = function() { var isComponent = filter([ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', 'components/plottable/plottable.d.ts' ]); return tsProject.src() .pipe(isComponent) .pipe(ts(tsProject)) .js .pipe(gulp.dest('.')); }
Remove the plottable typings todo as it is currently a good solution Change: 130777731
Remove the plottable typings todo as it is currently a good solution Change: 130777731
JavaScript
apache-2.0
tensorflow/tensorboard,ioeric/tensorboard,qiuminxu/tensorboard,shakedel/tensorboard,agrubb/tensorboard,qiuminxu/tensorboard,francoisluus/tensorboard-supervise,agrubb/tensorboard,ioeric/tensorboard,ioeric/tensorboard,qiuminxu/tensorboard,qiuminxu/tensorboard,ioeric/tensorboard,tensorflow/tensorboard,francoisluus/tensorboard-supervise,tensorflow/tensorboard,francoisluus/tensorboard-supervise,agrubb/tensorboard,francoisluus/tensorboard-supervise,shakedel/tensorboard,tensorflow/tensorboard,francoisluus/tensorboard-supervise,tensorflow/tensorboard,agrubb/tensorboard,tensorflow/tensorboard,shakedel/tensorboard,shakedel/tensorboard,shakedel/tensorboard,shakedel/tensorboard,ioeric/tensorboard,ioeric/tensorboard,agrubb/tensorboard,francoisluus/tensorboard-supervise,qiuminxu/tensorboard,agrubb/tensorboard,tensorflow/tensorboard,qiuminxu/tensorboard
--- +++ @@ -31,8 +31,6 @@ 'components/tf-*/**/*.ts', 'components/vz-*/**/*.ts', 'typings/**/*.ts', - // TODO(danmane): add plottable to the typings registry after updating it - // and remove this. 'components/plottable/plottable.d.ts' ]);
ccda02ea5da45204e0e6a5789b7242dbbcba1fee
angular_tutorial/examples/29/app.js
angular_tutorial/examples/29/app.js
angular.module('nameApp', []) .factory('PersonsService', personsService) .directive('name', nameDirective) .controller('ExampleCtrl', ExampleCtrl); ExampleCtrl.$inject = ['PersonsService']; function ExampleCtrl(PersonsService) { var ctrl = this; PersonsService.get(function(data) { ctrl.persons = data; }); ctrl.max = 4; } personsService.$inject = ['$http']; function personsService($http) { var service = { get: get_all, }; return service; function get_all(callback) { $http.get('/examples/28/names.json').then(function(response) { callback(response.data); }); } } NameDirectiveCtrl.$inject = ['$scope']; function NameDirectiveCtrl($scope) { $scope.remove = function(person) { $scope.persons = $scope.persons.filter(function(p) { if (p !== person) { return true; } return false; }); }; } function nameDirective() { return { restrict: 'AE', templateUrl: '/examples/29/name.html', controller: NameDirectiveCtrl, scope: { person: '=person', persons: '=all', }, }; }
angular.module('nameApp', []) .factory('PersonsService', personsService) .directive('name', nameDirective) .controller('ExampleCtrl', ExampleCtrl); ExampleCtrl.$inject = ['PersonsService']; function ExampleCtrl(PersonsService) { var ctrl = this; PersonsService.get(function(data) { ctrl.persons = data; }); ctrl.max = 4; } personsService.$inject = ['$http']; function personsService($http) { var service = { get: get_all, }; return service; function get_all(callback) { $http.get('/examples/29/names.json').then(function(response) { callback(response.data); }); } } NameDirectiveCtrl.$inject = ['$scope']; function NameDirectiveCtrl($scope) { $scope.remove = function(person) { $scope.persons = $scope.persons.filter(function(p) { if (p !== person) { return true; } return false; }); }; } function nameDirective() { return { restrict: 'AE', templateUrl: '/examples/29/name.html', controller: NameDirectiveCtrl, scope: { person: '=person', persons: '=all', }, }; }
Fix loading names.json for example 29
Fix loading names.json for example 29
JavaScript
mit
bjoernricks/angular-tutorial
--- +++ @@ -22,7 +22,7 @@ return service; function get_all(callback) { - $http.get('/examples/28/names.json').then(function(response) { + $http.get('/examples/29/names.json').then(function(response) { callback(response.data); }); }
9c89b403737203104685e63a4d39f716a2a6eb0e
resources/assets/components/PagingButtons/index.js
resources/assets/components/PagingButtons/index.js
import React from 'react'; import './paging-buttons.scss'; class PagingButtons extends React.Component { render() { const prev = this.props.prev; const next = this.props.next; return ( <div className="container__block"> <a href={prev} onClick={e => this.props.onPaginate(prev, e)} disabled={prev}>{prev ? "< previous" : null}</a> <div className="next-page"> <a href={next} onClick={e => this.props.onPaginate(next, e)}>{next ? "next >" : null}</a> </div> </div> ) } } export default PagingButtons;
import React from 'react'; import PropTypes from 'prop-types'; import './paging-buttons.scss'; class PagingButtons extends React.Component { render() { const prev = this.props.prev; const next = this.props.next; return ( <div className="container__block"> <a href={prev} onClick={e => this.props.onPaginate(prev, e)} disabled={prev}>{prev ? "< previous" : null}</a> <div className="next-page"> <a href={next} onClick={e => this.props.onPaginate(next, e)}>{next ? "next >" : null}</a> </div> </div> ) } } PagingButtons.propTypes = { next: PropTypes.string.isRequired, onPaginate: PropTypes.func.isRequired, prev: PropTypes.string.isRequired, }; export default PagingButtons;
Add proptype validation to PagingButtons component
Add proptype validation to PagingButtons component
JavaScript
mit
DoSomething/rogue,DoSomething/rogue,DoSomething/rogue
--- +++ @@ -1,4 +1,6 @@ import React from 'react'; +import PropTypes from 'prop-types'; + import './paging-buttons.scss'; class PagingButtons extends React.Component { @@ -17,4 +19,10 @@ } } +PagingButtons.propTypes = { + next: PropTypes.string.isRequired, + onPaginate: PropTypes.func.isRequired, + prev: PropTypes.string.isRequired, +}; + export default PagingButtons;
c37db776f177d3377bdea22a314f6f560880974f
vlc_remote.user.js
vlc_remote.user.js
// ==UserScript== // @name VLC Remote // @namespace fatmonkeys // @include http://[IP address of VLC Remote server]:8080/ // @version 1 // @grant none // ==/UserScript== document.onkeypress = checkKey; function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } function checkKey(e) { e = e || window.event; if (e.charCode == 32) { eventFire(document.getElementById('buttonPlay'), 'click'); } else if(e.ctrlKey && e.keyCode == 37) { eventFire(document.getElementById('buttonPrev'), 'mousedown'); eventFire(document.getElementById('buttonPrev'), 'mouseup'); } else if(e.ctrlKey && e.keyCode == 39) { eventFire(document.getElementById('buttonNext'), 'mousedown'); eventFire(document.getElementById('buttonNext'), 'mouseup'); } }
// ==UserScript== // @name VLC Remote // @namespace fatmonkeys // @include http://[IP address of VLC Remote server]:8080/ // @version 1 // @grant none // ==/UserScript== // Enables new keyboard shortcuts: // Space to pause/resume the current video. // Ctrl + Right arrow to jump to the next video in the playlist. // Ctrl + Left arrow to jump to the previous video in the playlist. document.onkeypress = checkKey; function eventFire(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } function checkKey(e) { e = e || window.event; if (e.charCode == 32) { eventFire(document.getElementById('buttonPlay'), 'click'); } else if(e.ctrlKey && e.keyCode == 37) { eventFire(document.getElementById('buttonPrev'), 'mousedown'); eventFire(document.getElementById('buttonPrev'), 'mouseup'); } else if(e.ctrlKey && e.keyCode == 39) { eventFire(document.getElementById('buttonNext'), 'mousedown'); eventFire(document.getElementById('buttonNext'), 'mouseup'); } }
Document shortcuts for VLC Remote
Document shortcuts for VLC Remote
JavaScript
mit
pchaigno/fatmonkeys
--- +++ @@ -5,6 +5,11 @@ // @version 1 // @grant none // ==/UserScript== + +// Enables new keyboard shortcuts: +// Space to pause/resume the current video. +// Ctrl + Right arrow to jump to the next video in the playlist. +// Ctrl + Left arrow to jump to the previous video in the playlist. document.onkeypress = checkKey;
65ccf49edfb0ebdeb06990b51a8c6cab57e35a1c
spec/options.spec.js
spec/options.spec.js
'use strict'; var Ajv = require(typeof window == 'object' ? 'ajv' : '../lib/ajv') , should = require('chai').should() , stableStringify = require('json-stable-stringify'); describe('Ajv Options', function () { describe('removeAdditional', function() { it('should remove properties that would error when `additionalProperties = false`', function() { var ajv = Ajv({ removeAdditional: true }); ajv.compile({ id: '//test/fooBar', properties: { foo: { type: 'string' }, bar: { type: 'string' } }, additionalProperties: false }); var object = { foo: 'foo', bar: 'bar', baz: 'baz-to-be-removed' }; ajv.validate('//test/fooBar', object) .should.equal(true); object.should.have.all.keys(['foo', 'bar']); object.should.not.have.property('baz'); }); }); });
'use strict'; var Ajv = require(typeof window == 'object' ? 'ajv' : '../lib/ajv') , should = require('chai').should() , stableStringify = require('json-stable-stringify'); describe('Ajv Options', function () { describe('removeAdditional', function() { it('should remove properties that would error when `additionalProperties = false`', function() { var ajv = Ajv({ removeAdditional: true }); ajv.compile({ id: '//test/fooBar', properties: { foo: { type: 'string' }, bar: { type: 'string' } }, additionalProperties: false }); var object = { foo: 'foo', bar: 'bar', baz: 'baz-to-be-removed' }; ajv.validate('//test/fooBar', object).should.equal(true); object.should.have.property('foo'); object.should.have.property('bar'); object.should.not.have.property('baz'); }); it('should remove properties that would error when `additionalProperties` is a schema', function() { var ajv = Ajv({ removeAdditional: true }); ajv.compile({ id: '//test/fooBar', properties: { foo: { type: 'string' }, bar: { type: 'string' } }, additionalProperties: { type: 'string' } }); var object = { foo: 'foo', bar: 'bar', baz: 'baz-to-be-kept', fizz: 1000 }; ajv.validate('//test/fooBar', object).should.equal(true); object.should.have.property('foo'); object.should.have.property('bar'); object.should.have.property('baz'); object.should.not.have.property('fizz'); }); }); });
Add test for `removeAdditional` when using a schema to validate additional properties.
Add test for `removeAdditional` when using a schema to validate additional properties.
JavaScript
mit
marbemac/ajv,epoberezkin/ajv,YChebotaev/ajv,marbemac/ajv,MailOnline/ajv,YChebotaev/ajv,epoberezkin/ajv,MailOnline/ajv,epoberezkin/ajv
--- +++ @@ -7,6 +7,7 @@ describe('Ajv Options', function () { describe('removeAdditional', function() { + it('should remove properties that would error when `additionalProperties = false`', function() { var ajv = Ajv({ removeAdditional: true }); @@ -20,9 +21,31 @@ foo: 'foo', bar: 'bar', baz: 'baz-to-be-removed' }; - ajv.validate('//test/fooBar', object) .should.equal(true); - object.should.have.all.keys(['foo', 'bar']); + ajv.validate('//test/fooBar', object).should.equal(true); + object.should.have.property('foo'); + object.should.have.property('bar'); object.should.not.have.property('baz'); + + }); + + it('should remove properties that would error when `additionalProperties` is a schema', function() { + var ajv = Ajv({ removeAdditional: true }); + + ajv.compile({ + id: '//test/fooBar', + properties: { foo: { type: 'string' }, bar: { type: 'string' } }, + additionalProperties: { type: 'string' } + }); + + var object = { + foo: 'foo', bar: 'bar', baz: 'baz-to-be-kept', fizz: 1000 + }; + + ajv.validate('//test/fooBar', object).should.equal(true); + object.should.have.property('foo'); + object.should.have.property('bar'); + object.should.have.property('baz'); + object.should.not.have.property('fizz'); });
fe8740d58fd78c210a51626508794c2d19a9d685
test/soft-wrap-indicator.test.js
test/soft-wrap-indicator.test.js
'use babel' SoftWrapIndicator = require('../lib/soft-wrap-indicator') describe('SoftWrapIndicatorPackage', () => { let atomEnv, indicator beforeEach(async () => { atomEnv = global.buildAtomEnvironment() let workspace = atomEnv.workspace let workspaceElement = atomEnv.views.getView(workspace) await atomEnv.packages.activatePackage('status-bar') await atomEnv.packages.activatePackage('language-javascript') await atomEnv.packages.activatePackage('language-gfm') await atomEnv.packages.activatePackage('soft-wrap-indicator') expect(SoftWrapIndicator.deactivate).to.be.ok indicator = SoftWrapIndicator.component.element }) afterEach(() => { atomEnv.destroy() }) it('creates an indicator element', () => { expect(indicator).to.be.ok }) })
'use babel' SoftWrapIndicator = require('../lib/soft-wrap-indicator') describe('SoftWrapIndicatorPackage', function () { let atomEnv, indicator beforeEach(async function () { await atom.packages.activatePackage('status-bar') await atom.packages.activatePackage('language-javascript') await atom.packages.activatePackage('language-gfm') await atom.packages.activatePackage('soft-wrap-indicator') expect(SoftWrapIndicator.deactivate).to.be.ok indicator = SoftWrapIndicator.component.element }) afterEach(function () { atom.destroy() }) it('creates an indicator element', function () { expect(indicator).to.be.ok }) })
Switch to using function keyword instead of arrow functions
Switch to using function keyword instead of arrow functions
JavaScript
mit
lee-dohm/soft-wrap-indicator
--- +++ @@ -2,28 +2,24 @@ SoftWrapIndicator = require('../lib/soft-wrap-indicator') -describe('SoftWrapIndicatorPackage', () => { +describe('SoftWrapIndicatorPackage', function () { let atomEnv, indicator - beforeEach(async () => { - atomEnv = global.buildAtomEnvironment() - let workspace = atomEnv.workspace - let workspaceElement = atomEnv.views.getView(workspace) - - await atomEnv.packages.activatePackage('status-bar') - await atomEnv.packages.activatePackage('language-javascript') - await atomEnv.packages.activatePackage('language-gfm') - await atomEnv.packages.activatePackage('soft-wrap-indicator') + beforeEach(async function () { + await atom.packages.activatePackage('status-bar') + await atom.packages.activatePackage('language-javascript') + await atom.packages.activatePackage('language-gfm') + await atom.packages.activatePackage('soft-wrap-indicator') expect(SoftWrapIndicator.deactivate).to.be.ok indicator = SoftWrapIndicator.component.element }) - afterEach(() => { - atomEnv.destroy() + afterEach(function () { + atom.destroy() }) - it('creates an indicator element', () => { + it('creates an indicator element', function () { expect(indicator).to.be.ok }) })
fa244c9b5c6e7a1d3e157e98a6a1081469ca2c54
lib/FilterPaneSearch/FilterPaneSearch.js
lib/FilterPaneSearch/FilterPaneSearch.js
import React from 'react'; import css from './FilterPaneSearch.css'; import Icon from '@folio/stripes-components/lib/Icon'; import Button from '@folio/stripes-components/lib/Button'; class FilterPaneSearch extends React.Component{ constructor(props){ super(props); this.searchInput = null; } clearSearchField(){ this.searchInput.value = ''; const evt = new Event('input', {bubbles: true}); this.searchInput.dispatchEvent(evt); } onChange() { console.log("changed: new value =", this.searchInput.value); // XXX We need to somehow feed the changed value into stripes-connect for the parent component } render(){ return( <div className={css.headerSearchContainer}> <div style={{alignSelf:"center"}}><Icon icon="search"/></div> <input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.onChange.bind(this)} placeholder="Search"/> <Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button> </div> ); } } export default FilterPaneSearch;
import React, { PropTypes } from 'react'; import css from './FilterPaneSearch.css'; import Icon from '@folio/stripes-components/lib/Icon'; import Button from '@folio/stripes-components/lib/Button'; class FilterPaneSearch extends React.Component{ static contextTypes = { router: PropTypes.object.isRequired }; constructor(props){ super(props); this.searchInput = null; } clearSearchField(){ this.searchInput.value = ''; const evt = new Event('input', {bubbles: true}); this.searchInput.dispatchEvent(evt); } onChange() { const value = this.searchInput.value; this.context.router.transitionTo("/users/" + value); } render(){ return( <div className={css.headerSearchContainer}> <div style={{alignSelf:"center"}}><Icon icon="search"/></div> <input className={css.headerSearchInput} ref={(ref) => this.searchInput = ref} type="text" value = {this.props.value} onChange={this.onChange.bind(this)} placeholder="Search"/> <Button className={css.headerSearchClearButton} onClick={this.clearSearchField.bind(this)} ><Icon icon="clearX" iconClassName={css.clearIcon}/></Button> </div> ); } } export default FilterPaneSearch;
Set the URL to include the modified query. Part of STRIPES-85.
Set the URL to include the modified query. Part of STRIPES-85. At present we express URLs in the form: http://localhost:3000/users/water with the query in the path rather than in the URL query, as: http://localhost:3000/users?q=water That's just because at present Stripes Connect can't get at the URL query, and we want to show searching working from top to bottom. Once Stripes Connect is up to speed (probably towards the end of next week) we will change the URLs used for searching. Because that change is coming, I am not worrying too much in the short term about this wrinkle: we currently set the whole of the path to "/users/"+value, so it only works when the Users module is mounted on /users. But since that's always, I am not losing sleep.
JavaScript
apache-2.0
folio-org/ui-users,folio-org/ui-users
--- +++ @@ -1,9 +1,13 @@ -import React from 'react'; +import React, { PropTypes } from 'react'; import css from './FilterPaneSearch.css'; import Icon from '@folio/stripes-components/lib/Icon'; import Button from '@folio/stripes-components/lib/Button'; class FilterPaneSearch extends React.Component{ + static contextTypes = { + router: PropTypes.object.isRequired + }; + constructor(props){ super(props); this.searchInput = null; @@ -16,8 +20,8 @@ } onChange() { - console.log("changed: new value =", this.searchInput.value); - // XXX We need to somehow feed the changed value into stripes-connect for the parent component + const value = this.searchInput.value; + this.context.router.transitionTo("/users/" + value); } render(){
499f6ab748b7ca1ea5f28dcb535b018fef595f71
src/GoogleMapsAPI.js
src/GoogleMapsAPI.js
"use strict"; var invariant = require('react/lib/invariant'); invariant( window.google || window.google.maps, '`google.maps` global object not found, make sure ' + 'Google maps in included before react-googlemaps is defined' ); module.exports = window.google.maps;
"use strict"; var invariant = require('react/lib/invariant'); invariant( window.google && window.google.maps, '`google.maps` global object not found, make sure ' + 'Google maps in included before react-googlemaps is defined' ); module.exports = window.google.maps;
Fix logic for checking google maps exists
Fix logic for checking google maps exists
JavaScript
mit
pieterv/react-googlemaps,adalgleish/react-googlemaps,soundswarm/react-googlemaps,shipstar/react-googlemaps,shipstar/react-googlemaps,soundswarm/react-googlemaps,ssangireddy-nisum-com/react-googlemaps,cgarvis/react-googlemaps,cgarvis/react-googlemaps,adalgleish/react-googlemaps,Amirus/react-googlemaps,petehunt/react-googlemaps,kaiserken/react-googlemaps,ssangireddy-nisum-com/react-googlemaps,Jonekee/react-googlemaps
--- +++ @@ -3,7 +3,7 @@ var invariant = require('react/lib/invariant'); invariant( - window.google || window.google.maps, + window.google && window.google.maps, '`google.maps` global object not found, make sure ' + 'Google maps in included before react-googlemaps is defined' );
b5efe1cde9795ac00c7345ec62b097f6dffd0aa7
tests/specs/module/chain/main.js
tests/specs/module/chain/main.js
define(function(require, exports, mod) { var test = require('../../../test') test.assert(seajs.config() === seajs, 'sea.config is chainable') test.assert(seajs.emit() === seajs, 'sea.emit is chainable') test.assert(seajs.on() === seajs, 'sea.on is chainable') test.assert(seajs.off() === seajs, 'sea.off is chainable') test.assert(seajs.log() === undefined, 'sea.log is NOT chainable') test.assert(seajs.use() === seajs, 'sea.use is chainable') test.assert(seajs.cwd(seajs.cwd()) === seajs.cwd(), 'sea.cwd is NOT chainable') //seajs.log(require.resolve('./a')) test.assert(require.async('./a') === require, 'require.async is chainable') test.assert(mod.load('./a') === undefined, 'module.load is NOT chainable') test.next() });
define(function(require, exports, mod) { var test = require('../../../test') test.assert(seajs.config() === seajs, 'sea.config is chainable') test.assert(seajs.emit() === seajs, 'sea.emit is chainable') test.assert(seajs.on() === seajs, 'sea.on is chainable') test.assert(seajs.off() === seajs, 'sea.off is chainable') test.assert(seajs.log() === undefined, 'sea.log is NOT chainable') test.assert(seajs.use() === seajs, 'sea.use is chainable') test.assert(seajs.cwd(seajs.cwd()) === seajs.cwd(), 'sea.cwd is NOT chainable') //seajs.log(require.resolve('./a')) test.assert(require.async('./a') === require, 'require.async is chainable') //test.assert(mod.load('./a') === undefined, 'module.load is NOT chainable') test.next() });
Remove specs for module.load function
Remove specs for module.load function
JavaScript
mit
judastree/seajs,moccen/seajs,seajs/seajs,AlvinWei1024/seajs,evilemon/seajs,kuier/seajs,JeffLi1993/seajs,zwh6611/seajs,lianggaolin/seajs,LzhElite/seajs,mosoft521/seajs,jishichang/seajs,yern/seajs,jishichang/seajs,liupeng110112/seajs,judastree/seajs,liupeng110112/seajs,miusuncle/seajs,evilemon/seajs,Gatsbyy/seajs,uestcNaldo/seajs,ysxlinux/seajs,eleanors/SeaJS,lianggaolin/seajs,yern/seajs,twoubt/seajs,FrankElean/SeaJS,kuier/seajs,mosoft521/seajs,eleanors/SeaJS,seajs/seajs,uestcNaldo/seajs,121595113/seajs,wenber/seajs,longze/seajs,treejames/seajs,lee-my/seajs,moccen/seajs,JeffLi1993/seajs,AlvinWei1024/seajs,zaoli/seajs,coolyhx/seajs,kaijiemo/seajs,coolyhx/seajs,baiduoduo/seajs,yern/seajs,13693100472/seajs,lee-my/seajs,yuhualingfeng/seajs,Lyfme/seajs,Gatsbyy/seajs,angelLYK/seajs,jishichang/seajs,yuhualingfeng/seajs,ysxlinux/seajs,twoubt/seajs,liupeng110112/seajs,eleanors/SeaJS,LzhElite/seajs,chinakids/seajs,121595113/seajs,baiduoduo/seajs,JeffLi1993/seajs,wenber/seajs,sheldonzf/seajs,baiduoduo/seajs,tonny-zhang/seajs,Gatsbyy/seajs,Lyfme/seajs,lovelykobe/seajs,imcys/seajs,zaoli/seajs,tonny-zhang/seajs,PUSEN/seajs,lovelykobe/seajs,lee-my/seajs,kaijiemo/seajs,evilemon/seajs,hbdrawn/seajs,lovelykobe/seajs,hbdrawn/seajs,FrankElean/SeaJS,treejames/seajs,chinakids/seajs,coolyhx/seajs,mosoft521/seajs,seajs/seajs,AlvinWei1024/seajs,angelLYK/seajs,yuhualingfeng/seajs,zwh6611/seajs,angelLYK/seajs,LzhElite/seajs,PUSEN/seajs,sheldonzf/seajs,longze/seajs,treejames/seajs,miusuncle/seajs,miusuncle/seajs,wenber/seajs,FrankElean/SeaJS,zaoli/seajs,PUSEN/seajs,kaijiemo/seajs,sheldonzf/seajs,longze/seajs,imcys/seajs,moccen/seajs,imcys/seajs,lianggaolin/seajs,Lyfme/seajs,MrZhengliang/seajs,twoubt/seajs,13693100472/seajs,zwh6611/seajs,judastree/seajs,MrZhengliang/seajs,uestcNaldo/seajs,tonny-zhang/seajs,ysxlinux/seajs,MrZhengliang/seajs,kuier/seajs
--- +++ @@ -1,4 +1,3 @@ - define(function(require, exports, mod) { @@ -15,7 +14,7 @@ //seajs.log(require.resolve('./a')) test.assert(require.async('./a') === require, 'require.async is chainable') - test.assert(mod.load('./a') === undefined, 'module.load is NOT chainable') + //test.assert(mod.load('./a') === undefined, 'module.load is NOT chainable') test.next()
b3f62f93ce1d39571afa7d01db6898c0316d414d
src/codeHighlight.js
src/codeHighlight.js
'use strict' const path = require('path') const rtfRenderer = require('../lib/') const execa = require('execa') module.exports = function codeHighlight(clipboard, settings) { const fontface = settings.getSync('fontface') const theme = settings.getSync('theme') const input = clipboard.readText() const output = rtfRenderer.highlightAuto(input, { fontface, theme }).value clipboard.writeRTF(output) // Pasting into the active application execa('osascript', [path.resolve('./src/paste.as')]).then((result) => { console.log(result.stdout) }) }
'use strict' const path = require('path') const rtfRenderer = require('../lib/') const execa = require('execa') module.exports = function codeHighlight(clipboard, settings) { const fontface = settings.getSync('fontface') const theme = settings.getSync('theme') const input = clipboard.readText() const output = rtfRenderer.highlightAuto(input, { fontface, theme }).value clipboard.write({ text: input, rtf: output }) }
Write original string to the clipboard as text and new as RTF
fix: Write original string to the clipboard as text and new as RTF
JavaScript
mpl-2.0
okonet/codestage,okonet/codestage
--- +++ @@ -12,10 +12,9 @@ fontface, theme }).value - clipboard.writeRTF(output) - // Pasting into the active application - execa('osascript', [path.resolve('./src/paste.as')]).then((result) => { - console.log(result.stdout) + clipboard.write({ + text: input, + rtf: output }) }
4fd504569b7847aa6fe1964866419ec2032de9b6
js/LearnController.js
js/LearnController.js
console.log("Create app module"); var learnApp = angular.module('LearnApp', []); var LearnController = function($scope) { var _this = this; window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); bus = window.castReceiverManager.getCastMessageBus('urn:x-cast:com.kg.learn'); window.castReceiverManager.start(); $scope.sendersCount = 0; this.addSender = function(event) { $scope.$apply(function() { console.log("New sender connected"); console.log(event); $scope.sendersCount++; console.log($scope.sendersCount); }); } this.removeSender = function(event) { $scope.apply(function() { console.log("Sender disconnected"); console.log(event); console.log(window.castReceiverManager.getSenders()); // Close app if there is no more client session if (window.castReceiverManager.getSenders().length == 0 && event.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER) { window.close(); } $scope.sendersCount--; }); }; window.castReceiverManager.onSenderDisconnected = this.removeSender; window.castReceiverManager.onSenderConnected = this.addSender; }; LearnController.$inject = ['$scope']; learnApp.controller('LearnController', LearnController);
console.log("Create app module"); var learnApp = angular.module('LearnApp', []); var LearnController = function($scope) { var _this = this; window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); bus = window.castReceiverManager.getCastMessageBus('urn:x-cast:com.kg.learn'); window.castReceiverManager.start(); $scope.sendersCount = 0; this.addSender = function(event) { $scope.$apply(function() { console.log("New sender connected"); console.log(event); $scope.sendersCount++; console.log($scope.sendersCount); }); } this.removeSender = function(event) { $scope.$apply(function() { console.log("Sender disconnected"); console.log(event); console.log(window.castReceiverManager.getSenders()); // Close app if there is no more client session if (window.castReceiverManager.getSenders().length == 0 && event.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER) { window.close(); } $scope.sendersCount--; }); }; window.castReceiverManager.onSenderDisconnected = this.removeSender; window.castReceiverManager.onSenderConnected = this.addSender; }; LearnController.$inject = ['$scope']; learnApp.controller('LearnController', LearnController);
Fix call to on session disconnected
Fix call to on session disconnected
JavaScript
mit
KevinGaudin/learncast
--- +++ @@ -20,7 +20,7 @@ } this.removeSender = function(event) { - $scope.apply(function() { + $scope.$apply(function() { console.log("Sender disconnected"); console.log(event); console.log(window.castReceiverManager.getSenders());
f603d70311214b39e5e6b82b89f38639f828ad24
bin/repl.js
bin/repl.js
#!/usr/bin/env node var repl = require('repl'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); Chrome(function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ' }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } });
#!/usr/bin/env node var repl = require('repl'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); Chrome(function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ' }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } }).on('error', function () { console.error('Cannot connect to Chrome'); });
Add error reporting to the REPL interface
Add error reporting to the REPL interface
JavaScript
mit
valaxy/chrome-remote-interface,cyrus-and/chrome-remote-interface,cyrus-and/chrome-remote-interface,washtubs/chrome-remote-interface
--- +++ @@ -19,4 +19,6 @@ var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } +}).on('error', function () { + console.error('Cannot connect to Chrome'); });
0eb999eeadd6b4014242d7f709e1767864d4f59b
helpers/helpers.js
helpers/helpers.js
module.exports = function (context) { return { $: function (expression) { return expression }, extend: { extendables: {}, add: function (selector, cssString) { this.extendables[selector] = { css: cssString, selectors: [] } }, that: function (extendable, selector) { if(!this.extendables[extendable]) return false this.extendables[extendable]['selectors'].push(selector) context.onDone.push(this.extendMaker(extendable)) }, extendMaker: function (extendable) { var self = this return function () { return [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n' } } } } }
module.exports = function (context) { return { $: function (expression) { return expression }, extend: { extendables: {}, add: function (selector, cssString) { this.extendables[selector] = { css: cssString, selectors: [] } }, that: function (extendable, selector) { if(!this.extendables[extendable]) return false this.extendables[extendable]['selectors'].push(selector) context.onDone.push(this.extendMaker(extendable)) }, extendMaker: function (extendable) { var self = this return function () { var returnVal if(!self.extendables[extendable]) return '' returnVal = [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n' self.extendables[extendable] = false return returnVal } } } } }
Make extendMake run only once
Make extendMake run only once
JavaScript
mit
Kriegslustig/jsheets
--- +++ @@ -20,7 +20,11 @@ extendMaker: function (extendable) { var self = this return function () { - return [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n' + var returnVal + if(!self.extendables[extendable]) return '' + returnVal = [self.extendables[extendable].selectors].concat(self.extendables[extendable].selectors).join(', ') + ' {' + self.extendables[extendable].css + '}\n' + self.extendables[extendable] = false + return returnVal } } }
6736f1c48f21d1cbcebedcc2f62647fac0f8cc17
src/TitleBar/macOs/Controls/index.js
src/TitleBar/macOs/Controls/index.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Close from './Close'; import Minimize from './Minimize'; import Resize from './Resize'; var styles = { controls: { WebkitUserSelect: 'none', userSelect: 'none', cursor: 'default', display: 'flex', width: '61px' }, inset: { marginLeft: '5px' } }; class Controls extends Component { static propTypes = { inset: PropTypes.bool, isFullscreen: PropTypes.bool, onCloseClick: PropTypes.func, onMinimizeClick: PropTypes.func, onMaximizeClick: PropTypes.func, onResizeClick: PropTypes.func }; constructor() { super(); this.state = { isOver: false }; } render() { return ( <div style={{ ...styles.controls }} onMouseEnter={() => this.setState({ isOver: true })} onMouseLeave={() => this.setState({ isOver: false })} > <Close onClick={this.props.onCloseClick} showIcon={this.state.isOver} /> <Minimize onClick={this.props.onMinimizeClick} showIcon={this.state.isOver} /> <Resize isFullscreen={this.props.isFullscreen} onClick={this.props.onResizeClick} onMaximizeClick={this.props.onMaximizeClick} showIcon={this.state.isOver} /> </div> ); } } export default Controls;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Close from './Close'; import Minimize from './Minimize'; import Resize from './Resize'; var styles = { controls: { WebkitUserSelect: 'none', userSelect: 'none', cursor: 'default', display: 'flex', width: '61px' }, inset: { marginLeft: '5px' } }; class Controls extends Component { static propTypes = { inset: PropTypes.bool, isFullscreen: PropTypes.bool, onCloseClick: PropTypes.func, onMinimizeClick: PropTypes.func, onMaximizeClick: PropTypes.func, onResizeClick: PropTypes.func }; constructor() { super(); this.state = { isOver: false }; } render() { return ( <div style={{ ...styles.controls }} onMouseEnter={() => this.setState({ isOver: true })} onMouseLeave={() => this.setState({ isOver: false })} > <Close onClick={this.props.onCloseClick} showIcon={this.state.isOver} isWindowFocused={this.props.isWindowFocused} /> <Minimize onClick={this.props.onMinimizeClick} showIcon={this.state.isOver} isWindowFocused={this.props.isWindowFocused} /> <Resize isFullscreen={this.props.isFullscreen} onClick={this.props.onResizeClick} onMaximizeClick={this.props.onMaximizeClick} showIcon={this.state.isOver} isWindowFocused={this.props.isWindowFocused} /> </div> ); } } export default Controls;
Allow end-user to force `isWindowFocused` prop
Allow end-user to force `isWindowFocused` prop
JavaScript
mit
gabrielbull/react-desktop
--- +++ @@ -42,16 +42,22 @@ onMouseEnter={() => this.setState({ isOver: true })} onMouseLeave={() => this.setState({ isOver: false })} > - <Close onClick={this.props.onCloseClick} showIcon={this.state.isOver} /> + <Close + onClick={this.props.onCloseClick} + showIcon={this.state.isOver} + isWindowFocused={this.props.isWindowFocused} + /> <Minimize onClick={this.props.onMinimizeClick} showIcon={this.state.isOver} + isWindowFocused={this.props.isWindowFocused} /> <Resize isFullscreen={this.props.isFullscreen} onClick={this.props.onResizeClick} onMaximizeClick={this.props.onMaximizeClick} showIcon={this.state.isOver} + isWindowFocused={this.props.isWindowFocused} /> </div> );
5094d5a54ef765bf3ee4c251ebae879eb978bac3
src/components/routes/user/logout.js
src/components/routes/user/logout.js
import React, { Component } from 'react'; import * as types from '../../../constants/ActionTypes' import { logout } from '../../../actions/login'; import { connect } from 'react-redux'; class Logout extends Component { render() { return ( <li id="logoutButton" onClick={this.props.logout}> <a> Logout </a> </li> ); } } export default connect(null, { logout })(Logout)
import React, { Component } from 'react'; import * as types from '../../../constants/ActionTypes' import { logout } from '../../../actions/login'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; class Logout extends Component { render() { return ( <li id="logoutButton" onClick={this.props.logout}> <Link to="/">Logout</Link> </li> ); } } export default connect(null, { logout })(Logout)
Send user to home when he logs out
Send user to home when he logs out
JavaScript
mit
fredmarques/petshop,fredmarques/petshop
--- +++ @@ -2,15 +2,14 @@ import * as types from '../../../constants/ActionTypes' import { logout } from '../../../actions/login'; import { connect } from 'react-redux'; +import { Link } from 'react-router-dom'; class Logout extends Component { render() { return ( <li id="logoutButton" onClick={this.props.logout}> - <a> - Logout - </a> + <Link to="/">Logout</Link> </li> ); }
fb84dc7e9af4ab38dc70135cc800be6648cd99ef
src/poller-script.js
src/poller-script.js
import getFeed from './rss-feed-poller'; import loadFile from './config-parser.js'; export default async function rssPoller(robot) { try { const config = await loadFile(process.env.HUBOT_RSS_CONFIG_FILE || 'hubotrssconfig.json'); JSON.parse(config).feeds.map(x => getFeed({ ...x, robot })) .forEach(x => x.startFeed()); } catch (err) { robot.logger.debug(err.message); } }
import getFeed from './rss-feed-poller'; import loadFile from './config-parser.js'; export default async function rssPoller(robot) { try { const config = await loadFile(process.env.HUBOT_RSS_CONFIG_FILE || 'hubotrssconfig.json'); if (!process.env.HUBOT_RSS_FEED_DISABLE) { JSON.parse(config).feeds.map(x => getFeed({ ...x, robot })) .forEach(x => x.startFeed()); } } catch (err) { robot.logger.debug(err.message); } }
Add env variable to disable this plugin
Add env variable to disable this plugin This is necessary because we have a stage hubot and a real hubot at our company and we don't want the stage hubot saying anything about the RSS feeds.
JavaScript
mit
KanoYugoro/hubot-rss-poller
--- +++ @@ -5,8 +5,10 @@ try { const config = await loadFile(process.env.HUBOT_RSS_CONFIG_FILE || 'hubotrssconfig.json'); - JSON.parse(config).feeds.map(x => getFeed({ ...x, robot })) - .forEach(x => x.startFeed()); + if (!process.env.HUBOT_RSS_FEED_DISABLE) { + JSON.parse(config).feeds.map(x => getFeed({ ...x, robot })) + .forEach(x => x.startFeed()); + } } catch (err) { robot.logger.debug(err.message); }
eb570519ff5e97a243bb616b0a4c30f80ad9dc56
ember-cli-build.js
ember-cli-build.js
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, codemirror: { modes: ['javascript', 'handlebars', 'markdown'], themes: ['mdn-like'] }, 'ember-cli-mocha': { useLintTree: false }, 'ember-prism': { components: ['javascript'], theme: 'coy' }, sassOptions: { includePaths: [ ] } }) app.import('bower_components/sinonjs/sinon.js') /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree() }
/* global require, module */ var EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { includePolyfill: true, optional: ['es7.decorators'] }, codemirror: { modes: ['javascript', 'handlebars', 'markdown'], themes: ['mdn-like'] }, 'ember-cli-mocha': { useLintTree: false }, 'ember-prism': { components: ['javascript'], theme: 'coy' }, sassOptions: { includePaths: [ ] } }) app.import('bower_components/sinonjs/sinon.js') /* This build file specifes the options for the dummy test app of this addon, located in `/tests/dummy` This build file does *not* influence how the addon or the app using it behave. You most likely want to be modifying `./index.js` or app's build file */ return app.toTree() }
Include babel polyfill for github pages demo
Include babel polyfill for github pages demo
JavaScript
mit
ciena-frost/ember-frost-bunsen,sandersky/ember-frost-bunsen,sandersky/ember-frost-bunsen,sophypal/ember-frost-bunsen,sandersky/ember-frost-bunsen,ciena-frost/ember-frost-bunsen,sophypal/ember-frost-bunsen,ciena-frost/ember-frost-bunsen,sophypal/ember-frost-bunsen
--- +++ @@ -5,6 +5,7 @@ var app = new EmberAddon(defaults, { babel: { + includePolyfill: true, optional: ['es7.decorators'] }, codemirror: {
725db3347d6a03e918706933c9c62502da0656e7
page/search/search-header/mixin/index.js
page/search/search-header/mixin/index.js
// Mixins let i18nMixin =require('../../../../common/i18n').mixin; let searchBehaviour = require('../../common/search-mixin').mixin; var searchWrappedAction = require('../action-wrapper'); module.exports = { mixins: [i18nMixin, searchBehaviour], getInitialState(){ return { isLoading: false } }, componentWillMount(){ this._prepareSearch = searchWrappedAction(this.search, this); } };
// Mixins let i18nMixin =require('../../../../common/i18n').mixin; let searchBehaviour = require('../../common/search-mixin').mixin; var searchWrappedAction = require('../action-wrapper'); let SearchBar = require('../../../../search/search-bar').component; var React = require('react'); module.exports = { mixins: [i18nMixin, searchBehaviour], getInitialState(){ return { isLoading: false } }, _runSearch(){ var criteria = this.refs.searchBar.getValue(); return this.props.searchAction(this._buildSearchCriteria(criteria.scope, criteria.query)) }, _SearchBarComponent(){ return <SearchBar ref='searchBar' value={this.props.query} scope={this.props.scope} scopes={this.props.scopeList} loading={this.state.isLoadingSearch} handleChange={this._runSearch} />; }, componentWillMount(){ this._prepareSearch = searchWrappedAction(this._runSearch, this); } };
Rewrite mixin in order to call runSearhc.
[search-header] Rewrite mixin in order to call runSearhc.
JavaScript
mit
get-focus/focus-components,asimsir/focus-components,Bernardstanislas/focus-components,Jerom138/focus-components,Ephrame/focus-components,anisgh/focus-components,KleeGroup/focus-components,KleeGroup/focus-components,Jerom138/focus-components,Jerom138/focus-components,JRLK/focus-components,JabX/focus-components,Bernardstanislas/focus-components,Ephrame/focus-components,sebez/focus-components,Ephrame/focus-components,JRLK/focus-components,anisgh/focus-components,JRLK/focus-components,anisgh/focus-components,asimsir/focus-components,sebez/focus-components,JabX/focus-components,Bernardstanislas/focus-components
--- +++ @@ -3,6 +3,8 @@ let i18nMixin =require('../../../../common/i18n').mixin; let searchBehaviour = require('../../common/search-mixin').mixin; var searchWrappedAction = require('../action-wrapper'); +let SearchBar = require('../../../../search/search-bar').component; +var React = require('react'); module.exports = { mixins: [i18nMixin, searchBehaviour], @@ -11,7 +13,21 @@ isLoading: false } }, + _runSearch(){ + var criteria = this.refs.searchBar.getValue(); + return this.props.searchAction(this._buildSearchCriteria(criteria.scope, criteria.query)) + }, + _SearchBarComponent(){ + return <SearchBar + ref='searchBar' + value={this.props.query} + scope={this.props.scope} + scopes={this.props.scopeList} + loading={this.state.isLoadingSearch} + handleChange={this._runSearch} + />; + }, componentWillMount(){ - this._prepareSearch = searchWrappedAction(this.search, this); + this._prepareSearch = searchWrappedAction(this._runSearch, this); } };
3d6b3f3a2568c64e8d75f8cdd7c73138d17df618
gui/js/main.js
gui/js/main.js
/** * main.js * * Only runs in modern browsers via feature detection */ if('querySelector' in document && 'localStorage' in window && 'addEventListener' in window) { }
/** * main.js * * Only runs in modern browsers via feature detection */ if('querySelector' in document && 'localStorage' in window && 'addEventListener' in window) { // Add class "js" to html element document.querySelector('html').classList.add('js'); }
Add class "js" to html element
Add class "js" to html element
JavaScript
isc
frippz/blog-prototype,frippz/blog-prototype
--- +++ @@ -5,7 +5,8 @@ */ if('querySelector' in document && 'localStorage' in window && 'addEventListener' in window) { - - - + + // Add class "js" to html element + document.querySelector('html').classList.add('js'); + }
3f25a2a290bea7d61f87a6506f13f9edb6be37a8
client/templates/posts/posts_list.js
client/templates/posts/posts_list.js
Template.postsList.helpers({ posts: function() { return Posts.find(); } });
Template.postsList.helpers({ posts: function() { return Posts.find({}, {sort: {submitted: -1}}); } });
Sort posts by submitted timestamp.
Sort posts by submitted timestamp. chapter7-8
JavaScript
mit
JeremyIglehart/Orionscope,ilacyero/microscope-flowrouter,ilacyero/microscope-flowrouter,thomasmery/meteor_microscope,thomasmery/meteor_microscope,JeremyIglehart/Orionscope
--- +++ @@ -1,5 +1,5 @@ Template.postsList.helpers({ posts: function() { - return Posts.find(); + return Posts.find({}, {sort: {submitted: -1}}); } });
de96e5017395d83dbdc5d51a1b01dfb99f1f4ad5
graph_ui/js/app.js
graph_ui/js/app.js
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var GraphPanel = require('./GraphPanel.js'); var SearchPanel = require('./SearchPanel.js'); var NodeInfoPanel = require('./NodeInfoPanel.js'); var Graphalyzer = React.createClass({ render: function() { return ( <div> <GraphPanel /> <SearchPanel /> <NodeInfoPanel /> </div> ); } }); ReactDOM.render( <Graphalyzer />, document.getElementById('main') );
'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var GraphPanel = require('./GraphPanel.js'); var SearchPanel = require('./SearchPanel.js'); var NodeInfoPanel = require('./NodeInfoPanel.js'); var Graphalyzer = React.createClass({ getDefaultProps: function() { return { websocket: new WebSocket("ws://rwhite226.duckdns.org:1618/ws") }; }, getInitialState: function() { return { graphData: {}, selectedNode: {} }; }, componentDidMount: function() { this.websocket.onmessage = handleWSMessage; }, handleWSMessage: function(event) { var response = event.data; if (response !== null) { this.setState({graphData: response}); } }, render: function() { return ( <div> <GraphPanel /> <SearchPanel websocket = {this.props.websocket} /> <NodeInfoPanel /> </div> ); } }); ReactDOM.render( <Graphalyzer />, document.getElementById('main') );
Add WebSocket to main Graphalyzer component
Add WebSocket to main Graphalyzer component
JavaScript
apache-2.0
rwhite226/Graphalyzer,rwhite226/Graphalyzer,rwhite226/Graphalyzer,rwhite226/Graphalyzer
--- +++ @@ -7,11 +7,37 @@ var NodeInfoPanel = require('./NodeInfoPanel.js'); var Graphalyzer = React.createClass({ + getDefaultProps: function() { + return { + websocket: new WebSocket("ws://rwhite226.duckdns.org:1618/ws") + }; + }, + + getInitialState: function() { + return { + graphData: {}, + selectedNode: {} + }; + }, + + componentDidMount: function() { + this.websocket.onmessage = handleWSMessage; + }, + + handleWSMessage: function(event) { + var response = event.data; + if (response !== null) { + this.setState({graphData: response}); + } + }, + render: function() { return ( <div> <GraphPanel /> - <SearchPanel /> + <SearchPanel + websocket = {this.props.websocket} + /> <NodeInfoPanel /> </div> );
b9d8733a034de457e3e9c8810ec22e6bb6a43870
webpack.main.babel.js
webpack.main.babel.js
import path from 'path'; import merge from 'webpack-merge'; import CleanWebpackPlugin from 'clean-webpack-plugin'; import CommonConfig from './webpack.common'; let config = { entry: ['./src/main.js'], output: { filename: 'main.bundle.js', path: path.resolve(__dirname, 'src', '.build'), }, node: { __dirname: true, }, target: 'electron-main', plugins: [ new CleanWebpackPlugin(['src/.build/main.bundle.js']), ], }; if (process.env.NODE_ENV === 'development') { config = merge(config, { devtool: 'inline-cheap-source-map', }); } else { config = merge(config, { node: { __dirname: false, }, }); } export default merge(CommonConfig, config);
import path from 'path'; import merge from 'webpack-merge'; import CleanWebpackPlugin from 'clean-webpack-plugin'; import CommonConfig from './webpack.common'; let config = { entry: ['./src/main.js'], output: { filename: 'main.bundle.js', path: path.resolve(__dirname, 'src', '.build'), }, node: { __dirname: true, }, target: 'electron-main', plugins: [ new CleanWebpackPlugin(['src/.build/main.bundle.js']), ], }; if (process.env.NODE_ENV === 'development') { config = merge(config, { devtool: 'inline-source-map', }); } else { config = merge(config, { node: { __dirname: false, }, }); } export default merge(CommonConfig, config);
Use original source for debugging main process
Use original source for debugging main process
JavaScript
mit
psychobolt/electron-boilerplate,psychobolt/electron-boilerplate
--- +++ @@ -21,7 +21,7 @@ if (process.env.NODE_ENV === 'development') { config = merge(config, { - devtool: 'inline-cheap-source-map', + devtool: 'inline-source-map', }); } else { config = merge(config, {
4dbf707da01342a3e1762fcc2422562852d2d6c8
lib/marker-manager.js
lib/marker-manager.js
/** @babel */ import { CompositeDisposable, Disposable } from 'atom' export default class MarkerManager extends Disposable { disposables = new CompositeDisposable() constructor (editor) { super(() => this.disposables.dispose()) this.editor = editor this.markers = [] this.disposables.add(latex.log.onMessages((messages, reset) => this.addMarkers(messages, reset))) this.disposables.add(new Disposable(() => this.clear())) this.disposables.add(this.editor.onDidDestroy(() => this.dispose())) this.addMarkers(latex.log.getMessages()) } addMarkers (messages, reset) { const filePath = this.editor.getPath() if (reset) this.clear() if (filePath) { for (const message of messages) { if (message.filePath && message.range && filePath.includes(message.filePath)) { this.addMarker(message) } } } } addMarker (message) { const marker = this.editor.markBufferRange(message.range, { invalidate: 'touch' }) this.editor.decorateMarker(marker, { type: 'line-number', class: `latex-${message.type}` }) this.markers.push(marker) } clear () { for (const marker of this.markers) { marker.destroy() } this.markers = [] } }
/** @babel */ import { CompositeDisposable, Disposable } from 'atom' export default class MarkerManager extends Disposable { disposables = new CompositeDisposable() constructor (editor) { super(() => this.disposables.dispose()) this.editor = editor this.markers = [] this.disposables.add(latex.log.onMessages((messages, reset) => this.addMarkers(messages, reset))) this.disposables.add(new Disposable(() => this.clear())) this.disposables.add(this.editor.onDidDestroy(() => this.dispose())) this.disposables.add(atom.config.onDidChange('latex.loggingLevel', () => this.update())) this.addMarkers(latex.log.getMessages()) } update () { this.clear() this.addMarkers(latex.log.getMessages()) } addMarkers (messages, reset) { if (reset) this.clear() if (this.editor.getPath()) { for (const message of messages) { this.addMarker(message.type, message.filePath, message.range) this.addMarker(message.type, message.logPath, message.logRange) } } } addMarker (type, filePath, range) { const currentFilePath = this.editor.getPath() if (filePath && range && currentFilePath.includes(filePath)) { const marker = this.editor.markBufferRange(range, { invalidate: 'touch' }) this.editor.decorateMarker(marker, { type: 'line-number', class: `latex-${type}` }) this.markers.push(marker) } } clear () { for (const marker of this.markers) { marker.destroy() } this.markers = [] } }
Add markers in log files
Add markers in log files
JavaScript
mit
thomasjo/atom-latex,thomasjo/atom-latex,thomasjo/atom-latex
--- +++ @@ -14,28 +14,34 @@ this.disposables.add(latex.log.onMessages((messages, reset) => this.addMarkers(messages, reset))) this.disposables.add(new Disposable(() => this.clear())) this.disposables.add(this.editor.onDidDestroy(() => this.dispose())) + this.disposables.add(atom.config.onDidChange('latex.loggingLevel', () => this.update())) this.addMarkers(latex.log.getMessages()) } + update () { + this.clear() + this.addMarkers(latex.log.getMessages()) + } + addMarkers (messages, reset) { - const filePath = this.editor.getPath() - if (reset) this.clear() - if (filePath) { + if (this.editor.getPath()) { for (const message of messages) { - if (message.filePath && message.range && filePath.includes(message.filePath)) { - this.addMarker(message) - } + this.addMarker(message.type, message.filePath, message.range) + this.addMarker(message.type, message.logPath, message.logRange) } } } - addMarker (message) { - const marker = this.editor.markBufferRange(message.range, { invalidate: 'touch' }) - this.editor.decorateMarker(marker, { type: 'line-number', class: `latex-${message.type}` }) - this.markers.push(marker) + addMarker (type, filePath, range) { + const currentFilePath = this.editor.getPath() + if (filePath && range && currentFilePath.includes(filePath)) { + const marker = this.editor.markBufferRange(range, { invalidate: 'touch' }) + this.editor.decorateMarker(marker, { type: 'line-number', class: `latex-${type}` }) + this.markers.push(marker) + } } clear () {
76019487cc2f5a845df07e24d8780a978e36352b
helpers/helpers.js
helpers/helpers.js
fs = require('fs'); module.exports = { publicClasses: function(context, options) { 'use strict'; var ret = ""; for(var i=0; i < context.length; i++) { if(!context[i].itemtype && context[i].access === 'public') { ret = ret + options.fn(context[i]); } else if (context[i].itemtype) { ret = ret + options.fn(context[i]); } } return ret; }, search : function(classes, modules) { 'use strict'; var ret = ''; for(var i=0; i < classes.length; i++) { if(i > 0) { ret += ', '; } ret += "\"" + 'classes/' + classes[i].displayName + "\""; } if(ret.length > 0 && modules.length > 0) { ret += ', '; } for(var j=0; j < modules.length; j++) { if(j > 0) { ret += ', '; } ret += "\"" + 'modules/' + modules[j].displayName + "\""; } return ret; } };
var fs, path, markdown; fs = require('fs'); path = require("path"); markdown = require( "markdown" ).markdown; module.exports = { publicClasses: function(context, options) { 'use strict'; var ret = ""; for(var i=0; i < context.length; i++) { if(!context[i].itemtype && context[i].access === 'public') { ret = ret + options.fn(context[i]); } else if (context[i].itemtype) { ret = ret + options.fn(context[i]); } } return ret; }, search : function(classes, modules) { 'use strict'; var ret = ''; for(var i=0; i < classes.length; i++) { if(i > 0) { ret += ', '; } ret += "\"" + 'classes/' + classes[i].displayName + "\""; } if(ret.length > 0 && modules.length > 0) { ret += ', '; } for(var j=0; j < modules.length; j++) { if(j > 0) { ret += ', '; } ret += "\"" + 'modules/' + modules[j].displayName + "\""; } return ret; }, homeContent : function () { var config = path.join(process.cwd(), 'yuidoc'); if (fs.existsSync(config + '.json') === true) { config = require(config); } var content = config.theme.home if (typeof content === 'string' && content !== '') { content = path.join(process.cwd(), content); } else { content = path.join(process.cwd(), 'README.md'); } if (fs.existsSync(content) === true) { content = fs.readFileSync(content, {encoding: "utf8"}); content = markdown.toHTML(content); } else { content = ''; } return content; } };
Add helper for home page content
Add helper for home page content
JavaScript
mit
staceymoore/yuidoc-bootstrap
--- +++ @@ -1,4 +1,7 @@ +var fs, path, markdown; fs = require('fs'); +path = require("path"); +markdown = require( "markdown" ).markdown; module.exports = { publicClasses: function(context, options) { @@ -38,5 +41,26 @@ } return ret; + }, + homeContent : function () { + var config = path.join(process.cwd(), 'yuidoc'); + if (fs.existsSync(config + '.json') === true) { + config = require(config); + } + + var content = config.theme.home + if (typeof content === 'string' && content !== '') { + content = path.join(process.cwd(), content); + } else { + content = path.join(process.cwd(), 'README.md'); + } + + if (fs.existsSync(content) === true) { + content = fs.readFileSync(content, {encoding: "utf8"}); + content = markdown.toHTML(content); + } else { + content = ''; + } + return content; } };