commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
83d7f5df654287aa6443fe96a3bded4fd3efe04d
add realm in boot
app/boot.js
app/boot.js
(function(document) { 'use strict'; var gitVersion = document.documentElement.attributes['git-version'].value; require.config({ waitSeconds: 120, baseUrl : 'app/', paths: { 'angular' : 'libs/angular-flex/angular-flex', 'angular-route' : 'libs/angular-route/angular-route', 'angular-sanitize' : 'libs/angular-sanitize/angular-sanitize.min', 'authentication' : 'factories/authentication', 'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min', 'bootstrap-datepicker' : 'libs/bootstrap-datepicker/dist/js/bootstrap-datepicker.min', 'css' : 'libs/require-css/css.min', 'lodash' : 'libs/lodash/lodash', 'linqjs' : 'libs/linqjs/linq.min', 'jquery' : 'libs/jquery/dist/jquery', 'guid' : 'libs/ui-guid-generator/dist/ui-guid-generator.min', 'moment' : 'libs/moment/min/moment.min', 'moment-timezone' : 'libs/moment-timezone/builds/moment-timezone-with-data-2010-2020.min', 'ngCookies' : 'libs/angular-cookies/angular-cookies.min', 'ngSmoothScroll' : 'libs/ngSmoothScroll/lib/angular-smooth-scroll', 'shim' : 'libs/require-shim/src/shim', 'text' : 'libs/requirejs-text/text', 'toastr' : 'libs/angular-toastr/dist/angular-toastr.tpls.min', 'URIjs' : 'libs/uri.js/src', 'ng-ckeditor' : 'libs/ng-ckeditor/ng-ckeditor', 'ckeditor' : 'libs/ng-ckeditor/libs/ckeditor/ckeditor', 'ngDialog' : 'libs/ng-dialog/js/ngDialog.min', 'ngInfiniteScroll' : 'libs/ngInfiniteScroll/build/ng-infinite-scroll', 'eonasdan-bootstrap-datetimepicker' :'libs/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min' }, shim: { 'libs/angular/angular' : { deps: ['jquery'] }, 'jquery-ui' : { deps: ['jquery'] }, 'angular' : { deps: ['libs/angular/angular'] }, 'angular-route' : { deps: ['angular'] }, 'ngCookies' : { deps : ['angular'] }, 'bootstrap' : { deps: ['jquery'] }, 'ngSmoothScroll' : { deps: [ 'angular']}, 'guid' : { exports: 'ui_guid_generator' }, 'toastr' : { deps: ['angular']}, 'angular-sanitize' : { deps: ['angular'] }, 'ng-ckeditor' : { deps: ['angular','ckeditor']}, 'ngDialog' : { deps: ['angular' ]}, 'bootstrap-datepicker' : { deps: ['css!libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css'] }, 'eonasdan-bootstrap-datetimepicker': { deps: ['jquery','moment','bootstrap','css!libs/eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css'] }, }, packages: [ { name: 'ammap', main: 'ammap', location : 'libs/ammap3/ammap' } ], urlArgs: 'v=' + gitVersion }); // BOOT if (!require.defined('_slaask')) define("_slaask", window._slaask); require(['angular', 'app', 'bootstrap', 'authentication', 'routes', 'template'], function(ng, app) { ng.element(document).ready(function () { ng.bootstrap(document, [app.name]); }); }); // Fix IE Console (function(a){a.console||(a.console={});for(var c="log info warn error debug trace dir group groupCollapsed groupEnd time timeEnd profile profileEnd dirxml assert count markTimeline timeStamp clear".split(" "),d=function(){},b=0;b<c.length;b++)a.console[c[b]]||(a.console[c[b]]=d)})(window); //jshint ignore:line })(document); if (!Object.assign) { Object.defineProperty(Object, 'assign', { enumerable: false, configurable: true, writable: true, value: function(target) { 'use strict'; if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object'); } var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) { continue; } nextSource = Object(nextSource); var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey]; } } } return to; } }); }
JavaScript
0.000016
@@ -1340,16 +1340,73 @@ croll',%0A + 'realm' : 'utilities/realm',%0A
c140b8c985cfc05ce8ae1326e470d9f4e1231a54
Remove arrow function to remain compatible with older Node versions
lib/metalsmith-metafiles.js
lib/metalsmith-metafiles.js
"use strict"; var MetafileMatcher = require('./metafile-matcher'); // Not needed in Node 4.0+ if (!Object.assign) Object.assign = require('object-assign'); class MetalsmithMetafiles { constructor(options) { options = options || {}; this._initMatcherOptions(options); this._initMatchers(); } _initMatcherOptions(options) { this._matcherOptions = []; var parserOptions = Object.assign({'.json': true}, options.parsers); for (var extension in parserOptions) { var enabled = parserOptions[extension]; if (enabled) { this._matcherOptions.push( Object.assign({}, options, {"extension": extension}) ); } } } _initMatchers() { this._matchers = this._matcherOptions.map((options) => new MetafileMatcher(options)); } // Main interface parseMetafiles(files) { filesLoop: for (var path in files) { for (var matcher of this._matchers) { var metafile = matcher.metafile(path, files[path]); if (!metafile.isMetafile) continue; if (!files[metafile.mainFile]) continue; Object.assign(files[metafile.mainFile], metafile.metadata); if (matcher.deleteMetaFiles) delete files[metafile.path]; continue filesLoop; } } } } module.exports = MetalsmithMetafiles;
JavaScript
0
@@ -746,16 +746,24 @@ ons.map( +function (options @@ -768,10 +768,22 @@ ns) -=%3E +%7B%0A return new @@ -807,16 +807,23 @@ options) +;%0A %7D );%0A %7D%0A%0A
f70047b47f9749c58bc2a0af13aebe70ee6b9c23
add test example of styling
ui/raidboss/data/00-misc/test.js
ui/raidboss/data/00-misc/test.js
'use strict'; [{ zoneRegex: /^Middle La Noscea$/, timelineFile: 'test.txt', // timeline here is additions to the timeline. They can // be strings, or arrays of strings, or functions that // take the same data object (including role and lang) // that triggers do. timeline: [ 'alerttext "Final Sting" before 4 "oh no final sting in 4"', 'alarmtext "Death" before 3', 'alertall "Long Castbar" before 1 speak "voice" "long"', function(data) { if (data.role != 'tank' && data.role != 'healer') return 'hideall "Super Tankbuster"'; }, function(data) { if (!data.role.startsWith('dps')) return 'hideall "Pentacle Sac (DPS)"'; }, function(data) { if (data.role != 'healer') return 'hideall "Almagest"'; return 'alarmtext "Almagest" before 0'; }, function(data) { // <_< let shortName = data.me.substring(0, data.me.indexOf(' ')); return [ '40 "Death To ' + shortName + '!!"', 'hideall "Death"', ]; }, ], timelineTriggers: [ { id: 'Test Angry Dummy', regex: /(Angry Dummy)/, regexDe: /(Wütender Dummy)/, beforeSeconds: 2, infoText: function(data, matches) { return { en: 'Stack for ' + matches[1], de: 'Sammeln für ' + matches[1], }; }, tts: { en: 'Stack', de: 'Sammeln', }, }, ], timelineReplace: [ { locale: 'de', replaceText: { 'Final Sting': 'Schlussstich', 'Almagest': 'Almagest', 'Angry Dummy': 'Wütender Dummy', 'Long Castbar': 'Langer Zauberbalken', 'Dummy Stands Still': 'Dummy still stehen', 'Death': 'Tot', 'Super Tankbuster': 'Super Tankbuster', 'Pentacle Sac': 'Pentacle Sac', 'Engage': 'Start!', }, replaceSync: { 'You bid farewell to the striking dummy': 'Du winkst der Trainingspuppe zum Abschied zu', 'You bow courteously to the striking dummy': 'Du verbeugst dich hochachtungsvoll vor der Trainingspuppe', 'test sync': 'test sync', 'Engage!': 'Start!', }, }, { locale: 'fr', replaceText: { 'Final Sting': 'Dard final', 'Almagest': 'Almageste', 'Angry Dummy': 'Mannequin en colère', 'Long Castbar': 'Longue barre de lancement', 'Dummy Stands Still': 'Mannequin immobile', 'Death': 'Mort', }, replaceSync: { 'You bid farewell to the striking dummy': 'Vous faites vos adieux au mannequin d\'entraînement', 'You bow courteously to the striking dummy': 'Vous vous inclinez devant le mannequin d\'entraînement', 'Engage!': 'À l\'attaque', }, }, ], triggers: [ { id: 'Test Poke', regex: /:You poke the striking dummy/, regexDe: /:Du stupst die Trainingspuppe an/, regexFr: /:Vous touchez légèrement le mannequin d'entraînement du doigt/, preRun: function(data) { data.pokes = (data.pokes || 0) + 1; }, infoText: function(data) { return { en: 'poke #' + data.pokes, de: 'stups #' + data.pokes, fr: 'Touché #' + data.pokes, }; }, }, { id: 'Test Psych', regex: /:You psych yourself up alongside the striking dummy/, regexDe: /:Du willst wahren Kampfgeist in der Trainingspuppe entfachen/, regexFr: /:Vous vous motivez devant le mannequin d'entraînement/, alertText: function(data) { return { en: 'PSYCH!!!', de: 'AUF GEHTS!!!', fr: 'MOTIVATION !!!', }; }, tts: { en: 'psych', de: 'auf gehts', fr: 'Motivation', }, groupTTS: { en: 'group psych', de: 'Gruppen auf gehts', fr: 'group motivation', }, }, { id: 'Test Laugh', regex: /:You burst out laughing at the striking dummy/, regexDe: /:Du lachst herzlich mit der Trainingspuppe/, regexFr: /:Vous vous esclaffez devant le mannequin d'entraînement/, suppressSeconds: 5, alarmText: function(data) { return { en: 'hahahahaha', de: 'hahahahaha', fr: 'Mouahahaha', }; }, tts: { en: 'hahahahaha', de: 'hahahahaha', fr: 'Haha mort de rire', }, groupTTS: { en: 'group laugh', de: 'Gruppenlache', fr: 'group motivation', }, }, { id: 'Test Clap', regex: /:You clap for the striking dummy/, regexDe: /:Du klatschst begeistert Beifall für die Trainingspuppe/, regexFr: /:Vous applaudissez le mannequin d'entraînement/, sound: '../../resources/sounds/WeakAuras/Applause.ogg', soundVolume: 0.3, tts: { en: 'clapity clap', de: 'klatschen', fr: 'Bravo, vive la France', }, }, { id: 'Test Lang', // In game: /echo cactbot lang regex: /00:0038:cactbot lang/, regexDe: /00:0038:cactbot sprache/, infoText: function(data) { return { en: 'Language: ' + data.lang, de: 'Sprache: ' + data.lang, }; }, }, ], }];
JavaScript
0
@@ -1032,32 +1032,177 @@ %5D;%0A %7D,%0A %5D,%0A + timelineStyles: %5B%0A %7B%0A regex: /%5EDeath To/,%0A style: %7B%0A 'color': 'red',%0A 'font-family': 'Impact',%0A %7D,%0A %7D,%0A %5D,%0A timelineTrigge
5a429d05748e49527b0f8fe57ce5118f3211d453
make linter happy
lib/modules/ens/embarkjs.js
lib/modules/ens/embarkjs.js
import namehash from 'eth-ens-namehash'; /*global web3*/ let __embarkENS = {}; // registry interface for later __embarkENS.registryInterface = [ { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "resolver", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "owner", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "resolver", "type": "address" } ], "name": "setResolver", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "label", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setSubnodeOwner", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "owner", "type": "address" } ], "name": "setOwner", "outputs": [], "type": "function" } ]; __embarkENS.resolverInterface = [ { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "addr", "outputs": [ { "name": "", "type": "address" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "content", "outputs": [ { "name": "", "type": "bytes32" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" } ], "name": "name", "outputs": [ { "name": "", "type": "string" } ], "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "kind", "type": "bytes32" } ], "name": "has", "outputs": [ { "name": "", "type": "bool" } ], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "addr", "type": "address" } ], "name": "setAddr", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "hash", "type": "bytes32" } ], "name": "setContent", "outputs": [], "type": "function" }, { "constant": false, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "name", "type": "string" } ], "name": "setName", "outputs": [], "type": "function" }, { "constant": true, "inputs": [ { "name": "node", "type": "bytes32" }, { "name": "contentType", "type": "uint256" } ], "name": "ABI", "outputs": [ { "name": "", "type": "uint256" }, { "name": "", "type": "bytes" } ], "payable": false, "type": "function" } ]; __embarkENS.registryAddresses = { // Mainnet "1": "0x314159265dd8dbb310642f98f50c066173c1259b", // Ropsten "3": "0x112234455c3a32fd11230c42e7bccd4a84e02010", // Rinkeby "4": "0xe7410170f87102DF0055eB195163A03B7F2Bff4A" }; __embarkENS.setProvider = function () { const self = this; // get network id and then assign ENS contract based on that let registryAddresses = this.registryAddresses; this.ens = null; web3.eth.net.getId().then(id => { if (registryAddresses[id] !== undefined) { EmbarkJS.onReady(() => { self.ens = new EmbarkJS.Contract({abi: self.registryInterface, address: registryAddresses[id]}); }); } // todo: deploy at this point }).catch(e => { if (e.message.indexOf('Provider not set or invalid') > -1) { console.warn('ENS is not available in this chain'); return; } console.error(e); }); }; __embarkENS.resolve = function(name) { const self = this; if (self.ens === undefined) return; let node = namehash.hash(name); return self.ens.methods.resolver(node).call().then((resolverAddress) => { let resolverContract = new EmbarkJS.Contract({abi: self.resolverInterface, address: resolverAddress}); return resolverContract.methods.addr(node).call(); }).then((addr) => { return addr; }).catch(err => err); }; __embarkENS.lookup = function(address) { const self = this; if (self.ens === undefined) return; if (address.startsWith("0x")) address = address.slice(2); let node = namehash.hash(address.toLowerCase() + ".addr.reverse"); return self.ens.methods.resolver(node).call().then((resolverAddress) => { let resolverContract = new EmbarkJS.Contract({abi: self.resolverInterface, address: resolverAddress}); return resolverContract.methods.name(node).call(); }).then((name) => { if (name === "" || name === undefined) throw Error("ENS name not found"); return name; }).catch(err => err); };
JavaScript
0.000001
@@ -48,16 +48,26 @@ bal web3 +, EmbarkJS */%0Alet _
8b75a1ce5d544ce35c1c9f0b9cf3833ea0692844
Load token schemas.
app/main.js
app/main.js
exports = module.exports = function(IoC, negotiator, interpreter, translator, unsealer, sealer, logger) { var Tokens = require('tokens').Tokens; var tokens = new Tokens(); return Promise.resolve(tokens) .then(function(tokens) { var components = IoC.components('http://i.bixbyjs.org/tokens/Token'); return Promise.all(components.map(function(comp) { return comp.create(); } )) .then(function(formats) { formats.forEach(function(format, i) { var type = components[i].a['@type']; logger.info('Loaded token type: ' + type); tokens.format(type, format) }); }) .then(function() { return tokens; }); }) .then(function(tokens) { var api = {}; api.seal = function(claims, recipients, options, cb) { console.log('SEAL THIS MESSAGE!'); console.log(claims) var type = options.type || 'application/jwt'; var sealer; try { sealer = tokens.createSealer(type); } catch (ex) { return cb(ex); } sealer.seal(claims, recipients, options, function(err, token) { console.log('SEALED IT!'); console.log(err) console.log(token) if (err) { return cb(err); } return cb(null, token); }); }; api.unseal = function(token, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; var unsealer; try { unsealer = tokens.createUnsealer(); } catch (ex) { return cb(ex); } unsealer.unseal(token, options, function(err, claims, conditions, issuer) { if (err) { return cb(err); } return cb(null, claims, conditions, issuer); }); }; api.negotiate = function(formats) { return negotiator.negotiate(formats); } api.cipher = function(ctx, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; translator.translate(ctx, options, function(err, claims) { if (err) { return cb(err); } // Marshal context necessary for sealing the token. This includes this // that are conceptually "header" information, such as the audience, time // of issuance, expiration, etc. options.audience = ctx.audience; sealer.seal(claims, options, function(err, token) { if (err) { return cb(err); } return cb(null, token); }); }); } api.decipher = function(token, options, cb) { if (typeof options == 'function') { cb = options; options = undefined; } options = options || {}; unsealer.unseal(token, options, function(err, tok) { if (err) { return cb(err); } interpreter.interpret(tok, options, function(err, sctx) { if (err) { return cb(err); } return cb(null, sctx, tok); }); }); } return api; }); }; exports['@implements'] = 'http://i.bixbyjs.org/tokens'; exports['@singleton'] = true; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/tokens/Negotiator', './interpreter', './translator', './unsealer', './sealer', 'http://i.bixbyjs.org/Logger' ];
JavaScript
0
@@ -745,36 +745,804 @@ ion( -tokens) %7B%0A var api = %7B%7D +itokens) %7B%0A var components = IoC.components('http://i.bixbyjs.org/tokens/Schema');%0A return Promise.all(components.map(function(comp) %7B return comp.create(); %7D ))%0A .then(function(schemas) %7B%0A schemas.forEach(function(schema, i) %7B%0A var type = components%5Bi%5D.a%5B'@type'%5D;%0A logger.info('Loaded token schema: ' + type);%0A tokens.schema(type, schema);%0A %7D);%0A %0A //tokens.schema('urn:ietf:params:oauth:token-type:jwt', jwt);%0A %7D)%0A .then(function() %7B%0A return itokens;%0A %7D);%0A %7D)%0A .then(function(tokens) %7B%0A var api = %7B%7D;%0A %0A // TODO: Return tokens directly;%0A api.createSerializer = tokens.createSerializer.bind(tokens);%0A api.createSealer = tokens.createSealer.bind(tokens) ;%0A
7326b14369f16f3ee726b01c443d60fa27197a1d
Fix startup message
app/main.js
app/main.js
const express = require('express') const channels = require('./channels').channels const feed = require('./feed') const fs = require('fs') const path = require('path') const moment = require('moment') const channelEndpoint = require('./channelEndpoint') const app = express() // ------------------------------------------------------------------- // Main View // ------------------------------------------------------------------- app.get('/', (req, res) => { res.render('index', {}) }) // ------------------------------------------------------------------- // Channels // ------------------------------------------------------------------- app.get('/channels/', channelEndpoint.getChannels) app.get('/channels/:channelId', channelEndpoint.getChannel) app.get('/channels/:channelId/update', channelEndpoint.updateChannel) // ------------------------------------------------------------------- // Actions // ------------------------------------------------------------------- app.get('/actions/update', (req, res) => { cleanup() updateAllChannels() res.send("OK") }) app.get('/actions/clear', (req, res) => { cleanup() res.send("OK") }) app.use(express.static('static')) app.use(express.static('dist')) app.set('view engine', 'pug') app.listen(3000, () => { console.log('Example app listening on port 3000!') }) function cleanup(){ console.log("Removing obsolete images") fs.readdir(feed.imageDownloadDir, (err, files) => { if (err) throw err; isImageNotInUse = file => { return channels. filter( c => c.latest && c.latest.image && c.latest.image.includes(file) ) .length == 0 } files .filter( isImageNotInUse ) .forEach( file => { console.log(`Deleting ${file}`) fs.unlink( path.join(feed.imageDownloadDir, file), err => { if (err) throw err; } ) } ) }); } function updateAllChannels(){ // Limit interval between updates. console.log("Last updated at " + lastUpdate) let now = moment() let diff = moment.duration(now.diff(lastUpdate)).asMinutes() if(diff < mininumInterval){ return } lastUpdate = now; channels.forEach( c => { c.update() } ) } // ------------------------------------------------------------------- // Initialize Stuff // ------------------------------------------------------------------- var lastUpdate = moment.unix(0); const mininumInterval = 30; // minutes updateAllChannels()
JavaScript
0.000077
@@ -1288,19 +1288,16 @@ og(' -Example app +SDO Live lis
8a5f3992a9c5f604454ccd1e22352a140b55a5a8
Fix custom greeting bug.
bots/bot.js
bots/bot.js
// Copyright 2011 Vineet Kumar var fs = require('fs'); var repl = require('repl'); var path = require('path'); var ttapi = require('ttapi'); Bot = function(configFile) { this.ttapi = null; this.configFile = configFile || process.argv[2] || Bot.usage(); this.config = {}; this.greetings = {}; this.logChats = false; this.speechHandlers = {}; }; Bot.usage = function() { throw "Usage: node " + process.argv[1] + " <config.json>"; }; Bot.prototype.start = function() { var self = this; fs.readFile(self.configFile, 'utf8', function(err, data) { if (err) throw err; self.config = JSON.parse(data); var prompt = path.basename(self.configFile, path.extname(self.configFile)); var replContext = repl.start(prompt + "> ").context replContext.bot = self; self.readGreetings(); self.ttapi = new ttapi(self.config.auth, self.config.userid, self.config.roomid); replContext.say = self.ttapi.speak.bind(self.ttapi); self.bindHandlers(); }); }; Bot.prototype.bindHandlers = function() { this.ttapi.on('speak', this.onSpeak.bind(this)); this.ttapi.on('registered', this.onRegistered.bind(this)); this.ttapi.on('new_moderator', this.onNewModerator.bind(this)); this.speechHandlers['help'] = this.onHelp.bind(this); this.speechHandlers['commands'] = this.onHelpCommands.bind(this); }; Bot.prototype.readGreetings = function() { var self = this; var greetingsPath = path.join(path.dirname(process.argv[2]), self.config.greetings_filename) fs.readFile(greetingsPath, 'utf8', function(err, data) { if (err) throw err; self.greetings = JSON.parse(data); console.log('loaded %d greetings', Object.keys(self.greetings).length); }); }; /** * @param {{name: string, text: string}} data return by ttapi */ Bot.prototype.onSpeak = function(data) { if (this.debug) { console.dir(data); } if (this.logChats) { console.log('chat: %s: %s', data.name, data.text); } var words = data.text.split(/\s+/); var command = words[0].toLowerCase(); if (command.match(/^[!*\/]/)) { command = command.substring(1); } else if (Bot.bareCommands.indexOf(data.text) == -1) { // bare commands must match the entire text line return; } var handler = this.speechHandlers[command]; if (handler) { handler(data.text, data.name); } }; Bot.prototype.onHelp = function() { this.ttapi.speak(this.config.messages.help.replace(/{room\.name}/g, this.roomInfo.room.name)); }; Bot.prototype.onHelpCommands = function() { this.ttapi.speak( 'commands: ' + Object.keys(this.speechHandlers).map(function(s) { return "*" + s; })).join(', '); }; Bot.prototype.onRegistered = function(data) { if (this.debug) { console.dir(data); } user = data.user[0]; if (user.userid == this.config.userid) { this.ttapi.roomInfo(this.onRoomInfo.bind(this)); } else { this.ttapi.speak(this.greeting(user)); } }; Bot.prototype.greeting = function(user) { var message = this.greetings[user.userid]; if (!message && user.created * 1000 > new Date() - 7 * 24 * 3600 * 1000) { message = randomElement(this.config.messages.newUserGreetings); } else { message = randomElement(this.config.messages.defaultGreetings); } return message.replace(/{user\.name}/g, user.name); }; randomElement = function(ar) { return ar[Math.floor(Math.random() * ar.length)]; }; Bot.prototype.onRoomInfo = function(data) { var self = this; if (this.debug) { console.dir(data); } this.roomInfo = data; this.users = {}; this.roomInfo.users.forEach(function(user) { self.users[user.userid] = user; }); }; Bot.prototype.onNewModerator = function(data) { if (this.debug) { console.dir(data); } this.ttapi.speak(this.config.messages.newModerator .replace(/{user\.name}/g, this.users[data.userid].name) .replace(/{room\.name}/g, this.roomInfo.name)); }; Bot.bareCommands = [ 'help', ]; exports.Bot = Bot; if (process.argv.length > 2) { new Bot(process.argv[2]).start(); }
JavaScript
0
@@ -3141,29 +3141,39 @@ eetings);%0A%09%7D - else +%0A%09if (!message) %7B%0A%09%09message
b2d6812832f9c5b4e53325515eb9b77389b8f0b6
Improve no.js
app/assets/javascripts/admin/lib/no.js
app/assets/javascripts/admin/lib/no.js
var noJS = function() { var htmlTag = document.getElementsByTagName("html")[0]; htmlTag.className = htmlTag.className.replace("no-js", "js"); }; noJS();
JavaScript
0.000077
@@ -1,15 +1,5 @@ -var noJS = +( func @@ -134,15 +134,9 @@ );%0A%7D -;%0A%0AnoJS +) ();%0A
1da511510f2d70f4a00589b59bad410936cbb7d0
Remove line breaks
lib/node_modules/@stdlib/_tools/eslint/rules/no-require-absolute-path/lib/main.js
lib/node_modules/@stdlib/_tools/eslint/rules/no-require-absolute-path/lib/main.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isAbsolutePath = require( '@stdlib/assert/is-absolute-path' ); // VARIABLES // var rule; // FUNCTIONS // /** * Rule for validating that `require` is not called with an absolute file path. * * @param {Object} context - ESLint context * @returns {Object} validators */ function main( context ) { /** * Reports the error message. * * @private * @param {ASTNode} node - node to report */ function report( node ) { context.report({ 'node': node, 'message': 'require() call contains an absolute file path' }); } /** * Checks whether require path is an absolute file path. * * @private * @param {ASTNode} node - node to examine */ function validate( node ) { var requirePath; if ( node.callee.name === 'require' ) { requirePath = node.arguments[ 0 ].value; if ( isAbsolutePath( requirePath ) ) { report( node ); } } } return { 'CallExpression': validate }; } // MAIN // rule = { 'meta': { 'docs': { 'description': 'disallow `require()` calls of absolute file paths' }, 'schema': [] }, 'create': main }; // EXPORTS // module.exports = rule;
JavaScript
0.000014
@@ -1441,21 +1441,17 @@ %0A%09%09%09if ( -%0A%09%09%09%09 + isAbsolu @@ -1471,20 +1471,17 @@ rePath ) -%0A%09%09%09 + ) %7B%0A%09%09%09%09
1c0ae1ef63abba32a48c5ca01d8030ebd4e5bea2
Fix to more simple way.
lib/plugins/console/help.js
lib/plugins/console/help.js
'use strict'; var chalk = require('chalk'); module.exports = function(args){ var command = args._[0]; var list = this.extend.console.list(); if (list.hasOwnProperty(command) && command !== 'help'){ printHelpForCommand(command, list[command]); } else { printAllHelp(list); } }; function printHelpForCommand(command, data){ var options = data.options; console.log('Usage: hexo', command, options.usage || ''); console.log('\nDescription:'); console.log((options.description || options.desc || data.description || data.desc) + '\n'); if (options.arguments) printList('Arguments', options.arguments); if (options.commands) printList('Commands', options.commands); if (options.options) printList('Options', options.options); } function printAllHelp(list){ var keys = Object.keys(list); var commands = []; var key = ''; for (var i = 0, len = keys.length; i < len; i++){ key = keys[i]; commands.push({ name: key, desc: list[key].desc }); } console.log('Usage: hexo <command>\n'); printList('Commands', commands); printList('Global Options', [ {name: '--config', desc: 'Specify config file instead of using _config.yml'}, {name: '--cwd', desc: 'Specify the CWD'}, {name: '--debug', desc: 'Display all verbose messages in the terminal'}, {name: '--draft', desc: 'Display draft posts'}, {name: '--safe', desc: 'Disable all plugins and scripts'}, {name: '--silent', desc: 'Hide output on console'} ]); console.log('For more help, you can use \'hexo help [command]\' for the detailed information'); console.log('or you can check the docs:', chalk.underline('http://hexo.io/docs/')); } function printList(title, list){ var length = 0; var str = title + ':\n'; if (list.length > 0) { length = list[0].name.length; } list.sort(function(a, b){ var nameA = a.name; var nameB = b.name; var cmp = nameA.length - nameB.length; if (cmp > 0){ if (nameA.length > length) length = nameA.length; } else { if (nameB.length > length) length = nameB.length; } if (nameA < nameB) return -1; else if (nameA > nameB) return 1; else return 0; }).forEach(function(item){ var padding = length - item.name.length + 2; str += ' ' + chalk.bold(item.name); while (padding--){ str += ' '; } str += (item.description || item.desc) + '\n'; }); console.log(str); }
JavaScript
0.000021
@@ -1767,51 +1767,72 @@ %0A%0A -if ( list. -length %3E 0) %7B%0A length = list%5B0%5D +forEach(function(item) %7B%0A length = Math.max(length, item .nam @@ -1839,21 +1839,24 @@ e.length +) ;%0A %7D +); %0A%0A list @@ -1933,197 +1933,8 @@ -var cmp = nameA.length - nameB.length;%0A%0A if (cmp %3E 0)%7B%0A if (nameA.length %3E length) length = nameA.length;%0A %7D else %7B%0A if (nameB.length %3E length) length = nameB.length;%0A %7D%0A %0A
a106380210084f92468a85a45d29128a647405ac
Update Gulp/gulpfile.js
Gulp/gulpfile.js
Gulp/gulpfile.js
// Initialize modules const { src, dest, watch, series, parallel } = require("gulp"); // - importing npm packages const sourcemaps = require("gulp-sourcemaps"); const sass = require("gulp-sass"); const concat = require("gulp-concat"); const uglify = require("gulp-uglify"); const postcss = require("gulp-postcss"); const autoprefixer = require("autoprefixer"); const cssnano = require("cssnano"); const replace = require("gulp-replace"); // path variables const files = { scssPath: "app/scss/**/*.scss", jsPath: "app/js/**/*.js", }; // SASS TASK // compiles sass files function scssTask() { return src(files.scssPath) .pipe(sourcemaps.init()) .pipe(sass()) .pipe(postcss([autoprefixer(), cssnano()])) .pipe(sourcemaps.write(".")) .pipe(dest("dist")); } // JS TASK // concat and minify js files, adds minified js to dist folder function jsTask() { return src(files.jsPath) .pipe(concat("all.js")) .pipe(uglify()) .pipe(dest("dist")); } // CACHE BUSTING // clears cache when css & js changes are made // /"cacheBusting" attribute is added to stylesheet link, and script link in index.html // /to track changes by milliseonds of the time file is saved. const cacheBustingString = new Date().getTime(); function cacheBustingTask() { return src(["index.html"]) .pipe(replace(/cacheBusting=\d+/g, `cacheBusting=${cacheBustingString}`)) .pipe(dest(".")); } // WATCH TASK // Monitors files to detect changes in files before running scssTask and jsTask function watchTask() { watch([files.scssPath, files.jsPath], parallel(scssTask, jsTask)); } // DEFAULT TASK // main gulp task, needs to be publicly accessible by command line exports.default = series( parallel(scssTask, jsTask), cacheBustingTask, watchTask );
JavaScript
0
@@ -1079,17 +1079,16 @@ ade%0D%0A// -/ %22cacheBu
bc19ef7a6c660a139fd786fa8e1389df571232cd
refine cli option: -A
lib/plugins/module-paths.js
lib/plugins/module-paths.js
var path = require('path'); var config = require('../config'); var addon = (config.addon || []).map(formatPath); config.systemPluginPath = formatPath(config.SYSTEM_PLUGIN_PATH); function addDebugPaths(plugins) { if (config.debugMode) { plugins.unshift(process.cwd()); } } if (config.pluginPaths) { config.pluginPaths = config.pluginPaths.map(formatPath).concat(addon); addDebugPaths(config.pluginPaths); exports.getPaths = function() { return config.pluginPaths; }; return; } if (config.noGlobalPlugins) { addDebugPaths(addon); exports.getPaths = function() { return addon; }; return; } var env = process.env || {}; var execPath = process.execPath; var isWin = process.platform === 'win32'; var paths = addon.concat(module.paths.map(formatPath)); var globalDir = formatPath(getGlobalDir()); var appDataDir = formatPath(env.APPDATA, 'npm'); var pluginsPath = formatPath(config.baseDir); if (typeof execPath !== 'string') { execPath = ''; } paths = paths.filter(function(p) { return p; }); if (paths.indexOf(pluginsPath) == -1) { paths.unshift(pluginsPath); } pluginsPath = formatPath(env.WHISTLE_PLUGINS_PATH); if (pluginsPath && paths.indexOf(pluginsPath) == -1) { paths.unshift(pluginsPath); } paths.unshift(config.CUSTOM_PLUGIN_PATH, config.systemPluginPath); addDebugPaths(paths); var nvmBin = env.NVM_BIN; if (nvmBin && typeof nvmBin === 'string') { nvmBin = formatPath(path.join(nvmBin, '../lib')); if (paths.indexOf(nvmBin) == -1) { paths.push(nvmBin); } } if (appDataDir && paths.indexOf(appDataDir) == -1) { paths.push(appDataDir); } if (globalDir && paths.indexOf(globalDir) == -1) { paths.push(globalDir); } if (env.PATH && typeof env.PATH === 'string') { var list = env.PATH.trim().split(isWin ? ';' : ':'); ['', '../', '../lib'].forEach(function(prefix) { list.forEach(function(dir) { dir = formatPath(dir, prefix); addPluginPath(dir); }); }); } function addPluginPath(dir) { dir && paths.indexOf(dir) == -1 && paths.push(dir); } function formatPath(dir, prefix) { if (typeof dir !== 'string' || !(dir = dir.trim())) { return null; } if (/(?:^|\/|\\)node_modules[\\\/]?$/.test(dir)) { return dir.replace(/\\/g, '/'); } return path.resolve(dir, prefix || '', 'node_modules').replace(/\\/g, '/'); } function getGlobalDir() { var globalPrefix; if (env.PREFIX) { globalPrefix = env.PREFIX; } else if (isWin) { globalPrefix = execPath && path.dirname(execPath); } else { globalPrefix = execPath && path.dirname(path.dirname(execPath)); if (env.DESTDIR && typeof env.DESTDIR === 'string') { globalPrefix = path.join(env.DESTDIR, globalPrefix); } } if (typeof globalPrefix !== 'string') { return; } return formatPath(globalPrefix, isWin ? '' : 'lib'); } exports.getPaths = function() { return paths; };
JavaScript
0.999971
@@ -69,17 +69,16 @@ addon = -( config.a @@ -87,17 +87,44 @@ on %7C%7C %5B%5D -) +;%0Aaddon = addon.concat(addon .map(for @@ -131,16 +131,17 @@ matPath) +) ;%0A%0Aconfi
2890288be14bbd0a1d3bed382d6dc94ecbdc7d67
DELETE accepts body - unlike GET
jquery.methods.js
jquery.methods.js
(function($) { function getMethodHandler(method) { return function(url, query, body, cb) { var meth = method; if (!cb) { if (typeof body == "function") { cb = body; body = null; } else if (typeof query == "function") { cb = query; query = null; } else { cb = function() {}; } } if (url.pathname) url = url.toString(); if (!url) return cb(new Error("missing url")); var base = document.location.pathname.toString(); if (/\/$/.test(base)) base = base.substring(0, base.length - 1); url = url.replace(/^\.\./, base.split('/').slice(0, -1).join('/')); url = url.replace(/^\./, base); var opts = {}; if (/^(HEAD|GET|COPY|DELETE)$/i.test(meth)) { query = query || body || {}; if (meth == "GET") meth = null; opts.type = 'GET'; } else { if (!body && query) { body = query; query = null; } if (meth == "POST") meth = null; opts.type = "POST"; if (/\.php$/.test(url)) { opts.contentType = "application/x-www-form-urlencoded; charset=utf-8"; opts.data = body || null; } else { opts.contentType = "application/json; charset=utf-8"; opts.data = body && JSON.stringify(body) || null; } } // use custom header - all right with preflighted since it's not GET anyway if (meth) opts.headers = {"X-HTTP-Method-Override": meth}; var qobj = {}; for (var k in query) qobj[k] = query[k]; if (query) url = url.replace(/\/:(\w+)/g, function(str, name) { var val = qobj[name]; if (val != null) { delete qobj[name]; return '/' + val; } else { return '/:' + name; } }); var querystr = $.param(qobj || {}); if (querystr) url += (url.indexOf('?') > 0 ? "&" : "?") + querystr; opts.url = url; return $.ajax(opts).always(function(body, ts, res) { var status = res && res.status || body.status; if (status >= 200 && status < 400) { if (typeof body == "string") body = null; // discard non-json body = res.getResponseHeader('Location') || body; return cb(null, body); } else { if (!status) status = -1; return cb(status, body && body.responseText || body); } }); }; } $.HEAD = getMethodHandler("HEAD"); $.GET = getMethodHandler("GET"); $.PUT = getMethodHandler("PUT"); $.POST = getMethodHandler("POST"); $.DELETE = getMethodHandler("DELETE"); $.COPY = getMethodHandler("COPY"); })(jQuery);
JavaScript
0
@@ -667,15 +667,8 @@ COPY -%7CDELETE )$/i
59bc3173268313bb4546aa1c6da2309da408250d
add warning that allowed_ips must not be empty
protocols/luci-proto-wireguard/htdocs/luci-static/resources/protocol/wireguard.js
protocols/luci-proto-wireguard/htdocs/luci-static/resources/protocol/wireguard.js
'use strict'; 'require uci'; 'require form'; 'require network'; function validateBase64(section_id, value) { if (value.length == 0) return true; if (value.length != 44 || !value.match(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/)) return _('Invalid Base64 key string'); return true; } return network.registerProtocol('wireguard', { getI18n: function() { return _('WireGuard VPN'); }, getIfname: function() { return this._ubus('l3_device') || this.sid; }, getOpkgPackage: function() { return 'wireguard-tools'; }, isFloating: function() { return true; }, isVirtual: function() { return true; }, getDevices: function() { return null; }, containsDevice: function(ifname) { return (network.getIfnameOf(ifname) == this.getIfname()); }, renderFormOptions: function(s) { var o, ss; // -- general --------------------------------------------------------------------- o = s.taboption('general', form.Value, 'private_key', _('Private Key'), _('Required. Base64-encoded private key for this interface.')); o.password = true; o.validate = validateBase64; o.rmempty = false; o = s.taboption('general', form.Value, 'listen_port', _('Listen Port'), _('Optional. UDP port used for outgoing and incoming packets.')); o.datatype = 'port'; o.placeholder = _('random'); o.optional = true; o = s.taboption('general', form.DynamicList, 'addresses', _('IP Addresses'), _('Recommended. IP addresses of the WireGuard interface.')); o.datatype = 'ipaddr'; o.optional = true; o = s.taboption('general', form.Flag, 'nohostroute', _('No Host Routes'), _('Optional. Do not create host routes to peers.')); o.optional = true; // -- advanced -------------------------------------------------------------------- o = s.taboption('advanced', form.Value, 'metric', _('Metric'), _('Optional')); o.datatype = 'uinteger'; o.placeholder = '0'; o.optional = true; o = s.taboption('advanced', form.Value, 'mtu', _('MTU'), _('Optional. Maximum Transmission Unit of tunnel interface.')); o.datatype = 'range(1280,1420)'; o.placeholder = '1420'; o.optional = true; o = s.taboption('advanced', form.Value, 'fwmark', _('Firewall Mark'), _('Optional. 32-bit mark for outgoing encrypted packets. Enter value in hex, starting with <code>0x</code>.')); o.optional = true; o.validate = function(section_id, value) { if (value.length > 0 && !value.match(/^0x[a-fA-F0-9]{1,4}$/)) return _('Invalid hexadecimal value'); return true; }; // -- peers ----------------------------------------------------------------------- try { s.tab('peers', _('Peers'), _('Further information about WireGuard interfaces and peers at <a href=\'http://wireguard.com\'>wireguard.com</a>.')); } catch(e) {} o = s.taboption('peers', form.SectionValue, '_peers', form.TypedSection, 'wireguard_%s'.format(s.section)); o.depends('proto', 'wireguard'); ss = o.subsection; ss.anonymous = true; ss.addremove = true; ss.addbtntitle = _('Add peer'); ss.renderSectionPlaceholder = function() { return E([], [ E('br'), E('em', _('No peers defined yet')) ]); }; o = ss.option(form.Value, 'description', _('Description'), _('Optional. Description of peer.')); o.placeholder = 'My Peer'; o.datatype = 'string'; o.optional = true; o = ss.option(form.Value, 'public_key', _('Public Key'), _('Required. Base64-encoded public key of peer.')); o.validate = validateBase64; o.rmempty = false; o = ss.option(form.Value, 'preshared_key', _('Preshared Key'), _('Optional. Base64-encoded preshared key. Adds in an additional layer of symmetric-key cryptography for post-quantum resistance.')); o.password = true; o.validate = validateBase64; o.optional = true; o = ss.option(form.DynamicList, 'allowed_ips', _('Allowed IPs'), _("Required. IP addresses and prefixes that this peer is allowed to use inside the tunnel. Usually the peer's tunnel IP addresses and the networks the peer routes through the tunnel.")); o.datatype = 'ipaddr'; o.rmempty = false; o = ss.option(form.Flag, 'route_allowed_ips', _('Route Allowed IPs'), _('Optional. Create routes for Allowed IPs for this peer.')); o = ss.option(form.Value, 'endpoint_host', _('Endpoint Host'), _('Optional. Host of peer. Names are resolved prior to bringing up the interface.')); o.placeholder = 'vpn.example.com'; o.datatype = 'host'; o = ss.option(form.Value, 'endpoint_port', _('Endpoint Port'), _('Optional. Port of peer.')); o.placeholder = '51820'; o.datatype = 'port'; o = ss.option(form.Value, 'persistent_keepalive', _('Persistent Keep Alive'), _('Optional. Seconds between keep alive messages. Default is 0 (disabled). Recommended value if this device is behind a NAT is 25.')); o.datatype = 'range(0,65535)'; o.placeholder = '0'; }, deleteConfiguration: function() { uci.sections('network', 'wireguard_%s'.format(this.sid), function(s) { uci.remove('network', s['.name']); }); } });
JavaScript
0
@@ -4054,39 +4054,253 @@ paddr';%0A%09%09o. -rmempty = false +validate = function(section, value) %7B%0A%09%09%09var opt = this.map.lookupOption('allowed_ips', section);%0A%09%09%09var ips = opt%5B0%5D.formvalue(section);%0A%09%09%09if (ips.length == 0) %7B%0A%09%09%09%09return _('Value must not be empty');%0A%09%09%09%7D%0A%09%09%09return true;%0A%09%09%7D ;%0A%0A%09%09o = ss.
a75a66081c26f4b21181e72b76788e4da00a957e
update GroupList
src/GroupList/GroupList.js
src/GroupList/GroupList.js
/** * @file GroupList component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import List from '../List'; import Theme from '../Theme'; import Tip from '../Tip'; import Util from '../_vendors/Util'; import Event from '../_vendors/Event'; import SelectMode from '../_statics/SelectMode'; import LIST_SEPARATOR from '../_statics/ListSeparator'; export default class GroupList extends Component { static SelectMode = SelectMode; static LIST_SEPARATOR = LIST_SEPARATOR; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { value: this.initValue(props) }; this.initValue = ::this.initValue; this.wheelHandler = ::this.wheelHandler; } initValue(props) { if (!props) { return; } const {value, selectMode} = props; if (!selectMode) { return; } if (value) { return value; } switch (selectMode) { case GroupList.SelectMode.MULTI_SELECT: return []; case GroupList.SelectMode.SINGLE_SELECT: return null; default: return value; } } wheelHandler(e) { const {shouldPreventContainerScroll, onWheel} = this.props; shouldPreventContainerScroll && Event.preventContainerScroll(e); onWheel && onWheel(e); } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.state.value) { this.setState({ value: this.initValue(nextProps) }); } } render() { const { children, className, style, data, disabled, ...restProps } = this.props, {value} = this.state, listClassName = (className ? ' ' + className : ''); return ( <div className={'group-list' + listClassName} style={style} disabled={disabled} onWheel={this.wheelHandler}> { data && data.length > 0 ? data.map((item, index) => { if (item === LIST_SEPARATOR) { return <div key={index} className="list-separator"></div>; } return ( <div key={index}> <div className="group-list-group-title">{item.name}</div> <List {...restProps} data={item.children}/> </div> ); }) : null } {children} </div> ); } }; GroupList.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The theme. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The theme of the list item select radio or checkbox. */ selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * Children passed into the ListItem. */ data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({ // group name name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({ /** * The CSS class name of the list button. */ className: PropTypes.string, /** * Override the styles of the list button. */ style: PropTypes.object, /** * The theme of the list button. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The text value of the list button.Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The list item's display text. Type can be string, number or bool. */ text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The desc value of the list button. Type can be string or number. */ desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * If true,the list item will be disabled. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * The message of tip. */ tip: PropTypes.string, /** * The position of tip. */ tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)), /** * If true,the item will have center displayed ripple effect. */ rippleDisplayCenter: PropTypes.bool, /** * You can create a complicated renderer callback instead of value and desc prop. */ itemRenderer: PropTypes.func, /** * Callback function fired when a list item touch-tapped. */ onTouchTap: PropTypes.func }), PropTypes.string, PropTypes.number])) }), PropTypes.symbol])).isRequired, /** * The id field name in data. (default: "id") */ idField: PropTypes.string, /** * The value field name in data. (default: "value") */ valueField: PropTypes.string, /** * The display field name in data. (default: "text") */ displayField: PropTypes.string, /** * The description field name in data. (default: "desc") */ descriptionField: PropTypes.string, /** * If true, the list will be disabled. */ disabled: PropTypes.bool, /** * If true, the list will be at loading status. */ isLoading: PropTypes.bool, /** * The mode of listItem.Can be normal,checkbox. */ selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)), shouldPreventContainerScroll: PropTypes.bool, radioUncheckedIconCls: PropTypes.string, radioCheckedIconCls: PropTypes.string, checkboxUncheckedIconCls: PropTypes.string, checkboxCheckedIconCls: PropTypes.string, checkboxIndeterminateIconCls: PropTypes.string, /** * You can create a complicated renderer callback instead of value and desc prop. */ renderer: PropTypes.func, /** * Callback function fired when the list-item select. */ onItemTouchTap: PropTypes.func, /** * Callback function fired when the list changed. */ onChange: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; GroupList.defaultProps = { className: null, style: null, theme: Theme.DEFAULT, selectTheme: Theme.DEFAULT, data: [], idField: 'id', valueField: 'value', displayField: 'text', descriptionField: 'desc', disabled: false, selectMode: SelectMode.NORMAL, shouldPreventContainerScroll: true, radioUncheckedIconCls: 'fa fa-check', radioCheckedIconCls: 'fa fa-check', checkboxUncheckedIconCls: 'fa fa-square-o', checkboxCheckedIconCls: 'fa fa-check-square', checkboxIndeterminateIconCls: 'fa fa-minus-square' };
JavaScript
0
@@ -762,20 +762,21 @@ -this +Event .wheelHa @@ -783,22 +783,27 @@ ndler = -:: this +::Event .wheelHa @@ -1318,209 +1318,8 @@ %7D%0A%0A - wheelHandler(e) %7B%0A const %7BshouldPreventContainerScroll, onWheel%7D = this.props;%0A shouldPreventContainerScroll && Event.preventContainerScroll(e);%0A onWheel && onWheel(e);%0A %7D%0A%0A @@ -1940,20 +1940,21 @@ nWheel=%7B -this +Event .wheelHa
3c4bba38a4776dd05de92ac19e616b9e459c6d0c
Update codinglove regex
scripts/codinglove.js
scripts/codinglove.js
// Commands // bocbot [give me|spread some] joy|love - Get a random meme from thecodinglove.com var cheerio = require('cheerio'); module.exports = function(robot){ robot.codinglove = { url: 'http://thecodinglove.com/random', textSelector: 'body .post h3', imageSelector: 'body .post img', loadRequestData: function(data){ this.$ = cheerio.load(data); }, send: function(response, location){ var self = this, url = !!location ? location : this.url; // - Get a random image from thecodinglove // - Scrape the image url and caption text from the webpage // - Ignore 'i.minus.com' because it doesn't exist anymore // - Send it response.http(url).get()(function(err, res, body){ if (!!err){ response.send('Unable to get meme from thecodinglove.com'); robot.errors.log(err); return; } // If site responds with a redirect, which it does when you hit '/random', // get new location from response headers and recurse if (res.statusCode == 301 || res.statusCode == 302){ var loc = res.headers['location']; return self.send(response, loc); } // Initialize cheerio self.loadRequestData(body); // Scrape important data from page var caption = self.getText(); var imgUrl = self.getImage(); // If image url is from 'i.minus.com', do the request again because that site no longer works if (imgUrl.indexOf('i.minus.com') >= 0) return self.send(response); // 'tclhost.com' alwawys seems to return '.jpg' files but it has '.gif' files available at the same URL if (imgUrl.indexOf('tclhost.com') >= 0) imgUrl = imgUrl.replace('.jpg', '.gif'); response.send(robot.util.capitalize(caption) + '\n' + imgUrl); }); }, getImage: function(){ return this.$(this.imageSelector).first().attr('src'); }, getText: function(){ return this.$(this.textSelector).first().text(); } }; robot.respond(/((give me|spread) some )?(joy|love)/i, function(res){ robot.codinglove.send(res); }); }
JavaScript
0.000001
@@ -161,18 +161,17 @@ robot)%7B%0A -%09 %0A + %09robot.c @@ -922,17 +922,16 @@ random', - %0A%09%09%09%09// @@ -1469,13 +1469,9 @@ e);%0A -%09%09%09%09 %0A + %09%09%09%09 @@ -1917,16 +1917,117 @@ %09%7D%0A%09%7D;%0A%0A +%09// TODO: Implement the ability to get a number of these: (give me%7Cspread) (some )?(joy%7Clove)( %5Cd+)?%0A %09robot.r @@ -2035,17 +2035,16 @@ spond(/( -( give me%7C @@ -2051,16 +2051,17 @@ spread) +( some )?( @@ -2123,9 +2123,10 @@ );%0A%09%7D);%0A - %7D +%0A
00f7b65c7f084a6a5e241bc9f4e27bcf6ed02ce5
fix bug qd aucun fichier n'est sélectionné
app/main.js
app/main.js
const isDev = require('electron-is-dev'); const {autoUpdater} = require("electron-updater"); const log = require('electron-log'); autoUpdater.logger = log; autoUpdater.logger.transports.file.level = 'info'; log.info('App starting...'); const electron = require('electron'); const app = electron.app; const ipc = electron.ipcMain; let mainWindow; // Adds debug features like hotkeys for triggering dev tools and reload const Window = require('./class/Window').Window; const File = require('./class/File').File; const Tools = require('./class/Tools').Tools; // Prevent window being garbage collected app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { if (!mainWindow) { mainWindow = Window.create(800,600); } }); app.on('ready', () => { if (!isDev) { autoUpdater.checkForUpdates(); } console.log('The application is ready.'); mainWindow = Window.create(800,600); mainWindow.window.webContents.on('did-finish-load', () => { console.log(File); console.log('HTML is loaded.'); }); }); ipc.on('open-file', function (event) { File.window = mainWindow; let file = File.open(); event.sender.send('file-opened', {file: file.file, content: file.content}); }); function sendStatusToWindow(text) { log.info(text); mainWindow.window.webContents.send('message', text); } autoUpdater.on('checking-for-update', () => { sendStatusToWindow('Checking for update...'); }) autoUpdater.on('update-available', (info) => { sendStatusToWindow('Update available.'); mainWindow.window.webContents.send('update-available'); }) autoUpdater.on('update-not-available', (info) => { sendStatusToWindow('Update not available.'); }) autoUpdater.on('error', (err) => { sendStatusToWindow('Error in auto-updater.'+err); }) autoUpdater.on('download-progress', (progressObj) => { sendStatusToWindow(Math.round(progressObj.percent)+'%'); mainWindow.window.webContents.send('download-progress', { 'bytesPerSecond': Tools.FileConvertSize(progressObj.bytesPerSecond), 'percentValue' : Math.round(progressObj.percent), 'percent' : Math.round(progressObj.percent)+'%', 'transferred' : Tools.FileConvertSize(progressObj.transferred), 'total' : Tools.FileConvertSize(progressObj.total) }); }) autoUpdater.on('update-downloaded', (info) => { setTimeout(function() { autoUpdater.quitAndInstall(); }, 1000) });
JavaScript
0.000001
@@ -788,29 +788,29 @@ ndow.create( -800,6 +900,7 00);%0A %7D%0A%7D @@ -1226,24 +1226,56 @@ ile.open();%0A + if (file != null)%0A %7B%0A event.se @@ -1342,16 +1342,22 @@ tent%7D);%0A + %7D%0A %7D);%0A%0Afun
d03a7614f7ed66d400af2c46e8a3c2c877d7e573
Add todo for TTY
app/repl.js
app/repl.js
/* * Memcing * Copyright (c) 2014 Fatih Cetinkaya (http://github.com/cmfatih/memcing) * For the full copyright and license information, please view the LICENSE.txt file. */ // repl module implements Read-Eval-Print-Loop (REPL). // // TODO: Command result messages should be change. // Init reqs /* jslint node: true */ 'use strict'; var utilex = require('utilex'), q = require('q') ; // Init the module exports = module.exports = function(options, cacheInstance) { // Init vars var config = {isDebug: false, verbose: 1, isEnabled: false}, start, // start - function completer // auto complete - function ; // Check params if(typeof cacheInstance !== 'object') throw new Error('Invalid cache instance!'); if(options) { if(options.isDebug === true) config.isDebug = true; if(options.verbose !== undefined) config.verbose = options.verbose; if(options.isEnabled === true) config.isEnabled = true; } // Starts repl start = function start() { if(config.isDebug) utilex.tidyLog('[repl.start]: called'); // Init vars var deferred = q.defer(); // Check config if(config.isEnabled !== true) { deferred.resolve(); return deferred.promise; } else if(process.stdin.isTTY !== true) { deferred.reject("There is not a TTY context for interactive mode. (Or there is a pipe/stdin usage.)"); return deferred.promise; } var rl = require('readline').createInterface({ input: process.stdin, output: process.stdout, terminal: true, completer: completer }); if(config.verbose > 0) utilex.tidyLog('Running on interactive mode. Commands: ' + cacheInstance.cmdList.join(' ')); rl.setPrompt('> '); // set prompt rl.prompt(); // line event rl.on('line', function(line) { // Check the input if(!line.trim()) { rl.prompt(); return; } // Execute the command var cp = cacheInstance.execCmd(line); if(config.isDebug) utilex.tidyLog('[repl.line]: ' + JSON.stringify({cmd: cp.cmd, cmdArgs: cp.cmdArgs, cmdRes: cp.cmdRes})); switch(cp.cmd) { case 'get': console.log((cp.cmdRes && cp.cmdRes.val) ? cp.cmdRes.val : ''); break; case 'set': case 'add': console.log((cp.cmdRes.error) ? 'ERROR' : 'STORED'); break; case 'delete': console.log((cp.cmdRes) ? 'DELETED' : 'ERROR'); break; case 'drop': console.log((cp.cmdRes) ? 'DROPPED' : 'ERROR'); break; case 'increment': case 'decrement': console.log((cp.cmdRes.error) ? 'ERROR' : cp.cmdRes.val); break; case 'dump': // Cleanup expired entries cacheInstance.vacuum({exp: true}); if(cacheInstance.numOfEntry() > 0) { var cData = cp.cmdRes, cDataLen = cacheInstance.numOfEntry(), cDataCnt = 0, cChar = '' ; console.log('['); for(var key in cData) { cDataCnt++; cChar = (cDataCnt < cDataLen) ? ',' : ''; console.log(JSON.stringify(cData[key]) + cChar); } console.log(']'); } else { console.log('[]'); } break; case 'stats': console.log(JSON.stringify(cp.cmdRes, null, 2)); break; case 'vacuum': console.log(cp.cmdRes); break; case 'exit': if(cp.cmdRes.exit === true) process.exit(0); break; default: if(cp.cmdRes && cp.cmdRes.error) { console.log('ERROR (' + cp.cmdRes.error + ')'); } else { console.log('ERROR'); } } rl.prompt(); }); // close event rl.on('close', function() { process.exit(0); }); // SIGINT (^C) event rl.on('SIGINT', function() { rl.clearLine(process.stdin, 0); // clear prompt rl.question('All the cached data will be gone. Are you sure? (y/N) ', function(answer) { if(answer.match(/^(y|yes)$/i)) { rl.close(); } else { rl.prompt(); } }); }); deferred.resolve(); return deferred.promise; }; // Auto complete function for readline. completer = function completer(line) { // Init vars var lineF = line.trim(), cmdList, // cache command list lineCmds, // commands on the line lastCmd, // last command on the line fltrdCmds, // filtered commands matchingCmds // matching commands ; if(!lineF) { matchingCmds = cacheInstance.cmdList; } else { lineCmds = lineF.split(' '); lastCmd = lineCmds.pop(); if(lineCmds.length > 0) { cmdList = cacheInstance.cmdList.map(function(value) { return lineCmds.join(' ') + ' ' + value; }); } else { cmdList = cacheInstance.cmdList; } fltrdCmds = cmdList.filter(function(element) { return element.indexOf(lineF) === 0; }); if(!fltrdCmds.length) { matchingCmds = null; } else if(fltrdCmds.length === 1) { matchingCmds = [fltrdCmds[0] + ' ']; } else { if(lineCmds.length > 0) { fltrdCmds = fltrdCmds.map(function(value) { return value.split(' ').pop(); }); } matchingCmds = fltrdCmds; } } return [matchingCmds, line]; }; // Return return { start: start }; };
JavaScript
0
@@ -1280,32 +1280,216 @@ TTY !== true) %7B%0A + // TODO: There are some issues with TTY Check this code block later.%0A // https://www.npmjs.org/package/ttys%0A // https://github.com/joyent/node/issues/7300%0A%0A deferred.r
01dc3fe9ecf6f2653715b8897a214762806cf2ce
Create WS adapter
app/pouch-ws-adapter.js
app/pouch-ws-adapter.js
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.PouchWsAdapter = factory()); }(this, (function () {'use strict'; function PouchWsAdapter(localDb, remoteDb, options) { var self = this; if (!localDb || !remoteDb) { throw new Error("Please provide a local and a remote db."); } this.localDb = localDb; this.remoteDb = remoteDb; var opts = options || {}; this.forceCreate = opts.forceCreate || true; this.keepAlive = opts.keepAlive || false; this.queryParams = opts.queryParams || ''; this.checkpointCount = opts.checkpointCount || 2; this.checkpointDocId = "_local/checkpoint-" + this.localDb.name; this._initWebsocket(); this.socket.onmessage = function (event) { if (event.data) { var changes = JSON.parse(event.data); changes.forEach(function (change) { //console.log(change); self.remoteDb.get(change.id,{rev: change.changes.length > 0 ? change.changes[0].rev : '', revs: true}).then(function (doc) { //console.log(doc); self.localDb.bulkDocs([doc], {new_edits: false}).then(function () { self._checkpoint(change) }); }).catch(function(err){ console.log("Error when replicating change '" + change.id + "'. Could be that doc was removed meanwhile. Error:" + JSON.stringify(err)); }); }); } } this.getCheckpoint = new Promise(function(resolve, reject){ self.localDb.get(self.checkpointDocId).then(function (doc) { return resolve(doc.seq); }).catch(function () { self.localDb.info().then(function (result) { return resolve(result.update_seq); }).catch(function(){ return resolve(0); }); }); }) if (this.keepAlive) { this.socket.onclose = function () { //reinit the socket if the page is still open //console.log("Attempt to close the websocket"); self._initWebsocket(); }; } }; PouchWsAdapter.prototype._initWebsocket = function () { if (!this.socket || this.forceCreate) { var remoteUrl = this.remoteDb.name.replace("http", "ws"); this.socket = new WebSocket(remoteUrl + "/_changes?feed=websocket"); } } PouchWsAdapter.prototype.sync = function () { var self = this; this.socket.onopen = function (event) { self.getCheckpoint.then(function(seq) { var text = JSON.stringify({ "since": seq, "style": 'all_docs', "query_params" : self.queryParams }); //console.log("Starting sync with following options: " + text); var encoded = new TextEncoder("ascii").encode(text); self.socket.send(encoded); }); }; } PouchWsAdapter.prototype._checkpoint = function (change){ var self = this; if ((change.seq % this.checkpointCount) == 0 && !self.checkpointing) { self.checkpointing = true; self.localDb.get(self.checkpointDocId, {revs: true}).then(function (doc) { doc.seq = change.seq; doc.docId = change.id; doc.rev = change.changes[0].rev; self.localDb.put(doc); }).catch(function () { self.localDb.put({ _id: self.checkpointDocId, seq: change.seq, docId: change.id, rev: change.changes[0].rev }); }).finally(function(){ self.checkpointing = false; }); } } return PouchWsAdapter; })));
JavaScript
0
@@ -275,16 +275,17 @@ trict';%0A +%0A func
017d8aed847dc69e7abaae1bd3edb274c13cb89d
correct isArray
util/domless/domless.js
util/domless/domless.js
steal('can/util/can.js', 'can/util/attr', 'can/util/array/each.js', 'can/util/array/makeArray.js', function (can, attr) { var core_trim = String.prototype.trim; var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; function likeArray(obj) { return typeof obj.length === 'number'; } function flatten(array) { return array.length > 0 ? Array.prototype.concat.apply([], array) : array; } can.isArray = function(arr){ return arr instanceof arr; }; can.isFunction = (function () { if (typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') { return function (value) { return Object.prototype.toString.call(value) === '[object Function]'; }; } else { return function (value) { return typeof value === 'function'; }; } })(); can.trim = core_trim && !core_trim.call('\uFEFF\xA0') ? function (text) { return text == null ? '' : core_trim.call(text); } : // Otherwise use our own trimming functionality function (text) { return text == null ? '' : (text + '') .replace(rtrim, ''); }; // This extend() function is ruthlessly and shamelessly stolen from // jQuery 1.8.2:, lines 291-353. can.extend = function () { /*jshint maxdepth:6 */ var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !can.isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (can.isPlainObject(copy) || (copyIsArray = can.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && can.isArray(src) ? src : []; } else { clone = src && can.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = can.extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } // Return the modified object return target; }; can.map = function (elements, callback) { var values = [], putValue = function (val, index) { var value = callback(val, index); if (value != null) { values.push(value); } }; if (likeArray(elements)) { for (var i = 0, l = elements.length; i < l; i++) { putValue(elements[i], i); } } else { for (var key in elements) { putValue(elements[key], key); } } return flatten(values); }; can.proxy = function (cb, that) { return function () { return cb.apply(that, arguments); }; }; can.attr = attr; return can; });
JavaScript
0.999999
@@ -442,19 +442,21 @@ tanceof -a +A rr +ay ;%0A%09%7D;%0A%0A%09
95cd08ae1d205adff7d495f9e581d7c6f78015de
Add test for lenght()
docs/spec/toteSpec.js
docs/spec/toteSpec.js
describe('tote', function() { function getItemFromLocalStorage( key ) { return localStorage.getItem( key ); } describe('when creating', function() { var ls; afterEach(function() { ls.clear(); }); it('initializes with a namespace', function() { ls = tote('mystash'); expect( ls ).not.toBeNull(); }); it('throws exception, given a null namespace', function() { function createWithNullNamespace() { ls = tote(null); } expect( createWithNullNamespace ).toThrow(); }); it('throws exception, given an empty string namespace', function() { function createWithEmptyStringNamespace() { ls = tote(''); } expect( createWithEmptyStringNamespace ).toThrow(); }); }); describe('api', function() { var ls; beforeEach(function() { ls = tote('myarea'); }); afterEach(function() { ls.clear(); }); it('#set, writes serialized values with namespaced key', function() { var key = 'foo', value = 'FOO!!!'; ls.set(key, value); expect( getItemFromLocalStorage('myarea-foo') ).toEqual( '"' + value + '"' ); }); it('#get, retrieves values with namespaced key', function() { var key = 'bar', value = '!!!BAR'; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('#remove, deletes value associated with namespaced key', function() { var key1 = 'getridofthis', key2 = 'leavealone', value = 'Will be gone soon'; ls.set(key1, value); ls.set(key2, value); ls.remove(key1); expect( ls.get(key1) ).toBeNull(); expect( ls.get(key2) ).toEqual( value ); }); it('#all, returns an array of all values', function() { var key1 = 'x', value1 = 'The simple things', key2 = 'y', value2 = 'Are free?'; ls.set(key1, value1); ls.set(key2, value2); var all = ls.all(); expect( all[0] ).toEqual( value1 ); expect( all[1] ).toEqual( value2 ); }); it('#all({compact:true}), returns an array of a compact representation of all items', function() { var item1 = {'a':'Me'}, item2 = {'b':'You'}; ls.set('a', item1.a); ls.set('b', item2.b); var all = ls.all({compact:true}); expect( all[0] ).toEqual( item1 ); expect( all[1] ).toEqual( item2 ); }); it('#all({kvp:true}), returns an array key-value pairs stored in namespace', function() { var item1 = {key:'x', value:'Me'}, item2 = {key:'y', value:'You'}; ls.set(item1.key, item1.value); ls.set(item2.key, item2.value); var all = ls.all({kvp:true}); expect( all[0] ).toEqual( item1 ); expect( all[1] ).toEqual( item2 ); }); it('#clear, removes only values associated with self', function() { var lsOther = tote('another'), key1 = 'one', key2 = 'two', value1 = 'First value', value2 = 'Second value'; ls.set(key1, value1); ls.set(key2, value2); lsOther.set(key1, value1); lsOther.set(key2, value2); ls.clear(); expect( ls.get(key1) ).toBeNull(); expect( ls.get(key2) ).toBeNull(); expect( lsOther.get(key1) ).toEqual( value1 ); expect( lsOther.get(key2) ).toEqual( value2 ); }); }); describe('handling different datatypes', function() { var ls; beforeEach(function() { ls = tote('datatypes'); }); afterEach(function() { ls.clear(); }); it('persists and retrieves simple string', function() { var key = 'string-simple', value = 'Simple String'; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves string with crazy characters', function() { var key = 'string-complex', value = 'Some overly c\'omplex string/ with "quoted" and *strred* and & etc...'; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves a positive number', function() { var key = 'number-positive', value = 23434; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves a negative number', function() { var key = 'number-negative', value = -4747; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves a float', function() { var key = 'number-float', value = 3700.894; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves a boolean true', function() { var key = 'bool-true', value = true; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); it('persists and retrieves a boolean false', function() { var key = 'bool-false', value = false; ls.set(key, value); expect( ls.get(key) ).toEqual( value ); }); }); });
JavaScript
0.000001
@@ -3985,32 +3985,417 @@ 2 );%0A %7D); +%0A%0A it('#length, returns the number of items stored', function() %7B%0A var key1 = 'item1',%0A key2 = 'item2',%0A value = 'Just counting';%0A ls.set(key1, value);%0A ls.set(key2, value);%0A %0A expect( ls.length() ).toEqual( 2 );%0A%0A ls.remove(key1);%0A expect( ls.length() ).toEqual( 1 );%0A %7D); %0A %7D);%0A%0A%0A d
70bdf677e7d0b3f017f26110ebf7ac14442f74e4
fix delete host
app/remotehost_event.js
app/remotehost_event.js
/*jslint devel:true, node:true, nomen:true */ /*global require, global, $, io, socket, FileDialog, RemoteFTP */ var fs = require('fs'), regFile = '../conf/targetconf.json'; function updateHostList(socket) { "use strict"; fs.readFile(regFile, (function (socket) { return function (err, filebuf) { var host, list = [], k; if (err) { console.log(err); host = {}; } else { host = JSON.parse(filebuf.toString()); } if (host.hasOwnProperty('hpcpf') && host.hpcpf.hasOwnProperty('targets')) { host = host.hpcpf.targets; console.log("host", host); for (k = 0; k < host.length; k = k + 1) { if (host[k]) { if (host[k].userid === undefined) { list.push({name_hr : host[k].name_hr, server : host[k].server, userid : ""}); } else { list.push({name_hr : host[k].name_hr, server : host[k].server, userid : host[k].userid}); } } } socket.emit('updateRemoteHostList', JSON.stringify(list)); } }; }(socket))); } function registerEditorEvent(socket) { "use strict"; socket.on('REMOTEHOST:DELHOST', function (data) { console.log("DEL>" + data.name_hr); fs.readFile(regFile, function (err, filebuf) { var host, targets, jslist, k, prettyprintFunc = function (key, val) { return val; }, writeEndFunc = function (err) { if (err) { console.log(err); return; } updateHostList(socket); }; if (err) { console.log(err); return; } host = JSON.parse(filebuf.toString()); if (host.hasOwnProperty('hpcpf') && host.hpcpf.hasOwnProperty('targets')) { targets = host.hpcpf.targets; for (k = 0; k < targets.length; k = k + 1) { if (targets[k] && targets[k].name_hr === data.name_hr) { delete targets[k]; jslist = JSON.stringify(host, prettyprintFunc, " "); fs.writeFile(regFile, jslist, writeEndFunc); break; } } } }); }); socket.on('REMOTEHOST:REQHOSTINFO', function (data) { console.log(data); console.log("REQHOST>" + data.name_hr); fs.readFile(regFile, function (err, filebuf) { var host, k, hst; console.log("filebuf", filebuf.toString()); if (err) { console.log(err); host = {}; } else { host = JSON.parse(filebuf.toString()); } if (host.hasOwnProperty('hpcpf') && host.hpcpf.hasOwnProperty('targets')) { host = host.hpcpf.targets; for (k = 0; k < host.length; k = k + 1) { if (host[k] && host[k].name_hr === data.name_hr) { hst = host[k]; console.log("hst", hst); socket.emit('updateRemoteInfo', JSON.stringify({ name_hr : data.name_hr, server : hst.server, workpath : hst.workpath, userid : hst.userid, sshkey : hst.sshkey })); } } } }); }); socket.on('REMOTEHOST:reqHostList', function (data) { updateHostList(socket); }); socket.on('REMOTEHOST:AddHost', function (sdata) { var data = JSON.parse(sdata); fs.readFile(regFile, function (err, filebuf) { var host, targets, type, jslist, hst = null, k; if (err) { console.log(err); host = {}; } else { host = JSON.parse(filebuf.toString()); } if (host.hasOwnProperty('hpcpf') && host.hpcpf.hasOwnProperty('targets')) { targets = host.hpcpf.targets; for (k = 0; k < targets.length; k = k + 1) { if (targets[k] && targets[k].name_hr === data.name_hr) { console.log('already server'); hst = targets[k]; } } } if (!hst) { hst = {}; targets.push(hst); } //console.log(data); type = (data.server === 'localhost' ? 'local' : 'remote'); if (type === 'local') { hst.type = type; hst.name_hr = data.name_hr; hst.server = data.server; hst.userid = ""; hst.workpath = data.workpath; } else { hst.type = type; hst.name_hr = data.name_hr; hst.server = data.server; hst.userid = data.userid; hst.workpath = data.workpath; if (data.hasOwnProperty('sshkey')) { hst.sshkey = data.sshkey; } } jslist = JSON.stringify(host, function (key, val) { return val; }, " "); fs.writeFile(regFile, jslist, function (err) { if (err) { console.log(err); return; } updateHostList(socket);//socket.emit('updateRemoteHostList', JSON.stringify(makeHostList(jslist))); }); }); }); } module.exports.registerEditorEvent = registerEditorEvent;
JavaScript
0.000001
@@ -1770,25 +1770,28 @@ %09%09%09%09 -delete targets%5Bk%5D +targets.splice(k, 1) ;%0A%09%09
b6bfc5084e53efb171072d7cde2df707ba57dac4
test time
u2f-test.js
u2f-test.js
var userDict = {} // UserId -> KeyHandle var keyHandleDict = {}; // KeyHandle -> PublicKey var appId = window.location.origin; var version = "U2F_V2"; var p256 = new ECC('p256'); var sha256 = function(s) { return p256.hash().update(s).digest(); }; var BN = p256.n.constructor; // BN = BigNumber function id(s) { return document.getElementById(s); } function msg(s) { id('messages').innerHTML += "<br>" + s; } function userId() { return id('userid').value; } function u2f_b64(s) { return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); } function u2f_unb64(s) { s = s.replace(/-/g, '+').replace(/_/g, '/'); return atob(s + '==='.slice((s.length+3) % 4)); } function string2bytes(s) { var len = s.length; var bytes = new Uint8Array(len); for (var i=0; i<len; i++) bytes[i] = s.charCodeAt(i); return bytes; } function bcat(buflist) { var len = 0; for (var i=0; i<buflist.length; i++) { if (typeof(buflist[i])=='string') buflist[i]=string2bytes(buflist[i]); len += buflist[i].length; } var buf = new Uint8Array(len); len = 0; for (var i=0; i<buflist.length; i++) { buf.set(buflist[i], len); len += buflist[i].length; } return buf; } function chr(c) { return String.fromCharCode(c); } // Because map passes 3 args function bytes2string(bytes) { return Array.from(bytes).map(chr).join(''); } function bytes2b64(bytes) { return u2f_b64(bytes2string(bytes)); } function asn1bytes(asn1) { return asn1.stream.enc.slice( asn1.stream.pos, asn1.stream.pos + asn1.length + asn1.header); } function mkchallenge() { var s = []; for(i=0;i<32;i++) s[i] = String.fromCharCode(Math.floor(Math.random()*256)); return u2f_b64(s.join()); } function enroll_local() { msg("Enrolling user " + userId()); var challenge = mkchallenge(); var req = { "challenge": challenge, "appId": appId, "version": version}; u2f.register(appId, [req], [], function(response) { var result = process_enroll_response(response); msg("User " + userId() + " enroll " + (result ? "succeeded" : "failed")); }); } function auth_local() { msg("Authorizing user " + userId()); keyHandle = userDict[userId()]; if (!keyHandle) { msg("User " + userId() + " not enrolled"); return; } var challenge = mkchallenge(); var req = { "challenge": challenge, "keyHandle": keyHandle, "appId": appId, "version": version }; u2f.sign(appId, challenge, [req], function(response) { var result = verify_auth_response(response); msg("User " + userId() + " auth " + (result ? "succeeded" : "failed")); }); } function auth_timeset() { //OnlyKey settime to keyHandle msg("Authorizing user " + userId()); messageHeader = [255, 255, 255, 255]; messageType = 228 epochTime = Math.round(new Date().getTime() / 1000.0).toString(16); msg("Setting current epoch time on OnlyKey to " + epochTime); keyHandle = messageHeader + messageType + epochTime var challenge = mkchallenge(); var req = { "challenge": challenge, "keyHandle": keyHandle, "appId": appId, "version": version }; u2f.sign(appId, challenge, [req], function(response) { var result = verify_auth_response(response); msg("User " + userId() + " auth " + (result ? "succeeded" : "failed")); }); } function process_enroll_response(response) { var err = response['errorCode']; if (err) { msg("Registration failed with error code " + err); return false; } var clientData_b64 = response['clientData']; var regData_b64 = response['registrationData']; var clientData_str = u2f_unb64(clientData_b64); var clientData = JSON.parse(clientData_str); var origin = clientData['origin']; if (origin != appId) { msg("Registration failed. AppId was " + origin + ", should be " + appId); return false; } var v = string2bytes(u2f_unb64(regData_b64)); var u2f_pk = v.slice(1, 66); // PK = Public Key var kh_bytes = v.slice(67, 67 + v[66]); // KH = Key Handle var kh_b64 = bytes2b64(kh_bytes); var cert_der = v.slice(67 + v[66]); var cert_asn1 = ASN1.decode(cert_der); var cert_pk_asn1 = cert_asn1.sub[0].sub[6].sub[1]; var cert_pk_bytes = asn1bytes(cert_pk_asn1); var cert_key = p256.keyFromPublic(cert_pk_bytes.slice(3), 'der'); var sig = cert_der.slice(cert_asn1.length + cert_asn1.header); var l = [[0], sha256(appId), sha256(clientData_str), kh_bytes, u2f_pk]; var v = cert_key.verify(sha256(bcat(l)), sig); if (v) { userDict[userId()] = kh_b64; keyHandleDict[kh_b64] = u2f_pk; } return v; } function verify_auth_response(response) { var err = response['errorCode']; if (err==127) { // OnlyKey Vendor defined error code used to indicate settime success msg("Successfully set time on OnlyKey"); msg("Google Authenticator feature is now enabled!"); return false; } else if (err) { msg("Auth failed with error code " + err); return false; } var clientData_b64 = response['clientData']; var clientData_str = u2f_unb64(clientData_b64); var clientData_bytes = string2bytes(clientData_str); var clientData = JSON.parse(clientData_str); var origin = clientData['origin']; var kh = response['keyHandle']; var pk = keyHandleDict[kh]; var key = p256.keyFromPublic(pk, 'der'); var sigData = string2bytes(u2f_unb64(response['signatureData'])); var sig = sigData.slice(5); var appid = document.location.origin; var m = bcat([sha256(appid), sigData.slice(0,5), sha256(clientData_bytes)]); if (!key.verify(sha256(m), sig)) return false; var userPresent = sigData[0]; var counter = new BN(sigData.slice(1,5)).toNumber(); msg("User present: " + userPresent); msg("Counter: " + counter); return true; }
JavaScript
0.000006
@@ -2767,16 +2767,60 @@ chTime = + %5B89, 8, 219, 7%5D; //5908DB07%0A //epochTime = Math.ro
5195bc7bf63345c7f57492fcd7e0eed5b6cfa3a6
Fix _.min issue
lib/rank/network-simplex.js
lib/rank/network-simplex.js
const __ = require('lodash3') const _ = require('lodash') const feasibleTree = require('./feasible-tree') const slack = require('./util').slack const initRank = require('./util').longestPath const preorder = require('../graphlib').alg.preorder const postorder = require('../graphlib').alg.postorder const simplify = require('../util').simplify module.exports = networkSimplex // Expose some internals for testing purposes networkSimplex.initLowLimValues = initLowLimValues networkSimplex.initCutValues = initCutValues networkSimplex.calcCutValue = calcCutValue networkSimplex.leaveEdge = leaveEdge networkSimplex.enterEdge = enterEdge networkSimplex.exchangeEdges = exchangeEdges /* * The network simplex algorithm assigns ranks to each node in the input graph * and iteratively improves the ranking to reduce the length of edges. * * Preconditions: * * 1. The input graph must be a DAG. * 2. All nodes in the graph must have an object value. * 3. All edges in the graph must have "minlen" and "weight" attributes. * * Postconditions: * * 1. All nodes in the graph will have an assigned "rank" attribute that has * been optimized by the network simplex algorithm. Ranks start at 0. * * * A rough sketch of the algorithm is as follows: * * 1. Assign initial ranks to each node. We use the longest path algorithm, * which assigns ranks to the lowest position possible. In general this * leads to very wide bottom ranks and unnecessarily long edges. * 2. Construct a feasible tight tree. A tight tree is one such that all * edges in the tree have no slack (difference between length of edge * and minlen for the edge). This by itself greatly improves the assigned * rankings by shorting edges. * 3. Iteratively find edges that have negative cut values. Generally a * negative cut value indicates that the edge could be removed and a new * tree edge could be added to produce a more compact graph. * * Much of the algorithms here are derived from Gansner, et al., "A Technique * for Drawing Directed Graphs." The structure of the file roughly follows the * structure of the overall algorithm. */ function networkSimplex (g) { g = simplify(g) initRank(g) const t = feasibleTree(g) initLowLimValues(t) initCutValues(t, g) let e let f while ((e = leaveEdge(t))) { f = enterEdge(t, g, e) exchangeEdges(t, g, e, f) } } /* * Initializes cut values for all edges in the tree. */ function initCutValues (t, g) { let vs = postorder(t, t.nodes()) vs = vs.slice(0, vs.length - 1) _.each(vs, function (v) { assignCutValue(t, g, v) }) } function assignCutValue (t, g, child) { const childLab = t.node(child) const parent = childLab.parent t.edge(child, parent).cutvalue = calcCutValue(t, g, child) } /* * Given the tight tree, its graph, and a child in the graph calculate and * return the cut value for the edge between the child and its parent. */ function calcCutValue (t, g, child) { const childLab = t.node(child) const parent = childLab.parent // True if the child is on the tail end of the edge in the directed graph let childIsTail = true // The graph's view of the tree edge we're inspecting let graphEdge = g.edge(child, parent) // The accumulated cut value for the edge between this node and its parent let cutValue = 0 if (!graphEdge) { childIsTail = false graphEdge = g.edge(parent, child) } cutValue = graphEdge.weight _.each(g.nodeEdges(child), function (e) { const isOutEdge = e.v === child const other = isOutEdge ? e.w : e.v if (other !== parent) { const pointsToHead = isOutEdge === childIsTail const otherWeight = g.edge(e).weight cutValue += pointsToHead ? otherWeight : -otherWeight if (isTreeEdge(t, child, other)) { const otherCutValue = t.edge(child, other).cutvalue cutValue += pointsToHead ? -otherCutValue : otherCutValue } } }) return cutValue } function initLowLimValues (tree, root) { if (arguments.length < 2) { root = tree.nodes()[0] } dfsAssignLowLim(tree, {}, 1, root) } function dfsAssignLowLim (tree, visited, nextLim, v, parent) { const low = nextLim const label = tree.node(v) visited[v] = true _.each(tree.neighbors(v), function (w) { if (!_.has(visited, w)) { nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v) } }) label.low = low label.lim = nextLim++ if (parent) { label.parent = parent } else { // TODO should be able to remove this when we incrementally update low lim delete label.parent } return nextLim } function leaveEdge (tree) { return _.find(tree.edges(), function (e) { return tree.edge(e).cutvalue < 0 }) } function enterEdge (t, g, edge) { let v = edge.v let w = edge.w // For the rest of this function we assume that v is the tail and w is the // head, so if we don't have this edge in the graph we should flip it to // match the correct orientation. if (!g.hasEdge(v, w)) { v = edge.w w = edge.v } const vLabel = t.node(v) const wLabel = t.node(w) let tailLabel = vLabel let flip = false // If the root is in the tail of the edge then we need to flip the logic that // checks for the head and tail nodes in the candidates function below. if (vLabel.lim > wLabel.lim) { tailLabel = wLabel flip = true } const candidates = _.filter(g.edges(), function (edge) { return flip === isDescendant(t, t.node(edge.v), tailLabel) && flip !== isDescendant(t, t.node(edge.w), tailLabel) }) return __.min(candidates, function (edge) { return slack(g, edge) }) } function exchangeEdges (t, g, e, f) { const v = e.v const w = e.w t.removeEdge(v, w) t.setEdge(f.v, f.w, {}) initLowLimValues(t) initCutValues(t, g) updateRanks(t, g) } function updateRanks (t, g) { const root = _.find(t.nodes(), function (v) { return !g.node(v).parent }) let vs = preorder(t, root) vs = vs.slice(1) _.each(vs, function (v) { const parent = t.node(v).parent let edge = g.edge(v, parent) let flipped = false if (!edge) { edge = g.edge(parent, v) flipped = true } g.node(v).rank = g.node(parent).rank + (flipped ? edge.minlen : -edge.minlen) }) } /* * Returns true if the edge is in the tree. */ function isTreeEdge (tree, u, v) { return tree.hasEdge(u, v) } /* * Returns true if the specified node is descendant of the root node per the * assigned low and lim attributes in the tree. */ function isDescendant (tree, vLabel, rootLabel) { return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim }
JavaScript
0
@@ -1,34 +1,4 @@ -const __ = require('lodash3')%0A cons @@ -5615,14 +5615,15 @@ urn -_ _.min +By (can
722edfc7dda11c185c8bcf4210d8f5bf50753777
Add override status to getMode
webapp/api/programme.js
webapp/api/programme.js
'use strict'; const async = require('async'); const ProgrammeFileWriter = require('heatingprogramme').ProgrammeFileWriter; const programmeModelBuilder = require('../models/programmeModelBuilder'); const ProgrammeProvider = require('../models/programmeProvider'); const CallingForHeatFile = require('../models/callingForHeatFile'); const Joi = require('joi'); const comfortSetPointSchema = Joi.number().precision(2).required(); function writeProgrammeAndReturnModes(programme, req, res) { const programmeDataPath = req.app.get('programmeDataPath') async.series({ programme: function (callback) { ProgrammeFileWriter.writeProgramme(programmeDataPath, programme, (err) => { callback(err, programmeModelBuilder.buildFromProgramme(programme)); }); }, callingForHeat: function (callback) { setTimeout(() => { new CallingForHeatFile(programmeDataPath).readFromFile((err, callingForHeat) => { callback(err, callingForHeat); }); }, 500); } }, (err, results) => { if (err) { res.status(500); res.end(); return; } res.send(results); }); } function createProgrammeProvider(req) { return new ProgrammeProvider(req.app.get('programmeDataPath')) } function comfortUntilDate(untilDate, req, res) { createProgrammeProvider(req).getProgramme((programme) => { programme.setComfortOverride(untilDate); writeProgrammeAndReturnModes(programme, req, res); }); } function setbackUntilDate(untilDate, req, res) { createProgrammeProvider(req).getProgramme((programme) => { programme.setSetbackOverride(untilDate); writeProgrammeAndReturnModes(programme, req, res); }); } function addDayToDate(date) { date.setDate(date.getDate() + 1); return date; } function setDateTimeToLocalMidnight(date) { date.setHours(0); date.setMinutes(0); date.setSeconds(0); date.setUTCMilliseconds(0); return date; } function setModeUntilDate(req, res, modeFunc) { const untilParam = req.params.until; const dateExpr = /^(\d{4})-?(\d{2})-?(\d{2})T(\d{2}):?(\d{2}):?(\d{2})Z$/; if (/^\d{13,14}$/.test(untilParam)) { // time in milliseconds UTC const untilInMs = parseInt(req.params.until); modeFunc(new Date(untilInMs), res); } else if (dateExpr.test(untilParam)) { // fully qualified ISO8601 UTC{ const matchedDate = untilParam.match(dateExpr); const untilDate = new Date(Date.UTC(matchedDate[1], matchedDate[2], matchedDate[3], matchedDate[4], matchedDate[5], matchedDate[6])); modeFunc(untilDate, req, res); } else { let untilDate = addDayToDate(new Date()); untilDate = setDateTimeToLocalMidnight(untilDate); modeFunc(untilDate, req, res); } } module.exports = { getHeatingMode: function(req, res) { createProgrammeProvider(req).getProgramme((programme) => { const now = new Date(); const response = { heatingEnabled: programme.isHeatingEnabled(), comfortLevelEnabled: programme.isInComfortMode(now), }; res.send(response); }); }, setHeatingModeAuto: function (req, res) { createProgrammeProvider(req).getProgramme((programme) => { programme.setHeatingOn(); programme.clearOverride(); writeProgrammeAndReturnModes(programme, req, res); }); }, setHeatingModeOff: function (req, res) { createProgrammeProvider(req).getProgramme((programme) => { programme.setHeatingOff(); writeProgrammeAndReturnModes(programme, req, res); }); }, setComfortMode: function (req, res) { setModeUntilDate(req, res, comfortUntilDate); }, setSetbackMode: function (req, res) { setModeUntilDate(req, res, setbackUntilDate); }, getComfortSetPoint: function (req, res) { createProgrammeProvider(req).getProgramme((programme) => { const response = { comfortSetPoint: programme.getComfortSetPoint() }; res.send(response); }); }, setComfortSetPoint: function (req, res) { createProgrammeProvider(req).getProgramme((programme) => { Joi.validate(req.body, comfortSetPointSchema, (err, setpoint) => { if (err) { res.status(400).send(`Set Point must be a number with maximum precision of 2 decimal places. ${req.body}`); } else { programme.setComfortSetPoint(setpoint); ProgrammeFileWriter.writeProgramme(req.app.get('programmeDataPath'), programme, (err) => { if (err) { res.status(500); res.end(); return; } const response = { comfortSetPoint: programme.getComfortSetPoint() }; res.send(response); }); } }); }); } };
JavaScript
0.000001
@@ -2994,16 +2994,70 @@ e(now),%0A + inOverride: programme.isInOverridePeriod(now)%0A %7D;
649056d246384ff84723876c7eb564e1b62340a8
make the slide a little cleaner.
js/BlogScratch.js
js/BlogScratch.js
//// //// NOTE: This is test/demo code--don't worry too much about it. //// jQuery(document).ready(function(){ /// /// Do a demo D3 chart from docs. /// var data = [4, 8, 15, 16, 23, 35, 42, 3, 3, 6, 9, 11, 18, 26]; var width = 420; var barHeight = 20; var x = d3.scale.linear() .domain([0, d3.max(data)]) .range([0, width]); var chart = d3.select("#d3-chart") .attr("width", width) .attr("height", barHeight * data.length); var bar = chart.selectAll("g") .data(data) .enter().append("g") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); bar.append("rect") .attr("width", x) .attr("height", barHeight - 1); bar.append("text") .attr("x", function(d) { return x(d) - 3; }) .attr("y", barHeight / 2) .attr("dy", ".35em") .text(function(d) { return d; }); /// /// Do a demo ticker. /// var ticker_cache = [ 'Cras justo odio', 'Dapibus ac facilisis in', 'Morbi leo risus', 'Porta ac consectetur ac', 'Vestibulum at eros', ]; function _cycle_ticker(){ // Rotate top item to end. var top = ticker_cache.shift(); ticker_cache.push(top); // Slide up and remove. jQuery('#ticker-demo li').first().slideUp(500, function(){ jQuery('#ticker-demo li').first().remove(); var new_elt = '<li class="list-group-item">' + top +'</li>'; jQuery(new_elt).hide().appendTo('#ticker-demo').slideDown(500,function(){ // When done, start countdown to new cycle. window.setTimeout(_cycle_ticker, 3500); }); }); } _cycle_ticker(); // start cycling });
JavaScript
0
@@ -1062,17 +1062,20 @@ %0A %5D;%0A -%09 + %0A fun @@ -1210,16 +1210,63 @@ remove. + Plus removal step (arbitrary--could be below). %0A%09jQuery @@ -1318,16 +1318,60 @@ tion()%7B%0A +%09 // Get rid of the disappeared element.%0A %09 jQu @@ -1416,18 +1416,83 @@ );%0A%09 - %0A%09 +%7D); %0A%09// Add and slide in. Plus restart wait (arbitrary--could be above).%0A%09 var @@ -1549,20 +1549,16 @@ /li%3E';%0A%09 - jQuery(n @@ -1624,17 +1624,20 @@ ion()%7B%0A%09 -%09 + // When @@ -1673,17 +1673,20 @@ cycle.%0A%09 -%09 + window.s @@ -1721,22 +1721,8 @@ 0);%0A -%09 %7D);%09 %0A %09%7D);
92200769cfbcf4bb08044acdc1d47822d33bade3
Debug sidebar js
module/htdocs/js/sb-admin-2.js
module/htdocs/js/sb-admin-2.js
$(function() { $('#side-menu').metisMenu(); }); //Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size $(function() { $(window).bind("load resize", function() { topOffset = 50; width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse'); topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse'); } height = ((this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height) - 1; height = height - topOffset; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }); var url = window.location; var element = $('ul.nav a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; }).addClass('active').parent().parent().addClass('in').parent(); if (element.is('li')) { element.addClass('active'); } });
JavaScript
0
@@ -935,14 +935,21 @@ $(' -ul.nav +#sidebar-menu a') @@ -961,32 +961,144 @@ er(function() %7B%0A + if (this.href.indexOf('#', this.href.length - '#'.length) !== -1) %7B%0A return false;%0A %7D%0A return t @@ -1142,16 +1142,22 @@ his.href + + '?' ) == 0;%0A
412a935cda8b0497da7a0829bffca9f8053e2854
Fix lint warning
editor/validate.js
editor/validate.js
'use strict'; /*global vl, d3, ZSchema */ var vgSchema = null; var validateVl = function(vlspec) { var validator = new ZSchema(); var valid = validator.validate(vlspec, vl.schema.schema); if (!valid) { console.error(validator.getLastErrors()); } }; var validateVg = function(vgspec) { var validator = new ZSchema(); var callback = function() { var valid = validator.validate(vgspec, vgSchema); if (!valid) { console.error(validator.getLastErrors()); } }; if (vgSchema) { callback(); } else { d3.json('editor/bower_components/vega/vega-schema.json', function(error, json) { if (error) return console.warn(error); vgSchema = json; callback(); }); } };
JavaScript
0.000009
@@ -32,16 +32,40 @@ ZSchema +, validateVl, validateVg */%0A%0Avar
0290f5112942a65a21a6b5353944c2a0779ecd67
Use tmpPath and tmpName is the deploy route
lib/server/routes/deploy.js
lib/server/routes/deploy.js
// > The deploy post route. // > Removes previous deploy if it exists. // > Accepts a tarball, unpacks it and puts it in the right place. // // > Copyright © 2013 Matt Styles // > Licensed under the MIT license 'use strict'; // Includes var icarus = require( '../../icarus' ), fs = require( 'fs' ), path = require( 'path' ), util = require( 'util' ), tar = require( 'tar' ), fstream = require( 'fstream' ), zlib = require( 'zlib' ), async = require( 'async' ), rimraf = require( 'rimraf' ); // Export the test route module.exports = function( req, res ) { var deployPath = path.join( icarus.utils.getHome(), icarus.config.get( 'dir.main' ), icarus.config.get( 'dir.deploy' ) ); // Get some info about the transfer var reqData = { start: new Date(), projectName: req.query.pkgName, tmpName: req.query.tmpName.replace( /\/tmp\//, '/archive/' ) }; // Store the archive folder.<br> // @todo should be in the config. var archiveFolder = '.icarus/archive/'; // Remove a pre-existing deploy of the project var removeProject = function( done ) { fs.exists( path.join( deployPath, reqData.projectName ), function( exists ) { // If a previous deploy exists then remove it if ( exists ) { icarus.log.info( 'Removing previous deploy of '.grey + reqData.projectName.yellow.bold ); // Remove the previous project directory rimraf( path.join( deployPath, reqData.projectName ), function( err ) { if ( err ) { icarus.log.info( 'An error occurred removing a previous deploy : '.red + err ); process.exit(); } icarus.log.info( 'Previous deploy '.grey + 'removed'.yellow.bold ); done(); }); } else { // If no previous deploy then log it icarus.log.info( 'No previous deploy to remove'.grey ); // Inform async we are finished done(); } }); }; icarus.log.info( 'Attempting to deploy '.grey + reqData.projectName.yellow.bold + ' tarball into '.grey + deployPath.yellow.bold ); // Do some maintenance work before piping the request object into the deploy folder async.series([ removeProject ], function( err, result ) { if ( err ) { icarus.log.error( '\nError deploying ' + reqData.projectName + ' : ' + err ); } // Extract the request into the correct directory req .pipe( zlib.Unzip() ) .pipe( tar.Extract( { path: deployPath })) .on( 'error', function( err ) { icarus.log.info( '\nDeployment'.grey + ' unsuccessful'.red.bold ); icarus.log.debug( 'The following error occurred while trying to deploy ' + reqData.projectName ); icarus.log.debug( err ); res.send( { "status": "something went horribly, horribly wrong" } ); return; }) .on( 'end', function () { // Do a basic speed check and record it var endTime = new Date(); icarus.log.info( 'Time taken to deploy: '.grey + ( icarus.utils.timeFormat( endTime - reqData.start ) ).toString().yellow.bold ); icarus.log.info( 'Deployment'.grey + (reqData.projectName ? ' of '.grey + reqData.projectName.yellow.bold : '') + ' ...'.grey + 'successful'.green.bold ); res.send( { "status": "deployed" } ); }); // Write the tarball into an archive directory req .pipe( fstream.Writer( reqData.tmpName ) ) .on( 'ready', function() { icarus.log.info( 'Writing archive to '.grey + reqData.tmpName.yellow.bold ); }) .on ('error', function( err ) { icarus.log.error( 'Error storing archive : ' + err ); }) .on( 'close', function() { icarus.log.info( 'finished writing to archive'.grey ); }); }); };
JavaScript
0.000001
@@ -710,24 +710,144 @@ ploy' ) );%0A%0A + // Store the archive folder.%3Cbr%3E%0A // @todo should be in the config.%0A var archiveFolder = '.icarus/archive/';%0A%0A // Get s @@ -1000,49 +1000,37 @@ ame. -replace( /%5C/tmp%5C//, '/archive/' ) +match( /%5B%5E%5C/%5D+$/ )%5B0%5D %0A %7D;%0A %0A @@ -1029,127 +1029,99 @@ %7D;%0A -%0A -// Store the archive folder.%3Cbr%3E%0A // @todo should be in the config.%0A var archiveFolder = '.icarus/archive/'; +reqData.tmpPath = path.join( icarus.utils.getHome(), archiveFolder, reqData.tmpName );%0A %0A%0A @@ -1801,22 +1801,14 @@ -process.exit() +return ;%0A @@ -3915,16 +3915,66 @@ .Writer( + path.join( icarus.utils.getHome(), archiveFolder, reqData @@ -3985,16 +3985,18 @@ Name ) ) + ) %0A @@ -4100,20 +4100,20 @@ Data.tmp -Name +Path .yellow.
ef96e9237500d17b115d066d3cd0409b760d4891
Remove tiny red dot - fixes #33
client/y.js
client/y.js
function userLoggedIn(user) { var options = { userCloseable: false, timeout: 3000 }; if (user) return true; Notifications.warn('Sign in', 'Board changes not allowed, please sign in or feel free to watch :-)', options); return false; } Template.game.events({ 'click .undo_move': function() { var user = Meteor.user(); if (!userLoggedIn(user)) return; Meteor.call('undo'); }, 'click .reset_board': function() { var user = Meteor.user(); if (!userLoggedIn(user)) return; Meteor.call('reset'); }, 'click .mute': function() { var mute = Session.get("mute"); if (mute === true) { document.getElementById("MuteButton").value = "Mute"; Session.set("mute", false); } else { document.getElementById("MuteButton").value = "UnMute"; Session.set("mute", true); } } }); Deps.autorun(function () { Meteor.subscribe('moves'); Meteor.subscribe('stones'); Meteor.subscribe('users'); var lastMove = Moves.findOne({}, {sort: {step: -1}}); if (typeof(lastMove) != 'undefined' && lastMove.step > 0) { if (Session.get("mute")) return; var audioElement = document.createElement('audio'); audioElement.setAttribute('src', 'stone.ogg'); audioElement.load(); audioElement.play(); } }); Template.board.helpers({ moves: function() { return Moves.find(); }, stones: function() { return Stones.find(); }, lastMove: function() { return [Moves.findOne({}, {sort: {step: -1}})]; } }); Template.lastMoveTemplate.helpers({ cx: function() { var stone = Stones.findOne({name: this.name}); return stone && stone.x; }, cy: function() { var stone = Stones.findOne({name: this.name}); return stone && stone.y; } }); Template.move.helpers({ color: function() { var color = (this.step === 0) ? "yellow" : (this.step % 2 === 0) ? "white" : "black"; return color; }, opacity: function() { var opacity = (this.step === 0) ? 0 : 1; return opacity; }, rsize: function() { var rsize = (this.step === 0) ? 17 : 10; return rsize; }, cx: function() { var stone = Stones.findOne({name: this.name}); return stone && stone.x; }, cy: function() { var stone = Stones.findOne({name: this.name}); return stone && stone.y; } }); Template.stone.events({ 'click': function() { var user = Meteor.user(); if (!userLoggedIn(user)) return; Meteor.call('move', this.name, function(error, id) { if(error) { console.log(error.reason); } }); } }); /* Template.listMoves.helpers({ moves: function() { return Moves.find({}, {sort: {step: 1}}); } }); */ Template.listMovesBlack.helpers({ moves: function() { return Moves.find({step: {$mod: [2, 1]}}, {sort: {step: 1}}); } }); Template.listMovesWhite.helpers({ moves: function() { return Moves.find({step: {$mod: [2, 0]}}, {sort: {step: 1}}); } }); Template.usersOnline.helpers({ users: function() { return Meteor.users.find({ "status.online": true }); } });
JavaScript
0
@@ -1513,16 +1513,23 @@ -return %5B +var lastMove = Move @@ -1561,16 +1561,81 @@ p: -1%7D%7D) +;%0A if (typeof(lastMove) != 'undefined')%0A return %5BlastMove %5D;%0A %7D%0A%7D
14b04b085f0688c37580b7622ef36b062e4d0bcf
Update to return the title Function
app/routes/ember-cli.js
app/routes/ember-cli.js
import Route from '@ember/routing/route'; export default Route.extend({ titleToken() { return 'Ember CLI'; } });
JavaScript
0.000172
@@ -77,13 +77,8 @@ itle -Token () %7B @@ -99,16 +99,42 @@ mber CLI + - Ember API Documentation ';%0A %7D%0A%7D
9807ec6539ecc67e7a6687f21ec8033bcddf95d4
Fix phrasing when re-subscribing user to a stream.
frontend_tests/node_tests/stream_data.js
frontend_tests/node_tests/stream_data.js
global.stub_out_jquery(); add_dependencies({ stream_color: 'js/stream_color.js' }); set_global('blueslip', {}); var stream_data = require('js/stream_data.js'); (function test_basics() { var denmark = { subscribed: false, color: 'blue', name: 'Denmark', stream_id: 1, in_home_view: false }; var social = { subscribed: true, color: 'red', name: 'social', stream_id: 2, in_home_view: true, invite_only: true }; var test = { subscribed: true, color: 'yellow', name: 'test', stream_id: 3, in_home_view: false, invite_only: false }; stream_data.add_sub('Denmark', denmark); stream_data.add_sub('social', social); assert(stream_data.all_subscribed_streams_are_in_home_view()); stream_data.add_sub('test', test); assert(!stream_data.all_subscribed_streams_are_in_home_view()); assert.equal(stream_data.get_sub('denmark'), denmark); assert.equal(stream_data.get_sub('Social'), social); assert.deepEqual(stream_data.home_view_stream_names(), ['social']); assert.deepEqual(stream_data.subscribed_streams(), ['social', 'test']); assert.deepEqual(stream_data.get_colors(), ['red', 'yellow']); assert(stream_data.is_subscribed('social')); assert(stream_data.is_subscribed('Social')); assert(!stream_data.is_subscribed('Denmark')); assert(!stream_data.is_subscribed('Rome')); assert(stream_data.get_invite_only('social')); assert(!stream_data.get_invite_only('unknown')); assert.equal(stream_data.get_color('social'), 'red'); assert.equal(stream_data.get_color('unknown'), global.stream_color.default_color); assert.equal(stream_data.get_name('denMARK'), 'Denmark'); assert.equal(stream_data.get_name('unknown Stream'), 'unknown Stream'); assert(stream_data.in_home_view('social')); assert(!stream_data.in_home_view('denmark')); // Deleting a subscription makes you unsubscribed from the perspective of // the client. // Deleting a subscription is case-insensitive. stream_data.delete_sub('SOCIAL'); assert(!stream_data.is_subscribed('social')); }()); (function test_get_by_id() { stream_data.clear_subscriptions(); var id = 42; var sub = { name: 'Denmark', subscribed: true, color: 'red', stream_id: id }; stream_data.add_sub('Denmark', sub); sub = stream_data.get_sub('Denmark'); assert.equal(sub.color, 'red'); sub = stream_data.get_sub_by_id(id); assert.equal(sub.color, 'red'); }()); (function test_subscribers() { stream_data.clear_subscriptions(); var sub = {name: 'Rome', subscribed: true, stream_id: 1}; stream_data.add_sub('Rome', sub); stream_data.set_subscribers(sub, ['fred@zulip.com', 'george@zulip.com']); assert(stream_data.user_is_subscribed('Rome', 'FRED@zulip.com')); assert(stream_data.user_is_subscribed('Rome', 'fred@zulip.com')); assert(stream_data.user_is_subscribed('Rome', 'george@zulip.com')); assert(!stream_data.user_is_subscribed('Rome', 'not_fred@zulip.com')); stream_data.set_subscribers(sub, []); var email = 'brutus@zulip.com'; assert(!stream_data.user_is_subscribed('Rome', email)); // add stream_data.add_subscriber('Rome', email); assert(stream_data.user_is_subscribed('Rome', email)); // verify that adding an already-removed subscriber is a noop stream_data.add_subscriber('Rome', email); assert(stream_data.user_is_subscribed('Rome', email)); // remove stream_data.remove_subscriber('Rome', email); assert(!stream_data.user_is_subscribed('Rome', email)); // verify that removing an already-removed subscriber is a noop stream_data.remove_subscriber('Rome', email); assert(!stream_data.user_is_subscribed('Rome', email)); // Verify defensive code in set_subscribers, where the second parameter // can be undefined. stream_data.set_subscribers(sub); stream_data.add_sub('Rome', sub); stream_data.add_subscriber('Rome', email); sub.subscribed = true; assert(stream_data.user_is_subscribed('Rome', email)); // Verify that we noop and don't crash when unsubsribed. sub.subscribed = false; global.blueslip.warn = function () {}; stream_data.add_subscriber('Rome', email); assert.equal(stream_data.user_is_subscribed('Rome', email), undefined); stream_data.remove_subscriber('Rome', email); assert.equal(stream_data.user_is_subscribed('Rome', email), undefined); }());
JavaScript
0.000001
@@ -3445,37 +3445,35 @@ ding an already- -remov +add ed subscriber is
a2a40033a0d15a81d116c6dd52eefec64c9bf9c0
rename _alertdiv
src/WidgetName/widget/WidgetName.js
src/WidgetName/widget/WidgetName.js
/* WidgetName ======================== @file : WidgetName.js @version : {{version}} @author : {{author}} @date : {{date}} @copyright : {{copyright}} @license : {{license}} Documentation ======================== Describe your widget here. */ // Required module list. Remove unnecessary modules, you can always get them back from the boilerplate. define([ "dojo/_base/declare", "mxui/widget/_WidgetBase", "dijit/_TemplatedMixin", "mxui/dom", "dojo/dom", "dojo/dom-prop", "dojo/dom-geometry", "dojo/dom-class", "dojo/dom-style", "dojo/dom-construct", "dojo/_base/array", "dojo/_base/lang", "dojo/text", "dojo/html", "dojo/_base/event", "WidgetName/lib/jquery-1.11.2", "dojo/text!WidgetName/widget/template/WidgetName.html" ], function(declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, dojoProp, dojoGeometry, dojoClass, dojoStyle, dojoConstruct, dojoArray, dojoLang, dojoText, dojoHtml, dojoEvent, _jQuery, widgetTemplate) { "use strict"; var $ = _jQuery.noConflict(true); // Declare widget's prototype. return declare("WidgetName.widget.WidgetName", [ _WidgetBase, _TemplatedMixin ], { // _TemplatedMixin will create our dom node using this HTML template. templateString: widgetTemplate, // DOM elements inputNodes: null, colorSelectNode: null, colorInputNode: null, infoTextNode: null, // Parameters configured in the Modeler. mfToExecute: "", messageString: "", backgroundColor: "", // Internal variables. Non-primitives created in the prototype are shared between all widget instances. _handles: null, _contextObj: null, _alertDiv: null, // dojo.declare.constructor is called to construct the widget instance. Implement to initialize non-primitive properties. constructor: function() { this._handles = []; }, // dijit._WidgetBase.postCreate is called after constructing the widget. Implement to do extra setup work. postCreate: function() { console.log(this.id + ".postCreate"); this._updateRendering(); this._setupEvents(); }, // mxui.widget._WidgetBase.update is called when context is changed or initialized. Implement to re-render and / or fetch data. update: function(obj, callback) { console.log(this.id + ".update"); this._contextObj = obj; this._resetSubscriptions(); this._updateRendering(); callback(); }, // mxui.widget._WidgetBase.enable is called when the widget should enable editing. Implement to enable editing if widget is input widget. enable: function() {}, // mxui.widget._WidgetBase.enable is called when the widget should disable editing. Implement to disable editing if widget is input widget. disable: function() {}, // mxui.widget._WidgetBase.resize is called when the page's layout is recalculated. Implement to do sizing calculations. Prefer using CSS instead. resize: function(box) {}, // mxui.widget._WidgetBase.uninitialize is called when the widget is destroyed. Implement to do special tear-down work. uninitialize: function() { // Clean up listeners, helper objects, etc. There is no need to remove listeners added with this.connect / this.subscribe / this.own. }, // We want to stop events on a mobile device _stopBubblingEventOnMobile: function(e) { if (typeof document.ontouchstart !== "undefined") { dojoEvent.stop(e); } }, // Attach events to HTML dom elements _setupEvents: function() { this.connect(this.colorSelectNode, "change", function(e) { // Function from mendix object to set an attribute. this._contextObj.set(this.backgroundColor, this.colorSelectNode.value); }); this.connect(this.infoTextNode, "click", function(e) { // Only on mobile stop event bubbling! this._stopBubblingEventOnMobile(e); // If a microflow has been set execute the microflow on a click. if (this.mfToExecute !== "") { mx.data.action({ params: { applyto: "selection", actionname: this.mfToExecute, guids: [ this._contextObj.getGuid() ] }, callback: function(obj) { //TODO what to do when all is ok! }, error: dojoLang.hitch(this, function(error) { console.log(this.id + ": An error occurred while executing microflow: " + error.description); }) }, this); } }); }, // Rerender the interface. _updateRendering: function() { this.colorSelectNode.disabled = this.readOnly; this.colorInputNode.disabled = this.readOnly; if (this._contextObj !== null) { dojoStyle.set(this.domNode, "display", "block"); var colorValue = this._contextObj.get(this.backgroundColor); this.colorInputNode.value = colorValue; this.colorSelectNode.value = colorValue; dojoHtml.set(this.infoTextNode, this.messageString); dojoStyle.set(this.infoTextNode, "background-color", colorValue); } else { dojoStyle.set(this.domNode, "display", "none"); } // Important to clear all validations! this._clearValidations(); }, // Handle validations. _handleValidation: function(validations) { this._clearValidations(); var validation = validations[0], message = validation.getReasonByAttribute(this.backgroundColor); if (this.readOnly) { validation.removeAttribute(this.backgroundColor); } else if (message) { this._addValidation(message); validation.removeAttribute(this.backgroundColor); } }, // Clear validations. _clearValidations: function() { dojoConstruct.destroy(this._alertdiv); this._alertdiv = null; }, // Show an error message. _showError: function(message) { if (this._alertDiv !== null) { dojoHtml.set(this._alertDiv, message); return true; } this._alertDiv = dojoConstruct.create("div", { "class": "alert alert-danger", "innerHTML": message }); dojoConstruct.place(this.domNode, this._alertdiv); }, // Add a validation. _addValidation: function(message) { this._showError(message); }, // Reset subscriptions. _resetSubscriptions: function() { // Release handles on previous object, if any. if (this._handles) { this._handles.forEach(function(handle) { mx.data.unsubscribe(handle); }); this._handles = []; } // When a mendix object exists create subscribtions. if (this._contextObj) { var objectHandle = this.subscribe({ guid: this._contextObj.getGuid(), callback: dojoLang.hitch(this, function(guid) { this._updateRendering(); }) }); var attrHandle = this.subscribe({ guid: this._contextObj.getGuid(), attr: this.backgroundColor, callback: dojoLang.hitch(this, function(guid, attr, attrValue) { this._updateRendering(); }) }); var validationHandle = this.subscribe({ guid: this._contextObj.getGuid(), val: true, callback: dojoLang.hitch(this, this._handleValidation) }); this._handles = [ objectHandle, attrHandle, validationHandle ]; } } }); }); require(["WidgetName/widget/WidgetName"], function() { "use strict"; });
JavaScript
0.000301
@@ -6581,33 +6581,33 @@ troy(this._alert -d +D iv);%0A @@ -6618,17 +6618,17 @@ s._alert -d +D iv = nul @@ -7073,17 +7073,17 @@ s._alert -d +D iv);%0A
b097a60c965ef6c7cf6ac255ad90ba12f3188aff
support browser globals, who likes that these days?
attricon.js
attricon.js
/** * An miniscule Backbone view that binds an icon className to a model attribute. * @param {[options]} * model The model to bind to. * attribute The attribute of the model to map to an icon. * iconMap An object that maps the attribute value to an icon. * formRaw A function to map a raw attribute value to a icon key. */ define(function(require){ var Backbone = require('backbone'); // Default function to transform from raw value to icon key; var fromRaw = function fromRaw(value){ return value.toString(); }; var Attricon = Backbone.View.extend({ tagName: 'i', initialize: function(options){ if(! (options && options.attribute && options.iconMap && this.model)){ throw new Error('Attricon view requires a model, an attribute, and an iconMap'); } this.iconMap = options.iconMap; this.fromRaw = options.fromRaw || fromRaw; this.listenTo(this.model, 'change:' + options.attribute, function(model, value){ this.addIcon(value); }); if(this.model.has(options.attribute)){ this.addIcon(this.model.get(options.attribute)); } }, // set's the className of element to a mapped icon class. addIcon: function(value){ var val = this.fromRaw(value); var icon = (val in this.iconMap) ? this.iconMap[val] : 'icon-question'; this.el.className = icon; } }, { Status: { 'pending': 'icon-check-empty', 'in-progress': 'icon-cog icon-spin', 'succeeded': 'icon-check', 'failed': 'icon-warning-sign' }, OS: { 'linux': 'icon-linux', 'android': 'icon-android', 'apple': 'icon-apple', 'windows': 'icon-windows' } }); return Attricon; });
JavaScript
0
@@ -360,71 +360,245 @@ */%0A -define(function(require)%7B%0A var Backbone = require('b +(function (root, factory) %7B%0A if (typeof define === 'function' && define.amd) %7B%0A // AMD%0A define(%5B'backbone'%5D, factory);%0A %7D else %7B%0A // Browser globals%0A root.Attricon = factory(root.B ackbone -' ); +%0A %7D%0A%7D(this, function (Backbone) %7B %0A%0A @@ -1924,11 +1924,14 @@ tricon;%0A -%7D +%0A%7D) ); +%0A
2f56dbec388fa3cc7ae64dec9176ebf4946c6a24
Remove CR
src/SidePanel/SidePanel.js
src/SidePanel/SidePanel.js
import React from 'react/addons'; import Portal from '../Portal/Portal.js'; import SidePanelContents from './SidePanelContents.js'; /** * Wrapper for the SidePanel, to put it inside of a Portal. * The SidePanel needs its own lifecycle and therefore this wrapper is necessary */ export default class SidePanel extends React.Component { render() { return ( <Portal> <SidePanelContents {...this.props} /> </Portal> ); } }
JavaScript
0.000002
@@ -334,17 +334,16 @@ onent %7B%0A -%0A render
956dae6e2266ef5f30a3e69fe8fa89fd4f60930e
configure playlists to only show valid songs
app/routes/playlists.js
app/routes/playlists.js
"use strict" var express = require('express'); var router = express.Router(); var passport = require('passport') var credential = require('credential') var _ = require('lodash') var db = require('../db') router.get( '/getUserPlaylists', function(request, response) { if (!request.user) { response.status(401).json({error: 'unauthorized'}) return } db.query('SELECT active_playlist_id FROM "user" WHERE id = $1', [request.user.id]) .then((activePlaylistResult) => { return activePlaylistResult.rows[0].active_playlist_id }) .then((activePlaylistId) => { db.query('SELECT * FROM playlist WHERE user_id=$1', [request.user.id]) .then((result) => { let activePlaylist = _.find( result.rows, (playlist) => { return playlist.id === activePlaylistId } ); if (activePlaylist) { activePlaylist.active = true } response.json(result.rows) }) }) } ) router.get('/getPlaylist/:playlistId', (request, response) => { if (!request.user) { response.status(401).json({error: 'unauthorized'}) return } let playlistId = request.params.playlistId let playlist = null; db.query('SELECT * FROM playlist WHERE id=$1 LIMIT 1', [playlistId]) .then((playlistQueryResult) => { if (playlistQueryResult.rows[0].user_id !== request.user.id) { response.status(401).json({error: 'unauthorized'}) return } return Promise.resolve(playlistQueryResult.rows[0]) }).then((playlistResult) => { playlist = playlistResult return db.query( `SELECT song.* FROM song, playlist_has_song WHERE song.id = playlist_has_song.song_id AND playlist_has_song.playlist_id = $1`, [playlistResult.id] ) }).then((songs) => { playlist.songs = songs.rows response.json(playlist) }).catch((error) => { console.log(error) }) } ) router.get('/setActivePlaylist/:id', (request, response) => { if (!request.user) { return response.status(401).json({error: 'unauthorized'}) } let playlistId = request.params.id let userId = request.user.id db.query( 'SELECT COUNT(*) AS count FROM playlist WHERE id = $1 AND user_id=$2', [playlistId, userId] ).then((result) => { return new Promise((resolve, reject) => { if (result.rows[0].count == 1) { //count returns as a string so `==` resolve() } reject('not a playlist of logged in user') }) }).then(() => { return db.query( 'UPDATE "user" SET active_playlist_id = $1 WHERE id = $2', [playlistId, userId] ) }).then((result) => { return response.send(JSON.stringify({status: 'success' })) }).catch((error) => { console.log(error) response.status(500) }) } ) module.exports = router;
JavaScript
0.000002
@@ -1665,16 +1665,67 @@ tResult%0A + var validStatuses = %5B'valid', 'converted'%5D%0A @@ -1899,16 +1899,141 @@ _id = $1 + AND%0A song.status IN ($%7B%0A validStatuses.map((s) =%3E %7B return %22'%22 + s + %22'%22 %7D).join(',')%0A %7D) %60,%0A
e8f29df935c5bd607ff950d6ab2656ffe99ee9c0
Fix id generation for anonymous columns.
src/column-layout.js
src/column-layout.js
import { emptyIfUndefinedFormat } from '@zambezi/d3-utils' import { property, replaceArrayContents } from '@zambezi/fun' import { wrap } from 'underscore' import { updateTextIfChanged } from './update-text-if-changed' const valueByKey = {} , defaultFormat = wrap(String, emptyIfUndefinedFormat) export function columnLayout(columns) { const result = validateAndSegregateColumns(columns) columns.hasDoubleRowHeader = columns.some(visibleWithChildren) return result } function validateAndSegregateColumns(columns) { const columnsLeft = [] , columnsRight = [] , columnsFree = [] , columnIdsFound = {} , predefinedColumnId = columns.reduce(byId, {}) columns.forEach(validateAndSegregateColumn) orderColumnsByBlock() cacheColumnSubsets() return columns function validateAndSegregateColumn(column) { const locked = column.locked , children = column.children if (columnHasEmptyChildren(column)) return clearTransientChildProperties(column) completeProperties(column) if (!columnIdIsUnique(column)) return function columnHasEmptyChildren(column) { if (!children || children.length) return false console.info(`Removing column with empty children: ${column.id}`) return true } ;( locked == 'left' ? columnsLeft : locked == 'right' ? columnsRight : columnsFree ).push(column) if (children) { column.children = children.map(updateChildProperties).filter(columnIdIsUnique) } return column function updateChildProperties(d, i) { d.isChild = true d.parentColumn = column d.childIndex = i d.childTotal = children.length completeProperties(d) return d } function newId(column) { var label = column.label , k = ( column.key || (label && label.toLowerCase()) || '').replace(/\W+/g, '-') , columnKeyCount = k && predefinedColumnId[k] if (!k) return 'c-' + (++columnIdCount).toString(16).toUpperCase() if (columnKeyCount) return k + '-' + ++predefinedColumnId[k] predefinedColumnId[k] = 1 return k } function columnIdIsUnique(column) { if (columnIdsFound[column.id]) { console.error(`Repeated id for column '${column.id}', removing`) return false } columnIdsFound[column.id] = true return true } function completeProperties(column) { const key = column.key || '' let value = valueByKey[key] if (!column.id) column.id = newId(column) if (!column.format) column.format = defaultFormat if (!column.components) column.components = [ updateTextIfChanged ] if (!value) value = valueByKey[key] = property(key) column.value = value // column.hasData = rows.some(value) } } function byId(acc, column) { if (!column) return acc const id = column.id , children = column.children if (id) acc[id] = 1 if (children) children.reduce(byId, acc) return acc } function orderColumnsByBlock() { replaceArrayContents( columns , columnsLeft.concat(columnsFree).concat(columnsRight) ) } function cacheColumnSubsets() { columns.left = columnsLeft columns.right = columnsRight columns.free = columnsFree columns.leafColumns = columns.right.reduce( findLeafColumns , columns.free.reduce( findLeafColumns , columns.left.reduce( findLeafColumns , [] ) ) ) columns.onlyFreeColumns = !(columns.left.length + columns.right.length) columnsLeft.name = 'left' columnsFree.name = 'free' columnsRight.name = 'right' } } function findLeafColumns(p, c) { return p.concat(c.children || c) } function clearTransientChildProperties(column) { delete column.isChild delete column.parentColumn delete column.childIndex delete column.childTotal } function visibleWithChildren(column) { if (column.hidden) return false return column.children && column.children.some(d => !d.hidden) }
JavaScript
0
@@ -294,16 +294,42 @@ ormat)%0A%0A +let columnIdCount = 0xA %0A%0A export f @@ -1863,16 +1863,27 @@ umn.key +%0A %7C%7C (labe @@ -1936,16 +1936,17 @@ g, '-')%0A +%0A @@ -2018,17 +2018,17 @@ rn ' -c +gen -' + ( -++ colu @@ -2036,16 +2036,18 @@ nIdCount +++ ).toStri
713546f0d9fe31d6da2f2dba353ff8f3d92b096d
Allow reloading soundcloud.com
app/menu.js
app/menu.js
'use strict' const electron = require('electron') const Events = require('events') const Menu = electron.Menu const app = electron.app const shell = electron.shell const events = new Events() const menu = [ { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' } ] }, { label: 'View', submenu: [ { label: 'Toggle Full Screen', accelerator: (function() { if (process.platform == 'darwin') return 'Ctrl+Command+F' else return 'F11' })(), click: function(item, focusedWindow) { if (focusedWindow) focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } } ] }, { label: 'History', submenu: [ { label: 'Home', accelerator: 'CmdOrCtrl+Shift+H', click() { events.emit('home') } }, { label: 'Back', accelerator: 'CmdOrCtrl+Left', click() { events.emit('back') } }, { label: 'Forward', accelerator: 'CmdOrCtrl+Right', click() { events.emit('forward') } } ] }, { label: 'Controls', submenu: [ { label: 'Play/Pause', accelerator: 'Space' }, { label: 'Next', accelerator: 'Shift+Right' }, { label: 'Previous', accelerator: 'Shift+Left' } ] }, { label: 'Window', role: 'window', submenu: [ { label: 'Main Window', accelerator: 'CmdOrCtrl+1', click() { events.emit('main-window') } }, { label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize' }, { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' } ] }, { label: 'Help', role: 'help', submenu: [ { label: 'Learn More', click: function() { shell.openExternal('http://soundcleod.com') } } ] } ] if (process.env.NODE_ENV == 'development' || process.env.NODE_ENV == 'test') menu[1].submenu.push( { label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function(item, focusedWindow) { if (focusedWindow) focusedWindow.reload() } }, { label: 'Toggle Developer Tools', accelerator: (function() { if (process.platform == 'darwin') return 'Alt+Command+I' else return 'Ctrl+Shift+I' })(), click: function(item, focusedWindow) { if (focusedWindow) focusedWindow.toggleDevTools() } } ) if (process.platform == 'darwin') { const name = app.getName() menu.unshift({ label: name, submenu: [ { label: 'About ' + name, role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Alt+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit() } } ] }) // Window menu. menu[3].submenu.push( { type: 'separator' }, { label: 'Bring All to Front', role: 'front' } ) } module.exports = Menu.buildFromTemplate(menu) module.exports.events = events
JavaScript
0.000001
@@ -1294,32 +1294,231 @@ en())%0A %7D%0A + %7D,%0A %7B%0A label: 'Reload',%0A accelerator: 'CmdOrCtrl+R',%0A click: function(item, focusedWindow) %7B%0A if (focusedWindow)%0A focusedWindow.reload()%0A %7D%0A %7D%0A %5D%0A @@ -2993,191 +2993,8 @@ %7B%0A - label: 'Reload',%0A accelerator: 'CmdOrCtrl+R',%0A click: function(item, focusedWindow) %7B%0A if (focusedWindow)%0A focusedWindow.reload()%0A %7D%0A %7D,%0A %7B%0A
1e3bfe80b1a2b3e9e2abb5d5d1607c868d4de3ba
Fix new list methods
src/SimpleResourceProxy.js
src/SimpleResourceProxy.js
/* * BSD 3-Clause License * * Copyright (c) 2017, MapCreator * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import ResourceBase from './crud/base/ResourceBase'; import PaginatedResourceListing from './PaginatedResourceListing'; import {isParentOf} from './utils/reflection'; /** * Proxy for accessing resource. This will make sure that they * are properly wrapped before the promise resolves. * @protected * @todo remove ::search* in favor of an object containing function parameters */ export default class SimpleResourceProxy { /** * @param {Maps4News} api - Instance of the api * @param {ResourceBase} Target - Target to wrap * @param {?string} [altUrl=null] - Internal use, Optional alternative url for more complex routing * @param {object} seedData - Internal use, used for seeding ::new */ constructor(api, Target, altUrl = null, seedData = {}) { if (!isParentOf(ResourceBase, Target)) { throw new TypeError('Target is not a child of ResourceBase'); } if (typeof Target !== 'function') { throw new TypeError('Target must to be a class not an instance'); } if (altUrl) { this.__baseUrl = altUrl; } this._api = api; this._Target = Target; this._seedData = seedData; } get _baseUrl() { if (!this.__baseUrl) { this.__baseUrl = this.new().baseUrl; } return this.__baseUrl; } /** * Get api instance * @returns {Maps4News} - Api instance */ get api() { return this._api; } /** * Target to wrap results in * @returns {ResourceBase} - Target constructor * @constructor */ get Target() { return this._Target; } /** * The name of the target * @returns {String} - Target name * @example * api.colors.accessorName === 'Color' * api.fontFamilies.accessorName = 'Font Families' */ get accessorName() { return this.Target.name.replace(/([A-Z])/g, x => ' ' + x).trim(); } /** * Build a new isntance of the target * @param {Object<String, *>} data - Data for the object to be populated with * @returns {ResourceBase} - Resource with target data */ new(data = {}) { // Merge but don't overwrite using seed data data = Object.assign(this._seedData, data); return new this.Target(this._api, data); } /** * List target resource * @param {Number|Object} params - ParametersThe page to be requested * @param {Number} [params.page=1] - The page to be requested * @param {Number} [params.perPage=this.api.defaults.perPage] - Amount of items per page. This is silently capped by the API * @param {?Object<String, String|Array<String>>} [params.search] - Search parameters * @returns {Promise} - Resolves with {@link PaginatedResourceListing} instance and rejects with {@link ApiError} * @example * // Find layers with a name that starts with "test" and a scale_min between 1 and 10 * // See Api documentation for search query syntax * const search = { * name: '^:test', * scale_min: ['>:1', '<:10'], * }; * * api.layers.list({perPage: 10, search}); */ list(params) { Object.assign(params, this.defaultParams); return this._buildResolver(params).getPage(params.page); } /** * List target resource * @param {Number|Object} params - ParametersThe page to be requested * @param {Number} [params.page=1] - The page to be requested * @param {Number} [params.perPage=this.api.defaults.perPage] - Amount of items per page. This is silently capped by the API * @param {Boolean} [params.shareCache=this.api.defaults.shareCache] - Share cache across instances * @param {?Object<String, String|Array<String>>} [params.search] - Search parameters * @returns {PaginatedResourceWrapper} - Wrapped paginated resource * @example * // Find layers with a name that starts with "test" and a scale_min between 1 and 10 * // See Api documentation for search query syntax * const search = { * name: '^:test', * scale_min: ['>:1', '<:10'], * }; * * api.layers.list({perPage: 10, search}); */ listAndWrap(params) { Object.assign(params, this.defaultParams); const wrapped = this._buildResolver(params).wrap(params.page); wrapped.get(params.page); return wrapped; } _buildResolver(params) { const paramType = typeof params; const url = this._baseUrl; if (!['number', 'object'].includes(paramType)) { throw new TypeError(`Expected params to be of type number or object. Got "${paramType}"`); } if (paramType === 'number') { return this.newList({page: params}); } return new PaginatedResourceListing(this._api, url, this.Target, params.search, params.page, params.perPage); } get defaultParams() { const defaults = this.api.defaults; return { page: 1, perPage: defaults.perPage, shareCache: defaults.shareCache, search: {}, }; } }
JavaScript
0.004964
@@ -4605,51 +4605,54 @@ -Object.assign(params, this.defaultP +const resolver = this._buildResolver(p arams);%0A @@ -4647,16 +4647,17 @@ arams);%0A +%0A retu @@ -4663,35 +4663,16 @@ urn -this._buildResolver(params) +resolver .get @@ -4676,22 +4676,24 @@ getPage( -params +resolver .page);%0A @@ -5585,51 +5585,54 @@ -Object.assign(params, this.defaultP +const resolver = this._buildResolver(p arams);%0A %0A @@ -5623,25 +5623,24 @@ er(params);%0A -%0A const wr @@ -5651,47 +5651,30 @@ d = -this._buildResolver(params).wrap(params +resolver.wrap(resolver .pag @@ -5694,22 +5694,24 @@ ped.get( -params +resolver .page);%0A @@ -6044,12 +6044,9 @@ his. -newL +l ist(
9e5fe54d6d4925e4c46b6b40e442c9ba88b063c0
Fix sorting
comments.js
comments.js
var append = require('append'), sha1 = require('sha1'), md5 = require('MD5'), querystring = require('querystring'), MongoDB = require('mongodb').Db, MongoServer = require('mongodb').Server; var INDEX = 'res'; // which field to index // constructor var Comments = module.exports = function Comments(opt) { // Default options var defaultOpt = { host: 'localhost', port: 27017, name: 'website', collection: 'comments' }; this.opt = append(defaultOpt, opt); }; // method: connect Comments.prototype.connect = function connect(connected) { var inst = this, opt = this.opt; // Server connection inst.server = new MongoServer(opt.host, opt.port, { auto_reconnect: true }); // DB connection var dbConnector = new MongoDB(opt.name, inst.server); try { dbConnector.open(function(err, db) { if (err) throw err; // DB connection inst.db = db; db.collection(opt.collection, function(err, col) { if (err) throw err; // ref to collection inst.collection = col; // ensure index col.ensureIndex(INDEX, function(err, index) { if (err) throw err; // callback connected(null, col); }); }); }); } catch(err) { connected(err); } }; // method: getCollection Comments.prototype.getCollection = function getCollection(done) { // If connection hasn't already been established if (typeof this.collection == 'undefined') // try to connect try { this.connect(done); } catch(err) { done(err); } // otherwise simply use existing collection else done(null, this.collection); }; // method: saveComment Comments.prototype.saveComment = function saveComment(res, comment, saved) { // resource comment.res = res; // email address and hash var email = comment.email; comment.email = { address: email, hash: md5(email) }; // edited comment.edited = new Date(); // hash the comment comment.hash = sha1(JSON.stringify(comment)); try { // get collection and save comment this.getCollection(function(err, col) { col.save(comment, saved); }); } catch(err) { saved(err); } }; // method: getComments Comments.prototype.getComments = function getComments(res, props, opt, received) { var defaultOpt = { sort: 'created' }; var defaultProps = { _id: true, author: true, 'email.hash': true, website: true, edited: true, message: true }; // set properties and options if (arguments.length == 2) { received = props; props = defaultProps; opt = defaultOpt; } else if (arguments.length == 3) { received = opt; opt = defaultOpt; props = append(defaultProps, props); } else { opt = append(defaultOpt, opt); props = append(defaultProps, props); } var query = {}; if (res !== null) query.res = res; try { // get collection and find comments this.getCollection(function(err, col) { col.find(query, props, opt, received); }); } catch(err) { received(err); } }; // method: count Comments.prototype.count = function count(res, counted) { try { this.getComments(res, function(err, results) { results.count(counted); }); } catch(err) { counted(err); } }; // method: close Comments.prototype.close = function(done) { if (this.db) this.db.close(done); }; // method: getCommentsJSON Comments.prototype.getCommentsJSON = function getCommentsJSON(res, resp, received) { // if resource is not defined if (typeof res == 'undefined') { resp.writeHead(404); resp.end(); } else { // request comments for this resource from the db this.getComments(res, function receiveComments(err, results) { if (err) { resp.writeHead(404); resp.end(); received(err); } else { // count the comments results.count(function count(err, count) { var i = 0; if (err) { resp.writeHead(404); resp.end(); received(err); } else { resp.writeHead(200, { 'Content-Type': 'application/json' }); // start JSON array output resp.write('['); // for each comment in the result set results.each(function (err, comment) { if (err) received(err); if (comment) { resp.write(JSON.stringify(comment)); // seperate comments by a comma if (++i < count) resp.write(','); } else { // end the output when there are no more comments resp.end(']'); received(null); } }); } }); } }); } }; // method: parseCommentPOST Comments.prototype.parseCommentPOST = function parseCommentPOST(res, req, parsed) { var data = ''; // add chunks to data req.on('data', function(chunk) { data += chunk; }); // when data is complete req.on('end', function() { try { parsed(null, querystring.parse(data)); } catch (err) { parsed(err); } }); // when connection is closed, before data is complete req.on('close', function(err) { parsed(err); }); }; // method: setCommentJSON Comments.prototype.setCommentJSON = function setCommentJSON(res, comment, resp, saved) { if (typeof res == 'undefined') { resp.writeHead(404); resp.end(); saved(new Error('Invalid argument. `res` must not be undefined.')); } else { if (comment === false) { resp.writeHead(412); // precondition failed resp.end(); saved(new Error('Precondition failed.')); } else { // save comment this.saveComment(res, comment, function(err, comment) { if (err) { resp.writeHead(500); resp.end(); saved(err); } else { // everything ok resp.writeHead(200); resp.end(); saved(null); } }); } } };
JavaScript
0.000024
@@ -2372,12 +2372,11 @@ t: ' -crea +edi ted'
1623ae966b9823088e65870104d9e37d714b23c0
Standardize on “//“ for all JS comments
src/reactize.js
src/reactize.js
var Turbolinks = require("exports?this.Turbolinks!turbolinks"); /* Disable the Turbolinks page cache to prevent Tlinks from storing versions of * pages with `react-id` attributes in them. When popping off the history, the * `react-id` attributes cause React to treat the old page like a pre-rendered * page and breaks diffing. */ Turbolinks.pagesCached(0); var HTMLtoJSX = require("htmltojsx"); var JSXTransformer = require("react-tools"); var React = require("react"); var Reactize = { version: REACTIZE_VERSION }; var converter = new HTMLtoJSX({createClass: false}); Reactize.reactize = function(element) { var code = JSXTransformer.transform(converter.convert(element.innerHTML)); return eval(code); }; Reactize.applyDiff = function(replacementElement, targetElement) { var bod = Reactize.reactize(replacementElement); React.render(bod, targetElement); }; function applyBodyDiff() { Reactize.applyDiff(document.body, document.body); global.removeEventListener("load", applyBodyDiff); } global.addEventListener("load", applyBodyDiff); // Turbolinks calls `replaceChild` on the document element when an update should // occur. Monkeypatch the method so Turbolinks can be used without modification. global.document.documentElement.replaceChild = Reactize.applyDiff; module.exports = global.Reactize = Reactize;
JavaScript
0.000001
@@ -59,17 +59,17 @@ ks%22);%0A%0A/ -* +/ Disable @@ -138,18 +138,18 @@ ions of%0A - * +// pages w @@ -217,18 +217,18 @@ ry, the%0A - * +// %60react- @@ -296,18 +296,18 @@ endered%0A - * +// page an @@ -328,12 +328,8 @@ ng.%0A - */%0A Turb
7c0805858c9ebc1d1d3f653e08d66460c07129a3
fix date comparison in github util
lib/sites/project/github.js
lib/sites/project/github.js
const request = require('request') const FeedParser = require('feedparser') class Github { constructor() { this._projectUrlRegex = /^(?:https:\/\/|http:\/\/)?github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$/ } isMatchUrlPattern(url) { if (url.length > 200) { return false } return this._projectUrlRegex.test(url) } getNewVersionInfoPromise(check_date, project) { let req = request(`https://github.com/${project.project_author}/${project.project_name}/releases.atom`) let feedparser = new FeedParser({addmeta: false}) return new Promise((resolve, reject) => { let info = [] req.on('error', function (error) { reject(error) }) req.on('response', function (res) { var stream = this // `this` is `req`, which is a stream if (res.statusCode !== 200) { this.emit('error', new Error('Bad status code')) } else { stream.pipe(feedparser) } }) feedparser.on('error', function (error) { reject(error) }) feedparser.on('readable', function () { let item let stream = this // `this` is `feedparser`, which is a stream while (item = stream.read()) { if (item.date > check_date) { info.push({ version: item.title, date: item.date }) } } }) feedparser.on('end', function () { resolve(info) }) }) } } module.exports = Github
JavaScript
0.000131
@@ -1442,21 +1442,61 @@ -if (item.date +let t = new Date(item.date)%0A if (t %3E c
125664de7633a3added289019ff9d38e5f5c4872
Convert `loadUser()` and `fetchUser()` to async/await
app/services/session.js
app/services/session.js
import Service, { inject as service } from '@ember/service'; import window from 'ember-window-mock'; import ajax from '../utils/ajax'; export default class SessionService extends Service { @service store; @service router; savedTransition = null; abortedTransition = null; isLoggedIn = false; currentUser = null; currentUserDetected = false; ownedCrates = null; constructor() { super(...arguments); let isLoggedIn; try { isLoggedIn = window.localStorage.getItem('isLoggedIn') === '1'; } catch (e) { isLoggedIn = false; } this.set('isLoggedIn', isLoggedIn); this.set('currentUser', null); } loginUser(user) { this.set('isLoggedIn', true); this.set('currentUser', user); try { window.localStorage.setItem('isLoggedIn', '1'); } catch (e) { // ignore error } } logoutUser() { this.set('savedTransition', null); this.set('abortedTransition', null); this.set('isLoggedIn', null); this.set('currentUser', null); try { window.localStorage.removeItem('isLoggedIn'); } catch (e) { // ignore error } } loadUser() { if (this.isLoggedIn && !this.currentUser) { this.fetchUser() .catch(() => this.logoutUser()) .finally(() => { this.set('currentUserDetected', true); let transition = this.abortedTransition; if (transition) { transition.retry(); this.set('abortedTransition', null); } }); } else { this.set('currentUserDetected', true); } } fetchUser() { return ajax('/api/v1/me').then(response => { this.set('currentUser', this.store.push(this.store.normalize('user', response.user))); this.set( 'ownedCrates', response.owned_crates.map(c => this.store.push(this.store.normalize('owned-crate', c))), ); }); } checkCurrentUser(transition, beforeRedirect) { if (this.currentUser) { return; } // The current user is loaded asynchronously, so if we haven't actually // loaded the current user yet then we need to wait for it to be loaded. // Once we've done that we can retry the transition and start the whole // process over again! if (!this.currentUserDetected) { transition.abort(); this.set('abortedTransition', transition); } else { this.set('savedTransition', transition); if (beforeRedirect) { beforeRedirect(); } return this.router.transitionTo('index'); } } }
JavaScript
0.999993
@@ -1134,16 +1134,22 @@ %0A %7D%0A%0A +async loadUser @@ -1203,24 +1203,44 @@ er) %7B%0A +try %7B%0A await this.fetchUs @@ -1247,29 +1247,41 @@ er() +; %0A +%7D - . catch -(() =%3E + (error) %7B%0A thi @@ -1298,37 +1298,28 @@ er() -) +; %0A +%7D - . finally -(() =%3E %7B%0A - @@ -1369,18 +1369,16 @@ - let tran @@ -1414,26 +1414,24 @@ on;%0A - if (transiti @@ -1432,26 +1432,24 @@ ansition) %7B%0A - tr @@ -1472,26 +1472,24 @@ ;%0A - this.set('ab @@ -1521,26 +1521,24 @@ - %7D%0A %7D);%0A @@ -1529,21 +1529,17 @@ %7D%0A - %7D); +%7D %0A %7D e @@ -1602,16 +1602,22 @@ %0A %7D%0A%0A +async fetchUse @@ -1626,22 +1626,36 @@ ) %7B%0A -return +let response = await ajax('/ @@ -1669,30 +1669,10 @@ me') -.then(response =%3E %7B%0A +;%0A @@ -1758,26 +1758,24 @@ ser)));%0A - this.set(%0A @@ -1772,18 +1772,16 @@ is.set(%0A - 'o @@ -1793,18 +1793,16 @@ rates',%0A - re @@ -1896,18 +1896,8 @@ - );%0A %7D );%0A
b5815ffcb753d6e7972b8a26fa8681f570625f23
Update PhetioGroup documentation
js/PhetioGroup.js
js/PhetioGroup.js
// Copyright 2019-2020, University of Colorado Boulder /** * Provides a placeholder in the static API for where dynamic elements may be created. Checks that elements of the group * match the approved schema. * * @author Michael Kauzmann (PhET Interactive Simulations) * @author Sam Reid (PhET Interactive Simulations) * @author Chris Klusendorf (PhET Interactive Simulations) */ import Emitter from '../../axon/js/Emitter.js'; import arrayRemove from '../../phet-core/js/arrayRemove.js'; import merge from '../../phet-core/js/merge.js'; import PhetioDynamicElementContainer from './PhetioDynamicElementContainer.js'; import Tandem from './Tandem.js'; import tandemNamespace from './tandemNamespace.js'; // constants const DEFAULT_CONTAINER_SUFFIX = 'Group'; class PhetioGroup extends PhetioDynamicElementContainer { /** * @param {function} createElement - function that creates a dynamic element for the group. * @param {Array.<*>|function.<[],Array.<*>>} defaultArguments arguments passed to create during API harvest * @param {Object} [options] - describe the Group itself */ constructor( createElement, defaultArguments, options ) { options = merge( { tandem: Tandem.REQUIRED, // {string} The group's tandem name must have this suffix, and the base tandem name for elements of // the group will consist of the group's tandem name with this suffix stripped off. containerSuffix: DEFAULT_CONTAINER_SUFFIX }, options ); super( createElement, defaultArguments, options ); // @public (read-only) this.array = []; // @public (read-only) // TODO: why validate with stub true? Also is it worth using TinyEmitter? https://github.com/phetsims/tandem/issues/170 this.elementCreatedEmitter = new Emitter( { parameters: [ { isValidValue: _.stubTrue } ] } ); this.elementDisposedEmitter = new Emitter( { parameters: [ { isValidValue: _.stubTrue } ] } ); // @public (only for PhetioGroupIO) - for generating indices from a pool this.groupElementIndex = 0; // Emit to the data stream on element creation/disposal this.elementCreatedEmitter.addListener( element => this.createdEventListener( element ) ); this.elementDisposedEmitter.addListener( element => this.disposedEventListener( element ) ); } /** * @public */ dispose() { assert && assert( false, 'PhetioGroup not intended for disposal' ); } /** * Remove an element from this Group, unregistering it from PhET-iO and disposing it. * @param element * @public */ disposeElement( element ) { arrayRemove( this.array, element ); this.elementDisposedEmitter.emit( element ); element.dispose(); } /** * Returns the element at the specified index * @param {number} index * @returns {Object} */ get( index ) { return this.array[ index ]; } /** * Get number of Group elements * @returns {number} * @public */ get length() { return this.array.length; } /** * Returns an array with elements that pass the filter predicate. * @param {function(PhetioObject)} predicate * @returns {Object[]} * @public */ filter( predicate ) { return this.array.filter( predicate ); } /** * Returns true if the group contains the specified object. * @param {Object} element * @returns {boolean} * @public */ contains( element ) { return this.array.indexOf( element ) >= 0; } /** * Runs the function on each element of the group. * @param {function(PhetioObject)} action - a function with a single parameter: the current element * @public */ forEach( action ) { this.array.forEach( action ); } /** * Returns an array with every element mapped to a new one. * @param {function(PhetioObject)} f * @returns {Object[]} * @public */ map( f ) { return this.array.map( f ); } /** * remove and dispose all registered group elements * @public */ clear() { while ( this.array.length > 0 ) { this.disposeElement( this.array[ this.array.length - 1 ] ); } this.groupElementIndex = 0; } /** * When creating a view element that corresponds to a specific model element, we match the tandem name index suffix * so that electron_0 corresponds to electronNode_0 and so on. * @param {PhetioObject} phetioObject * @param {...*} argsForCreateFunction - args to be passed to the create function, specified there are in the IO Type `stateToArgsForConstructor` method * @returns {PhetioObject} * @public */ createCorrespondingGroupElement( phetioObject, ...argsForCreateFunction ) { const index = window.phetio.PhetioIDUtils.getGroupElementIndex( phetioObject.tandem.name ); // If the specified index overlapped with the next available index, bump it up so there is no collision on the // next createNextElement if ( this.groupElementIndex === index ) { this.groupElementIndex++; } return this.createIndexedElement( index, argsForCreateFunction ); } /** * Creates the next group element. * @param {...*} argsForCreateFunction - args to be passed to the create function, specified there are in the IO Type `stateToArgsForConstructor` method * @returns {PhetioObject} * @public */ createNextElement( ...argsForCreateFunction ) { return this.createIndexedElement( this.groupElementIndex++, argsForCreateFunction ); } /** * Primarily for internal use, clients should usually use createNextElement. * @param {number} index - the number of the individual element * @param {Array.<*>} argsForCreateFunction * @returns {Object} * @public (PhetioGroupIO) */ createIndexedElement( index, argsForCreateFunction ) { const componentName = this.phetioDynamicElementName + window.phetio.PhetioIDUtils.GROUP_SEPARATOR + index; const groupElement = this.createDynamicElement( componentName, argsForCreateFunction, this.phetioType.parameterTypes[ 0 ] ); this.array.push( groupElement ); this.elementCreatedEmitter.emit( groupElement ); return groupElement; } } tandemNamespace.register( 'PhetioGroup', PhetioGroup ); export default PhetioGroup;
JavaScript
0
@@ -208,16 +208,459 @@ ema.%0A *%0A + * In general when creating an element, any extra wiring or listeners should not be added. These side effects are a code%0A * smell in the %60createElement%60 parameter. Instead attach a listener for when elements are created, and wire up listeners%0A * there. Further documentation about using PhetioGroup can be found at%0A * https://github.com/phetsims/phet-io/blob/master/doc/phet-io-instrumentation-guide.md#dynamically-created-phet-io-elements%0A *%0A * @auth
c8ebf763c012c6b4f5a94eb8693e6045c9c8d760
Version 1.5
app/util.js
app/util.js
module.exports = { convertToLocal: function(time) { var newTime = new Date(time); var originalTime = new Date(time); console.log(newTime.getTimezoneOffset()); newTime.setHours(newTime.getHours() + (newTime.getTimezoneOffset() / 60) + 4); return newTime; } };
JavaScript
0.000001
@@ -235,17 +235,17 @@ ) / 60) -+ +- 4);%0A%09%09r
9532b56ac98a3de57a8dcacfb0b847bb0ac8049d
Fix responder candidates missing
js/turn.responder.js
js/turn.responder.js
'use strict'; // https://codelabs.developers.google.com/codelabs/webrtc-web/#6 var api = ""; $("#start").click(function(){ var napi = document.getElementById("api").value; if (napi != "/") { api = "http://" + napi; } new Promise(function(resolve, reject){ navigator.webkitGetUserMedia({ video:true,audio:true },function(stream){ resolve(stream); }, function(error){ reject(error); }); }).then(function(stream){ var lv = document.getElementById("local"); lv.src = window.URL.createObjectURL(stream); console.log("[navigator.webkitGetUserMedia] lv.src= " + lv.src); // Use a peer connection to share stream to responder. var conn = new window.webkitRTCPeerConnection({iceServers:[{urls:["turn:stun.ossrs.net"], username:"guest", credential:"12345678"}]}); conn.addStream(stream); console.log("[conn.addStream] add stream to peer connection"); return conn; }).then(function(conn){ // Render the remote initiator stream. conn.onaddstream = function(e) { var rv = document.getElementById("remote"); rv.src = window.URL.createObjectURL(e.stream); console.log("[conn.onaddstream] rv.src=remoteStream " + rv.src); }; callInitiator(conn, api); }); }); function callInitiator(conn, api) { Promise.all([new Promise(function(resolve, reject){ // Request the candidates of initiator. var requestCandidates = function() { $.ajax({ type:"GET", async:true, url:api+"/api/webrtc/icandidates", contentType:"application/json", success:function(data){ data = JSON.parse(data) || []; // Wait util the rcandidates are completed, we should got 2 candidates. if (data.length != 2) { setTimeout(requestCandidates, 1000); return; } resolve(data); }, error:function(xhr,err){ reject(err); } }); }; requestCandidates(); }), new Promise(function(resolve, reject){ // Query the offer of initiator from signaling server. $.ajax({ type:"GET", async:true, url:api+"/api/webrtc/offer", contentType:"application/json", success:function(data){ var offer = unescapeOffer(JSON.parse(JSON.parse(data)[0])); resolve(offer); }, error: function(xhr, err) { reject(err); } }); })]).then(function([candidates,offer]){ // Transmit the responder candidates to signaling server. conn.onicecandidate = function(e) { if (!e.candidate) { return; } if (e.candidate.candidate.indexOf("relay") == -1) { console.log("[conn.onicecandidate] ignore " + e.candidate.candidate); return; } console.log("[conn.onicecandidate] " + e.candidate.candidate); console.log(e.candidate); var data = JSON.stringify(escapeCandicate(e.candidate)); $.ajax({type:"POST", async:true, url:api+"/api/webrtc/rcandidates", contentType:"application/json", data:data}); }; // once got the peer offer(SDP), we can generate our answer(SDP). conn.setRemoteDescription(offer); // trigger conn.onaddstream console.log("[onRemoteGotOffer] Got offer " + offer.sdp.length + "B sdp as bellow:"); console.log(offer); console.log(offer.sdp); // Since the 'remote' side has no media stream we need // to pass in the right constraints in order for it to // accept the incoming offer of audio and video. conn.createAnswer(function(answer){ // For chrome new API, we can delay set the TURN. //conn.setConfiguration({iceServers:[{urls:["turn:stun.ossrs.net"], username:"guest", credential:"12345678"}]}); conn.setLocalDescription(answer); // trigger conn.onicecandidate(). console.log("[conn.createAnswer] answer " + answer.sdp.length + "B sdp as bellow:"); console.log(answer); console.log(answer.sdp); var data = JSON.stringify(escapeOffer(answer)); $.ajax({type:"POST", async:true, url:api+"/api/webrtc/answer", contentType:"application/json", data:data}); // before addIceCandidate, we must setRemoteDescription for (var i = 0; i < candidates.length; i++) { var candidate = unescapeCandicate(JSON.parse(candidates[i])); conn.addIceCandidate(new window.RTCIceCandidate(candidate)); console.log("[requestCandidates] Got initiator candidate " + JSON.stringify(candidate)); } }, function(error){ console.log(error); }); }); } function escapeOffer(offer) { return {type:offer.type, sdp:escape(offer.sdp)}; } function escapeCandicate(candidate) { return {sdpMid:candidate.sdpMid, sdpMLineIndex:candidate.sdpMLineIndex, candidate:escape(candidate.candidate)}; } function unescapeOffer(offer) { return {type:offer.type, sdp:unescape(offer.sdp)}; } function unescapeCandicate(candidate) { return {sdpMid:candidate.sdpMid, sdpMLineIndex:candidate.sdpMLineIndex, candidate:unescape(candidate.candidate)}; }
JavaScript
0.000002
@@ -2514,53 +2514,146 @@ r = -unescapeOffer(JSON.parse(JSON.parse(data)%5B0%5D) +JSON.parse(data);%0A offer = offer%5B0%5D;%0A offer = JSON.parse(offer);%0A offer = unescapeOffer(offer );%0A
70827132d03cf88d08401a7f85a950abfdd529fd
fix minor typo
src/SimpleResourceProxy.js
src/SimpleResourceProxy.js
/* * BSD 3-Clause License * * Copyright (c) 2017, MapCreator * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import ResourceBase from './crud/base/ResourceBase'; import PaginatedResourceListing from './PaginatedResourceListing'; import {isParentOf} from './utils/reflection'; /** * Proxy for accessing resource. This will make sure that they * are properly wrapped before the promise resolves. * @protected * @todo remove ::search* in favor of an object containing function parameters */ export default class SimpleResourceProxy { /** * @param {Maps4News} api - Instance of the api * @param {ResourceBase} Target - Target to wrap * @param {?string} [altUrl=null] - Internal use, Optional alternative url for more complex routing * @param {object} seedData - Internal use, used for seeding ::new */ constructor(api, Target, altUrl = null, seedData = {}) { if (!isParentOf(ResourceBase, Target)) { throw new TypeError('Target is not a child of ResourceBase'); } if (typeof Target !== 'function') { throw new TypeError('Target must to be a class not an instance'); } if (altUrl) { this.__baseUrl = altUrl; } this._api = api; this._Target = Target; this._seedData = seedData; } get _baseUrl() { if (!this.__baseUrl) { this.__baseUrl = this.new().baseUrl; } return this.__baseUrl; } /** * Get api instance * @returns {Maps4News} - Api instance */ get api() { return this._api; } /** * Target to wrap results in * @returns {ResourceBase} - Target constructor * @constructor */ get Target() { return this._Target; } /** * The name of the target * @returns {String} - Target name * @example * api.colors.accessorName === 'Color' * api.fontFamilies.accessorName = 'Font Families' */ get accessorName() { return this.Target.name.replace(/([A-Z])/g, x => ' ' + x).trim(); } /** * Build a new isntance of the target * @param {Object<String, *>} data - Data for the object to be populated with * @returns {ResourceBase} - Resource with target data */ new(data = {}) { // Merge but don't overwrite using seed data data = Object.assign(this._seedData, data); return new this.Target(this._api, data); } /** * List target resource * @param {Number|Object} params - ParametersThe page to be requested * @param {Number} [params.page=1] - The page to be requested * @param {Number} [params.perPage=this.api.defaults.perPage] - Amount of items per page. This is silently capped by the API * @param {?Object<String, String|Array<String>>} [params.search] - Search parameters * @returns {Promise} - Resolves with {@link PaginatedResourceListing} instance and rejects with {@link ApiError} * @example * // Find layers with a name that starts with "test" and a scale_min between 1 and 10 * // See Api documentation for search query syntax * const search = { * name: '^:test', * scale_min: ['>:1', '<:10'], * }; * * api.layers.list({perPage: 10, search}); */ list(params) { const resolver = this._buildResolver(params); return resolver.getPage(resolver.page); } /** * List target resource * @param {Number|Object} params - ParametersThe page to be requested * @param {Number} [params.page=1] - The page to be requested * @param {Number} [params.perPage=this.api.defaults.perPage] - Amount of items per page. This is silently capped by the API * @param {Boolean} [params.shareCache=this.api.defaults.shareCache] - Share cache across instances * @param {?Object<String, String|Array<String>>} [params.search] - Search parameters * @returns {PaginatedResourceWrapper} - Wrapped paginated resource * @example * // Find layers with a name that starts with "test" and a scale_min between 1 and 10 * // See Api documentation for search query syntax * const search = { * name: '^:test', * scale_min: ['>:1', '<:10'], * }; * * api.layers.list({perPage: 10, search}); */ listAndWrap(params) { const resolver = this._buildResolver(params); const wrapped = resolver.wrap(resolver.page); wrapped.get(resolver.page); return wrapped; } _buildResolver(params) { const paramType = typeof params; const url = this._baseUrl; if (!['number', 'object'].includes(paramType)) { throw new TypeError(`Expected params to be of type number or object. Got "${paramType}"`); } if (paramType === 'number') { return this._buildResolver({page: params}); } return new PaginatedResourceListing(this._api, url, this.Target, params.search, params.page, params.perPage); } get defaultParams() { const defaults = this.api.defaults; return { page: 1, perPage: defaults.perPage, shareCache: defaults.shareCache, search: {}, }; } }
JavaScript
0.999596
@@ -5514,32 +5514,39 @@ api.layers.list +andWrap (%7BperPage: 10, s @@ -6201,24 +6201,162 @@ Page);%0A %7D%0A%0A + /**%0A * Get the defaults parameters.%0A * @returns %7B%7Bpage: number, perPage: number, shareCache: boolean, search: %7B%7D%7D%7D - Defaults%0A */%0A get defaul
3633e04fcdc65ad8d15f47972c920c29d376362f
Refactor tests for `#opensInNewTab`
spec/javascripts/merge_request_tabs_spec.js
spec/javascripts/merge_request_tabs_spec.js
/* eslint-disable no-var, comma-dangle, object-shorthand */ require('~/merge_request_tabs'); require('~/breakpoints'); require('~/lib/utils/common_utils'); require('vendor/jquery.scrollTo'); (function () { // TODO: remove this hack! // PhantomJS causes spyOn to panic because replaceState isn't "writable" var phantomjs; try { phantomjs = !Object.getOwnPropertyDescriptor(window.history, 'replaceState').writable; } catch (err) { phantomjs = false; } describe('MergeRequestTabs', function () { var stubLocation = {}; var setLocation = function (stubs) { var defaults = { pathname: '', search: '', hash: '' }; $.extend(stubLocation, defaults, stubs || {}); }; preloadFixtures('static/merge_request_tabs.html.raw'); beforeEach(function () { this.class = new gl.MergeRequestTabs({ stubLocation: stubLocation }); setLocation(); if (!phantomjs) { this.spies = { history: spyOn(window.history, 'replaceState').and.callFake(function () {}) }; } }); describe('#activateTab', function () { beforeEach(function () { spyOn($, 'ajax').and.callFake(function () {}); loadFixtures('static/merge_request_tabs.html.raw'); this.subject = this.class.activateTab; }); it('shows the first tab when action is show', function () { this.subject('show'); expect($('#notes')).toHaveClass('active'); }); it('shows the notes tab when action is notes', function () { this.subject('notes'); expect($('#notes')).toHaveClass('active'); }); it('shows the commits tab when action is commits', function () { this.subject('commits'); expect($('#commits')).toHaveClass('active'); }); it('shows the diffs tab when action is diffs', function () { this.subject('diffs'); expect($('#diffs')).toHaveClass('active'); }); }); describe('#opensInNewTab', function () { it('opens page tab in a new browser tab with Ctrl+Click - Windows/Linux', function () { const commitsLink = '.commits-tab li a'; const tabUrl = $(commitsLink).attr('href'); spyOn($.fn, 'attr').and.returnValue(tabUrl); spyOn(window, 'open').and.callFake(function (url, name) { expect(url).toEqual(tabUrl); expect(name).toEqual('_blank'); }); this.class.clickTab({ metaKey: false, ctrlKey: true, which: 1, stopImmediatePropagation: function () {} }); }); it('opens page tab in a new browser tab with Cmd+Click - Mac', function () { const commitsLink = '.commits-tab li a'; const tabUrl = $(commitsLink).attr('href'); spyOn($.fn, 'attr').and.returnValue(tabUrl); spyOn(window, 'open').and.callFake(function (url, target) { expect(url).toEqual(tabUrl); expect(target).toEqual('_blank'); }); this.class.clickTab({ metaKey: true, ctrlKey: false, which: 1, stopImmediatePropagation: function () {} }); }); it('opens page tab in a new browser tab with Middle-click - Mac/PC', function () { const commitsLink = '.commits-tab li a'; const tabUrl = $(commitsLink).attr('href'); spyOn($.fn, 'attr').and.returnValue(tabUrl); spyOn(window, 'open').and.callFake(function (url, target) { expect(url).toEqual(tabUrl); expect(target).toEqual('_blank'); }); this.class.clickTab({ metaKey: false, ctrlKey: false, which: 2, stopImmediatePropagation: function () {} }); }); }); describe('#setCurrentAction', function () { beforeEach(function () { spyOn($, 'ajax').and.callFake(function () {}); this.subject = this.class.setCurrentAction; }); it('changes from commits', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/commits' }); expect(this.subject('notes')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('diffs')).toBe('/foo/bar/merge_requests/1/diffs'); }); it('changes from diffs', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs' }); expect(this.subject('notes')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('changes from diffs.html', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs.html' }); expect(this.subject('notes')).toBe('/foo/bar/merge_requests/1'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('changes from notes', function () { setLocation({ pathname: '/foo/bar/merge_requests/1' }); expect(this.subject('diffs')).toBe('/foo/bar/merge_requests/1/diffs'); expect(this.subject('commits')).toBe('/foo/bar/merge_requests/1/commits'); }); it('includes search parameters and hash string', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/diffs', search: '?view=parallel', hash: '#L15-35' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1?view=parallel#L15-35'); }); it('replaces the current history state', function () { var newState; setLocation({ pathname: '/foo/bar/merge_requests/1' }); newState = this.subject('commits'); if (!phantomjs) { expect(this.spies.history).toHaveBeenCalledWith({ url: newState }, document.title, newState); } }); it('treats "show" like "notes"', function () { setLocation({ pathname: '/foo/bar/merge_requests/1/commits' }); expect(this.subject('show')).toBe('/foo/bar/merge_requests/1'); }); }); describe('#loadDiff', function () { it('requires an absolute pathname', function () { spyOn($, 'ajax').and.callFake(function (options) { expect(options.url).toEqual('/foo/bar/merge_requests/1/diffs.json'); }); this.class.loadDiff('/foo/bar/merge_requests/1/diffs'); }); }); }); }).call(this);
JavaScript
0
@@ -2030,82 +2030,19 @@ -it('opens page tab in a new browser tab with Ctrl+Click - Windows/Linux', +beforeEach( func @@ -2357,32 +2357,135 @@ ');%0A %7D);%0A + %7D);%0A it('opens page tab in a new browser tab with Ctrl+Click - Windows/Linux', function () %7B %0A this.cl @@ -2738,900 +2738,262 @@ -const commitsLink = '.commits-tab li a';%0A const tabUrl = $(commitsLink).attr('href');%0A%0A spyOn($.fn, 'attr').and.returnValue(tabUrl);%0A spyOn(window, 'open').and.callFake(function (url, target) %7B%0A expect(url).toEqual(tabUrl);%0A expect(target).toEqual('_blank');%0A %7D);%0A%0A this.class.clickTab(%7B%0A metaKey: true,%0A ctrlKey: false,%0A which: 1,%0A stopImmediatePropagation: function () %7B%7D%0A %7D);%0A %7D);%0A it('opens page tab in a new browser tab with Middle-click - Mac/PC', function () %7B%0A const commitsLink = '.commits-tab li a';%0A const tabUrl = $(commitsLink).attr('href');%0A%0A spyOn($.fn, 'attr').and.returnValue(tabUrl);%0A spyOn(window, 'open').and.callFake(function (url, target) %7B%0A expect(url).toEqual(tabUrl);%0A expect(target).toEqual('_blank');%0A %7D);%0A +this.class.clickTab(%7B%0A metaKey: true,%0A ctrlKey: false,%0A which: 1,%0A stopImmediatePropagation: function () %7B%7D%0A %7D);%0A %7D);%0A it('opens page tab in a new browser tab with Middle-click - Mac/PC', function () %7B %0A
e057ba9d78c763ce0a1396af7cb9db285c51daee
add billing details
models/user.js
models/user.js
var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var crypto = require('crypto'); var Schema = mongoose.Schema; var Role = require('./role.js'); var UserSchema = Schema({ username: { type: String, index: true }, password: { type: String }, fname: { type: String }, lname: { type: String }, email: { type: String }, role: [{type: Schema.Types.ObjectId, ref:Role }] }); var User = module.exports = mongoose.model('User', UserSchema); module.exports.createUser = function(newUser,callback){ bcrypt.genSalt(10,function(err,salt){ if(err) throw err; bcrypt.hash(newUser.password,salt,function(err,hash){ newUser.password = hash; newUser.save(callback); }); }); }; module.exports.comparePassword = function(candidatePassword, hash, callback){ bcrypt.compare(candidatePassword, hash, callback); }; module.exports.getUserByUsername = function(username, callback){ User.findOne(username,callback); }; module.exports.getUserById = function(id,callback){ User.findById(id,callback); };
JavaScript
0
@@ -368,24 +368,218 @@ : String %7D,%0A + companyname: %7Btype: String%7D,%0A country: %7Btype:String%7D,%0A address: %7Btype:String%7D,%0A town: %7Btype:String%7D,%0A county: %7Btype:String%7D,%0A postalcode: %7Btype: Number%7D,%0A role: @@ -1261,21 +1261,20 @@ Id(id,callback);%0A%7D;%0A -%0A
adc5362e53135ea031b7933a8bf505076db429ca
Remove layout-auto-guessing
lib/env.js
lib/env.js
'use strict'; /** * lib **/ /*global nodeca*/ // 3rd-party var Puncher = require('puncher'); //////////////////////////////////////////////////////////////////////////////// var tzOffset = (new Date).getTimezoneOffset(); //////////////////////////////////////////////////////////////////////////////// /** * lib.env(options) -> Object * - options (Object): Environment options. * * Create new request environment object. * * * ##### Options * * - **http**: HTTP origin object that contains `req` and `res`. * - **rpc**: API3 (Ajax) origin that contains `req` and `res`. * - **skip**: Array of middlewares to skip * - **session**: Session object * - **method**: Name of the server method, e.g. `'forums.posts.show'` * - **layout**: Layout name as String **/ module.exports = function env(options) { var req = (options.http || options.rpc).req; var method = String(options.method || ''); var ns = method.split('.').shift(); var layout = options.layout; if (!layout) { // get auto-guessed layout based on requested apiPath: // // forum.threads.show -> default.forum.threads // blogs.index -> default.blogs // admin.dashboard -> admin // admin.users.show -> admin.users // layout = (('admin' === ns) ? '' : 'default.') + method.split('.').slice(0, -1).join('.'); } var ctx = { extras: { puncher: new Puncher() }, helpers: { asset_path: function asset_path(path) { var asset = nodeca.runtime.assets.manifest.assets[path]; return !asset ? "#" : nodeca.runtime.router.linkTo('assets', { path: asset }); } }, origin: { http: options.http, rpc: options.rpc }, skip: (options.skip || []).slice(), session: options.session || null, request: { // FIXME: should be deprecated in flavour of env.origin origin: !!options.rpc ? 'RPC' : 'HTTP', method: method, ip: req.connection.remoteAddress, user_agent: req.headers['user-agent'], namespace: ns }, data: {}, runtime: { // FIXME: must be set from cookies theme: 'desktop' }, settings: { params: {}, fetch: function fetchSettings(keys, callback) { nodeca.settings.get(keys, this.params, {}, callback); } }, response: { data: { head: { title: null, // should be filled with default value apiPath: method, // List of assets for yepnope, // Each element is an object with properties: // // type: css|js // link: asset_url // // example: assets.push({type: 'js', link: '//example.com/foo.js'}); assets: [] }, menus: {}, widgets: {} }, headers: {}, // Layouts are supporting "nesting" via `dots: // // default.blogs // // In the example above, `default.blogs` will be rendered first and the // result will be provided for rendering to `default`. layout: layout, // Default view template name == server method name // One might override this, to render different view // view: method } }; // // env-dependent helper needs to be bounded to env // ctx.helpers.t = function (phrase, params) { var locale = this.runtime.locale || nodeca.config.locales['default']; return nodeca.runtime.i18n.t(locale, phrase, params); }.bind(ctx); ctx.helpers.t.exists = function (phrase) { var locale = this.runtime.locale || nodeca.config.locales['default']; return nodeca.runtime.i18n.hasPhrase(locale, phrase); }.bind(ctx); ctx.helpers.date = function (value, format) { var locale = this.runtime.locale || nodeca.config.locales['default']; return nodeca.shared.date(value, format, locale, tzOffset); }.bind(ctx); return ctx; };
JavaScript
0.000001
@@ -976,454 +976,8 @@ t(); -%0A var layout = options.layout;%0A%0A if (!layout) %7B%0A // get auto-guessed layout based on requested apiPath:%0A //%0A // forum.threads.show -%3E default.forum.threads%0A // blogs.index -%3E default.blogs%0A // admin.dashboard -%3E admin%0A // admin.users.show -%3E admin.users%0A //%0A layout = (('admin' === ns) ? '' : 'default.') +%0A method.split('.').slice(0, -1).join('.');%0A %7D %0A%0A @@ -2705,22 +2705,41 @@ layout: -layout +options.layout %7C%7C 'admin' ,%0A
fd20009fcf17de391b398cbb7ce746144fc610c6
Add test for the search field.
js/Search.spec.js
js/Search.spec.js
import React from 'react' import { shallow } from 'enzyme' import { shallowToJson } from 'enzyme-to-json' import Search from './Search' import ShowCard from './ShowCard' import preload from '../public/data.json' test('Search snapshot test', () => { const component = shallow(<Search />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('Search should render a ShowCard for each show', () => { const component = shallow(<Search />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) })
JavaScript
0
@@ -461,18 +461,16 @@ arch /%3E) - %0A expec @@ -533,12 +533,478 @@ .length)%0A%7D)%0A +%0Atest('Search should render correct amount of shows based on the search', () =%3E %7B%0A const searchWord = 'house'%0A const component = shallow(%3CSearch /%3E)%0A component.find('input').simulate('change', %7Btarget:%7Bvalue:searchWord%7D%7D)%0A const showCount = preload.shows.filter((show) =%3E %7B%0A return %60$%7Bshow.title%7D $%7Bshow.description%7D%60%0A .toUpperCase().indexOf(searchWord%0A .toUpperCase()) %3E= 0%0A %7D).length%0A expect(component.find(ShowCard).length).toEqual(showCount)%0A%7D)%0A
1d86bf33d90fba6b54129554ecae3a2ea892eec1
修复v3版本app-plus下配置pullToRefresh无效的Bug
src/platforms/app-plus/service/framework/webview/parser/pull-to-refresh-parser.js
src/platforms/app-plus/service/framework/webview/parser/pull-to-refresh-parser.js
export function parsePullToRefresh (routeOptions) { const windowOptions = routeOptions.window if (windowOptions.enablePullDownRefresh) { const pullToRefreshStyles = Object.create(null) // 初始化默认值 if (plus.os.name === 'Android') { Object.assign(pullToRefreshStyles, { support: true, style: 'circle' }) } else { Object.assign(pullToRefreshStyles, { support: true, style: 'default', height: '50px', range: '200px', contentdown: { caption: '' }, contentover: { caption: '' }, contentrefresh: { caption: '' } }) } if (windowOptions.backgroundTextStyle) { pullToRefreshStyles.color = windowOptions.backgroundTextStyle pullToRefreshStyles.snowColor = windowOptions.backgroundTextStyle } Object.assign(pullToRefreshStyles, windowOptions.pullToRefresh || {}) return pullToRefreshStyles } }
JavaScript
0
@@ -134,16 +134,88 @@ nRefresh + %7C%7C (windowOptions.pullToRefresh && windowOptions.pullToRefresh.support) ) %7B%0D%0A
fdcfa64c627f9522db5f176cc103171df839cad1
Fix broken test by including babel polyfill on dummy app
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); module.exports = function(defaults) { var app = new EmberAddon(defaults, { // Add options here }); /* This build file specifies 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(); };
JavaScript
0.000001
@@ -107,16 +107,17 @@ function + (default @@ -168,27 +168,62 @@ -// Add options here +'ember-cli-babel': %7B%0A includePolyfill: true%0A %7D %0A %7D @@ -231,17 +231,16 @@ ;%0A%0A /*%0A - This @@ -306,17 +306,16 @@ this%0A - addon, l @@ -339,17 +339,16 @@ /dummy%60%0A - This @@ -416,17 +416,16 @@ g it%0A - behave. @@ -494,16 +494,17 @@ ld file%0A + */%0A%0A
79c3dfacc8da6cf47babd0a1179865c2f3ffc2d3
add error log
routes/api.js
routes/api.js
var AV = require('leanengine'); var ObjTree = require('objtree'); var request = require('request'); var router = require('express').Router(); var baiduKey = process.env.baiduKey; var expressAPI = process.env.expressAPI; var busAPIOne = process.env.busAPIOne; var busAPITwo = process.env.busAPITwo; var busAPIThree = process.env.busAPIThree; var detailUrl = process.env.busAPIFour; router.get('/weather', function(req, res, next) { var option = { url: 'http://api.map.baidu.com/telematics/v3/weather', qs: { ak: baiduKey, location: 'shanghai', output: 'json' } } request(option, function(error, response, body){ var resData = JSON.parse(body); var tipt = resData.results[0].index[0]; var weather = resData.results[0].weather_data[0]; weather.tipt = tipt; res.send(weather); }); }); router.get('/express/:type/:postId', function(req, res, next){ var type = req.params.type; var postId = req.params.postId; var option = { url: expressAPI, qs: { type: type, postid: postId } } request(option, function(error, response, body){ res.send(JSON.parse(body)); }); }); router.get('/bus/:name', function(req, res, next){ var name = req.params.name; var option = { url: busAPIOne, qs: { action: 'One', name: name } } var busLine = {}; request(option, function(error, response, body){ if (response && response.statusCode === 200) { body = JSON.parse(body); for(key in body) { busLine[key] = body[key].trim(); } var op = { url: busAPITwo, qs: { action: 'Two', name: busLine.line_name, lineid: busLine.line_id } } request(op, function(error, response, bd){ bd = JSON.parse(bd); bd.busLine = busLine; res.send(bd); }); } else { console.error(JSON.stringify(response)); var query = new AV.Query('LinesInfo'); query.equalTo('line_name', name); query.find().then(function(busData) { var result = {}; busData = busData[0]._serverData; result.busLine = { "line_name": busData.line_name, "line_id": busData.line_id, "start_stop": busData.start_stop, "end_stop": busData.end_stop, }; result.lineResults0 = busData.lineResults0; result.lineResults1 = busData.lineResults1; res.send(result); }); } }); }); router.get('/busstop/:name/:lineid/:stopid/:direction', function(req, res, next){ var name = req.params.name; var lineId = req.params.lineid; var stopId = req.params.stopid; var direction = req.params.direction; var option = { url: busAPIThree, qs: { action: 'Three', name: name, lineid: lineId, stopid: stopId, direction: direction } } request(option, function(error, response, body){ if (response && response.statusCode === 200) { res.send(JSON.parse(body)); } else { option.url = detailUrl; request(option, function(error, response, bd){ if (response && response.statusCode === 200) { var xotree = new ObjTree(); res.send({ cars: xotree.parseXML(bd).result.cars.car }); } else { res.send({ "cars":[] }); } }); } }); }); module.exports = router;
JavaScript
0.000001
@@ -1835,32 +1835,12 @@ ror( -JSON.stringify(response) +name );%0A @@ -2236,16 +2236,47 @@ %7D;%0A + console.error(result);%0A
2ab73875c54e504268158afe077edc2299e0561a
Update openshift-io-registration.page.js
src/tests/work-item/work-item-list/page-objects/openshift-io-registration.page.js
src/tests/work-item/work-item-list/page-objects/openshift-io-registration.page.js
/** * AlMighty page object example module for openshift.io start page * See: http://martinfowler.com/bliki/PageObject.html, * https://www.thoughtworks.com/insights/blog/using-page-objects-overcome-protractors-shortcomings * @author ldimaggi@redhat.com */ 'use strict'; /* * openshift.io "Additional Action Required" page Definition */ var testSupport = require('../testSupport'), constants = require("../constants"), OpenShiftIoDashboardPage = require('./openshift-io-dashboard.page'); var until = protractor.ExpectedConditions; const devProcesses = { Agile: 0, Scrum: 1, IssueTracking: 2, ScenarioDrivenPlanning: 3 } class OpenShiftIoRegistrationPage { constructor() { }; /* Email field */ get emailField () { return element(by.id("email")); } clickEmailField () { browser.wait(until.elementToBeClickable(this.emailField), constants.LONG_WAIT, 'Failed to find element emailField'); return this.emailField.click(); } typeEmailField (emailString) { browser.wait(until.elementToBeClickable(this.emailField), constants.LONG_WAIT, 'Failed to find element emailField'); return this.emailField.sendKeys(emailString); } /* First name field */ get firstNameField () { return element(by.id("firstName")); } clickfirstNameField () { browser.wait(until.elementToBeClickable(this.firstNameField), constants.LONG_WAIT, 'Failed to find element firstNameField'); return this.firstNameField.click(); } typefirstNameField (firstNameString) { browser.wait(until.elementToBeClickable(this.firstNameField), constants.LONG_WAIT, 'Failed to find element firstNameField'); return this.firstNameField.sendKeys(firstNameString); } /* First last field */ get lastNameField () { return element(by.id("lastName")); } clicklastNameField () { browser.wait(until.elementToBeClickable(this.lastNameField), constants.LONG_WAIT, 'Failed to find element lastNameField'); return this.lastNameField.click(); } typelastNameField (lastNameString) { browser.wait(until.elementToBeClickable(this.lastNameField), constants.LONG_WAIT, 'Failed to find element lastNameField'); return this.lastNameField.sendKeys(lastNameString); } /* Company field */ get companyField () { return element(by.id("user.attributes.company")); } clickCompanyField () { browser.wait(until.elementToBeClickable(this.companyField), constants.LONG_WAIT, 'Failed to find element companyField'); return this.companyField.click(); } typeCompanyField (companyString) { browser.wait(until.elementToBeClickable(this.companyField), constants.LONG_WAIT, 'Failed to find element companyField'); return this.companyField.sendKeys(companyString); } /* Phone number field */ get phoneNumberField () { return element(by.id("user.attributes.phoneNumber")); } clickPhoneNumberField () { browser.wait(until.elementToBeClickable(this.phoneNumberField), constants.LONG_WAIT, 'Failed to find element phoneNumberField'); return this.phoneNumberField.click(); } typePhoneNumberField (phoneNumberString) { browser.wait(until.elementToBeClickable(this.phoneNumberField), constants.LONG_WAIT, 'Failed to find element phoneNumberField'); return this.phoneNumberField.sendKeys(phoneNumberString); } /* Country field */ get countryField () { return element(by.id("user.attributes.country")); } clickCountryField () { browser.wait(until.elementToBeClickable(this.countryField), constants.LONG_WAIT, 'Failed to find element countryField'); return this.countryField.click(); } typeCountryField (countryString) { browser.wait(until.elementToBeClickable(this.countryField), constants.LONG_WAIT, 'Failed to find element countryField'); return this.countryField.sendKeys(countryString); } /* Address Line 1 field */ get addressLine1Field () { return element(by.id("user.attributes.addressLine1")); } clickAddressLine1Field () { browser.wait(until.elementToBeClickable(this.addressLine1Field), constants.LONG_WAIT, 'Failed to find element addressLine1'); return this.addressLine1Field.click(); } typeAddressLine1Field (addressLine1String) { browser.wait(until.elementToBeClickable(this.addressLine1Field), constants.LONG_WAIT, 'Failed to find element addressLine1'); return this.addressLine1Field.sendKeys(addressLine1String); } /* Address City field */ get addressCityField () { return element(by.id("user.attributes.addressCity")); } clickAddressCityField () { browser.wait(until.elementToBeClickable(this.addressCityField), constants.LONG_WAIT, 'Failed to find element addressCity'); return this.addressCityField.click(); } typeAddressCityField (addressCityString) { browser.wait(until.elementToBeClickable(this.addressCityField), constants.LONG_WAIT, 'Failed to find element addressCity'); return this.addressCityField.sendKeys(addressCityString); } /* Address State field */ get addressStateField () { return element(by.id("user.attributes.addressStateText")); } clickAddressStateField () { browser.wait(until.elementToBeClickable(this.addressStateField), constants.LONG_WAIT, 'Failed to find element addressState'); return this.addressStateField.click(); } typeAddressStateField (addressStateString) { browser.wait(until.elementToBeClickable(this.addressStateField), constants.LONG_WAIT, 'Failed to find element addressState'); return this.addressStateField.sendKeys(addressStateString); } /* Address Postal Code field */ get addressPostalCodeField () { return element(by.id("user.attributes.addressPostalCode")); } clickAddressPostalCodeField () { browser.wait(until.elementToBeClickable(this.addressPostalCodeField), constants.LONG_WAIT, 'Failed to find element addressPostalCode'); return this.addressPostalCodeField.click(); } typeAddressPostalCodeField (addressPostalCodeString) { browser.wait(until.elementToBeClickable(this.addressPostalCodeField), constants.LONG_WAIT, 'Failed to find element addressPostalCode'); return this.addressPostalCodeField.sendKeys(addressPostalCodeString); } /* Accept terms checkbox */ get termsCheckBox () { return element(by.id("user.attributes.tcacc-1147")); } clickTermsCheckBox () { browser.wait(until.elementToBeClickable(this.termsCheckBox), constants.LONG_WAIT, 'Failed to find element termsCheckBox'); return this.termsCheckBox.click(); } /* Newsletter checkbox */ get newsletterCheckBox () { return element(by.id("user.attributes.newsletter")); } clickNewsletterCheckBox () { browser.wait(until.elementToBeClickable(this.newsletterCheckBox), constants.LONG_WAIT, 'Failed to find element Newsletter'); return this.newsletterCheckBox.click(); } /* OpenShift Online Newsletter checkbox */ get openShiftOnlineNewsletterCheckBox () { return element(by.id("user.attributes.newsletterOpenShiftOnline")); } clickOpenShiftOnlineNewsletterCheckBox () { browser.wait(until.elementToBeClickable(this.openShiftOnlineNewsletterCheckBox), constants.LONG_WAIT, 'Failed to find element openShiftOnlineCheckBox'); return this.openShiftOnlineNewsletterCheckBox.click(); } /* Submit button */ get submitButton () { return element(by.css('.button')); } clickSubmitButton () { browser.wait(until.elementToBeClickable(this.submitButton), constants.LONG_WAIT, 'Failed to find element submitButton'); this.submitButton.click(); return new OpenShiftIoDashboardPage(); } } module.exports = OpenShiftIoRegistrationPage;
JavaScript
0.000001
@@ -572,58 +572,8 @@ = %7B%0A - Agile: 0,%0A Scrum: 1,%0A IssueTracking: 2,%0A @@ -600,9 +600,9 @@ ng: -3 +0 %0A %7D
a017caf3ae88404e4ec390bac3fcfc25382e42f9
Refactor deprecated res.send(status, body)
routes/api.js
routes/api.js
'use strict'; var express = require('express') , router = express.Router() ; var Atm = require('../lib/atm'); // router.param('uid', function(req, res, next, uid) { // Atm.getByUid(req.params.id, function(err, result) { // if (err) return next(err); // req.atm = result || { error: 'item ' + req.params.id + ' not found' }; // next(); // }); // }); // router.route('/:uid') // .get() // .post() // .delete() // -- Middleware function loadAtm(req, res, next) { var uid = req.params.uid; Atm.getByUid(uid, function(err, doc) { if (err) return next(err); if (doc !== null) { req.atm = doc; next(); } else { res.send(404, { error: 'item ' + uid + ' not found' }); } }); } function validateBody(req, res, next) { var body = req.body; body.uid = req.params.uid; Atm.validate(body, function(validation) { if (validation.valid === false) { res.send(400, { error: validation.errors }); } else { req.atm = new Atm(body); next(); } }); } // GET -- fetch an ATM by id router.get('/:uid', loadAtm, function(req, res, next) { res.json(req.atm); }); // GET -- List all available ATMs router.get('/', function(req, res, next) { Atm.getAll(function(err, items) { if (err) return next(err); res.json(items); }); }); // POST -- add a new ATM router.post('/', validateBody, function(req, res, next) { var atm = req.atm; atm.save(function(err, result) { if (err) return next(err); if (result.length === 1) { res.send(201, result[0]); } else { next(new Error('could not create document')); } }); }); router.post('/*', function(req, res) { res.set('Allow', 'GET, PUT, DELETE'); res.send(405, 'Method Not Allowed'); }); router.put('/:uid', [loadAtm, validateBody], function(req, res, next) { var atm = req.atm; atm.save(function(err, result) { if (err) return next(err); if (result === 1) { res.json(atm); } else { next(new Error('item could not be saved')); } }); }); /* * DELETE atm by id. * NOTE: this is the backend-generated `uuid` and NOT the `_id` field on mongo. */ router.delete('/:uid', loadAtm, function(req, res, next) { Atm.remove(req.params.uid, function(err, result) { if (err) return next(err); if (result === 1) { res.json(req.atm); } else { next(new Error('item could not be saved')); } }); }); module.exports = router;
JavaScript
0
@@ -594,9 +594,9 @@ doc -! += == n @@ -614,68 +614,27 @@ re -q.atm = doc;%0A next();%0A %7D else %7B%0A res +s.status(404) .send( -404, %7B er @@ -667,24 +667,72 @@ found' %7D);%0A + %7D else %7B%0A req.atm = doc;%0A next();%0A %7D%0A %7D);%0A @@ -924,17 +924,24 @@ es.s -end(400, +tatus(400).send( %7B er @@ -1544,17 +1544,24 @@ es.s -end(201, +tatus(201).send( resu @@ -1740,17 +1740,24 @@ es.s -end(405, +tatus(405).send( 'Met
8edb1339d61f4b39e1ba69caa3d797c483480f82
Return JSON with authors.
src/article/models/ContribsModel.js
src/article/models/ContribsModel.js
import entityRenderers from '../../entities/entityRenderers' import DefaultModel from './DefaultModel' /* A model for holding authors and editors information. */ export default class ContribsModel extends DefaultModel{ constructor(node, context) { super(node, context) } getAuthors() { let authorsContribGroup = this._node.find('contrib-group[content-type=author]') let contribIds = authorsContribGroup.findAll('contrib').map(contrib => contrib.getAttribute('rid')) return contribIds.map(contribId => this.context.pubMetaDb.get(contribId)) } /* Utility method to render a contrib object */ renderContrib(contrib) { return entityRenderers[contrib.type](contrib.id, this.context.pubMetaDb) } }
JavaScript
0
@@ -557,16 +557,25 @@ ntribId) +.toJSON() )%0A %7D%0A%0A @@ -739,9 +739,8 @@ )%0A %7D%0A%7D%0A -%0A
7fcc71a6d7433f25cbee02016f3ebcfb6c29de76
fix bug: getRecommendList
routes/api.js
routes/api.js
var express = require('express'); var request = require('request'); var fs = require('fs'); var mysql = require('mysql'); var router = express.Router(); var mysql_query = function (query, callback) { var connection = mysql.createConnection({ host: 'localhost', user: 'azure', password: '6#vWHD_$', port: 52603, database: 'lobubble' }); connection.connect(); connection.query(query, callback); connection.end(); } /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/login', function(req, res, next){ var access_token = req.query.access_token; request({ url: "https://graph.facebook.com/v2.9/me?fields=id,name,picture.width(400),gender&access_token=" + access_token // url: req.protocol + '://secure.c.i' + '/api/user/profile', // headers: req.headers }, function (err, res2, body) { // console.log(body); // if(err){ // next(err); // return; // } try { body = JSON.parse(body); body.picture = body.picture.data.url; mysql_query("REPLACE INTO `account` (`id`, `token`, `fb_id`, `time`) VALUES(NULL, '"+access_token+"', '"+body.id+"', CURRENT_TIMESTAMP)", function(err, rows, fields){ if(err){ next(err); return; } mysql_query("REPLACE INTO `user` (`id`, `fb_id`, `name`, `picture`, `gender`, `time`) VALUES(NULL, '"+body.id+"', '"+body.name+"', '"+body.picture+"', '"+body.gender +"', CURRENT_TIMESTAMP)", function(err, rows, fields){ if(err){ // next(err); // return; } res.send(body); }); }); } catch (error) { next(error); } }); }); router.get('/getFriendList', function(req, res, next){ var access_token = req.query.access_token; var fb_id = req.query.id?req.query.id:"me"; request({ url: "https://graph.facebook.com/v2.9/"+fb_id+"/friends?fields=id,name,picture.width(300),gender&limit=1000&access_token=" + access_token // url: req.protocol + '://secure.c.i' + '/api/user/profile', // headers: req.headers }, function (err, res2, body) { try { body = JSON.parse(body); for(item in body.data){ body.data[item].picture = body.data[item].picture.data.url; } for(item in body.data){ mysql_query("REPLACE INTO `user` (`id`, `fb_id`, `name`, `picture`, `gender`, `time`) VALUES(NULL, '"+body.data[item].id+"', '"+body.data[item].name+"', '"+body.data[item].picture +"', '"+body.data[item].gender +"', CURRENT_TIMESTAMP)", function(err, rows, fields){ if(err){ // next(err); // return; } // res.send(body); }); } res.send(body); } catch (error) { next(error); } }); }); router.get('/getMyRecommend', function(req, res, next){ var access_token = req.query.access_token?req.query.access_token:""; var fb_id = req.query.id?req.query.id:NULL; var fQuery = fb_id?fb_id:"(SELECT `account`.`fb_id` FROM `account` WHERE `account`.`token` = '"+access_token+"')"; mysql_query("SELECT `recommend`.*, `user`.`name`, `user`.`picture` FROM `recommend`, `user` WHERE `recommend`.`fb_id` = `user`.`fb_id` AND `recommend`.`fb_id` = " + fQuery, function(err, rows, fields){ if(err){ next(err); return; } res.send(rows); }); }); router.get('/addMyRecommend', function(req, res, next){ var access_token = req.query.access_token; var friend_id = req.query.friend_id; mysql_query("REPLACE INTO `recommend` (`id`, `fb_id`, `target_id`, `time`) VALUES(NULL, (SELECT `account`.`fb_id` FROM `account` WHERE `account`.`token` = '"+access_token+"'), '"+friend_id+"', CURRENT_TIMESTAMP)", function(err, rows, fields){ if(err){ next(err); return; } request({ url: req.protocol + '://' + req.get('host') + '/api/v1/getMyRecommend?access_token=' + access_token }, function(err, res2, body){ res.send(body); }); }); }); module.exports = router;
JavaScript
0
@@ -2946,20 +2946,20 @@ uery.id: -NULL +null ;%0A%09var f
d4722faff8630067ee142fc38b172645cec75548
move disqus loading to application.js
js/application.js
js/application.js
/* Author: */ $(function() { // $('.bigger').biggerlink(); // $('.tabs').tabs(); var init = function() { if (typeof FB !== 'undefined') FB.XFBML.parse(); if (typeof twttr !== 'undefined') twttr.widgets.load(); $(".various").fancybox({ // maxWidth : 800, // maxHeight : 600, // fitToView : false, // width : '70%', // height : '70%', // autoSize : false, // closeClick : false, // openEffect : 'none', // closeEffect : 'none' }); }; init(); // ajax pushState String.prototype.decodeHTML = function() { return $("<div>", {html: "" + this}).html(); }; if (window.history && window.history.pushState) { var loadPage = function(href) { history.ready = true; history.pushState({path: href}, '', href); $('#container').load(href + ' #container>*', function(html) { document.title = html.match(/<title>(.*?)<\/title>/)[1].trim().decodeHTML(); init(); }); }; $(document).on('click', "a:not([href^='http://'])", function() { var href = $(this).attr('href'); // if (href.indexOf(document.domain) > -1 || href.indexOf(':') === -1) { loadPage(href); // } return false; }); $(window).on("popstate", function(e) { // console.log(e.originalEvent); if (window.history.ready || e.originalEvent.state !== null) { // if not initial load loadPage(location.href); } }); // (function(original) { // overwrite history.pushState // history.pushState = function(state) { // change(state); // return original.apply(this, arguments); // }; // })(history.pushState); } });
JavaScript
0
@@ -109,120 +109,11 @@ ) %7B%0A -%09%09if (typeof FB !== 'undefined') FB.XFBML.parse();%0A%09%09if (typeof twttr !== 'undefined') twttr.widgets.load();%0A %09%09%0A + %09%09$( @@ -354,21 +354,686 @@ 'none'%0A - %09%09%7D); +%0A%0A%09%09if (typeof FB !== 'undefined') FB.XFBML.parse();%0A%09%09if (typeof twttr !== 'undefined') twttr.widgets.load();%0A%09%09%0A%09 /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */%0A%09 var disqus_shortname = 'usefulparadigm'; // required: replace example with your forum shortname%0A%0A%09 /* * * DON'T EDIT BELOW THIS LINE * * */%0A%09 (function() %7B%0A%09 var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;%0A%09 dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';%0A%09 (document.getElementsByTagName('head')%5B0%5D %7C%7C document.getElementsByTagName('body')%5B0%5D).appendChild(dsq);%0A%09 %7D)();%0A%09%09 %0A%09%7D;%0A%09%0A%09
c6a35ca35e3b241b3f276090559c8bd97ae1b837
Change RegistryEntry to "private"
src/registry.js
src/registry.js
'use babel'; let registry = new Map(); let refreshHandlers = []; export class RegistryEntry { constructor(options) { this.element = options.element; if (typeof options.liveTime !== 'undefined') { this.liveTime = options.liveTime; } else { this.liveTime = 600; } this.refresh = options.refresh; this.refreshable = isFinite(this.liveTime); this.lastChanged = new Date(); /** will be set after the entry was added to the registry */ this.id = null; } get() { const now = new Date(); if (this.refreshable && this.lastChanged.getTime() + this.liveTime < now.getTime()) { this.set(this.refresh()); } return this.element; } set(element) { this.lastChanged = new Date(); this.element = element; } remove() { if (this.id === null) { throw new Error(`This entry is not part of the registry`); } const wasInRegistry = registry.delete(this.id); if (wasInRegistry) { this.id = null; } else { throw new Error(`This entry is not part of the registry`); } } } function refresh() { refreshHandlers.forEach(cb => cb()); } export function on(event, cb) { switch (event) { case 'refresh': refreshHandlers.push(cb); break; default: throw new Error('Unknown event'); } } export function add(options) { const entry = new RegistryEntry(options); const id = Symbol(); entry.id = id; registry.set(id, entry); } export function getAll({type, name}={}, doRefresh=true) { if (doRefresh) { refresh(); } let all = []; registry.forEach(entry => { const element = entry.get(); if (type && !(element instanceof type)) { return; } if (name && element.name !== name) { return; } if (element) { all.push(element); } }); return all; }
JavaScript
0
@@ -60,23 +60,16 @@ = %5B%5D;%0A%0A -export class Re
0d7cfde7c85bf6c8275b7db45cc2f2faf911fb41
Use charCode instead of keyCode
js/application.js
js/application.js
;(function(){ var G = dijkstra.hexGrid(2); var view = new dijkstra.GraphView(G, document.getElementById('graph'), { placement: function(position){ return { 'x': 100 * position.x, 'y': 100 * position.y }}, radius: 20, between: 0.3, vertex: { events : { mouseenter: function(event){ var id = this.getAttribute('data-vertex'); var v = G.findVertex(id); algorithm.setPathFrom(v); } } } }); var algorithm = new dijkstra.ShortestPath(G); algorithm.setSource(G.vertices[0]); algorithm.setTarget(G.vertices[G.vertices.length - 1]); algorithm.setPathFrom(G.vertices[G.vertices.length - 1]); view.visualize(algorithm); function loop(){ view.update(); requestAnimationFrame(loop); }; loop(); document.body.addEventListener('keypress', function(event){ if (event.keyCode == 32) { algorithm.step(); } }); window.G = G; })();
JavaScript
0.000015
@@ -1009,19 +1009,20 @@ (event. -key +char Code ==
dadcfc719fb492d0dd15d4f49bc7dcb37b188861
drop self. access pattern
v2/frame.js
v2/frame.js
// Copyright (c) 2015 Uber Technologies, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; /* eslint-disable curly */ /* eslint max-statements: [1, 30] */ Frame.Overhead = 0x10; Frame.MaxSize = 0xffff; Frame.MaxBodySize = Frame.MaxSize - Frame.Overhead; Frame.MaxId = 0xfffffffe; Frame.NullId = 0xffffffff; Frame.Types = {}; module.exports = Frame; var bufrw = require('bufrw'); var errors = require('../errors'); var Types = require('./index.js').Types; function Frame(id, body) { var self = this; self.isLazy = false; self.size = 0; self.type = (body && body.type) || 0; if (id === null || id === undefined) { self.id = Frame.NullId; } else { self.id = id; } self.body = body; } // size:2: type:1 reserved:1 id:4 reserved:8 ... Frame.RW = bufrw.Base(frameLength, readFrameFrom, writeFrameInto); function frameLength(frame) { var body = frame.body; var bodyRW = body.constructor.RW; var length = 0; length += bufrw.UInt16BE.width; // size:2: length += bufrw.UInt8.width; // type:1 length += 1; // reserved:1 length += bufrw.UInt32BE.width; // id:4 length += 8; // reserved:8 ... var res = bodyRW.byteLength(body); if (!res.err) { res.length += length; } return res; } function readFrameFrom(buffer, offset) { var frame = new Frame(); var res; res = bufrw.UInt16BE.readFrom(buffer, offset); if (res.err) return res; offset = res.offset; frame.size = res.value; res = bufrw.UInt8.readFrom(buffer, offset); if (res.err) return res; offset = res.offset; frame.type = res.value; var BodyType = Frame.Types[frame.type]; if (!BodyType) { return bufrw.ReadResult.error(errors.InvalidFrameTypeError({ typeNumber: frame.type }), offset - 1); } offset += 1; res = bufrw.UInt32BE.readFrom(buffer, offset); if (res.err) return res; offset = res.offset; frame.id = res.value; offset += 8; res = BodyType.RW.readFrom(buffer, offset); if (res.err) { if (frame.type === Types.CallRequest || frame.type === Types.CallRequestCont ) { // TODO: wrapped? res.err.frameId = frame.id; } return res; } offset = res.offset; frame.body = res.value; res.value = frame; return res; } function writeFrameInto(frame, buffer, offset) { var body = frame.body; var bodyRW = body.constructor.RW; var start = offset; var end = offset; var res; // skip size, write later offset += bufrw.UInt16BE.width; res = bufrw.UInt8.writeInto(frame.type, buffer, offset); if (res.err) return res; offset = res.offset; end = offset + 1; buffer.fill(0, offset, end); offset = end; res = bufrw.UInt32BE.writeInto(frame.id, buffer, offset); if (res.err) return res; offset = res.offset; end = offset + 8; buffer.fill(0, offset, end); offset = end; res = bodyRW.writeInto(body, buffer, offset); if (res.err) return res; offset = res.offset; frame.size = res.offset - start; res = bufrw.UInt16BE.writeInto(frame.size, buffer, start); if (res.err) return res; res.offset = offset; return res; } Frame.fromBuffer = function fromBuffer(buffer) { return bufrw.fromBuffer(Frame.RW, buffer, 0); }; Frame.prototype.byteLength = function byteLength() { var self = this; return bufrw.byteLength(Frame.RW, self); }; Frame.prototype.intoBuffer = function intoBuffer(buffer) { var self = this; return bufrw.intoBuffer(Frame.RW, self, buffer); }; Frame.prototype.toBuffer = function toBuffer() { var self = this; return bufrw.toBuffer(Frame.RW, self); };
JavaScript
0.000054
@@ -1532,33 +1532,12 @@ -var self = this;%0A self +this .isL @@ -1553,20 +1553,20 @@ se;%0A -self +this .size = @@ -1572,20 +1572,20 @@ 0;%0A -self +this .type = @@ -1657,28 +1657,28 @@ ) %7B%0A -self +this .id = Frame. @@ -1706,20 +1706,20 @@ -self +this .id = id @@ -1730,20 +1730,20 @@ %7D%0A -self +this .body = @@ -4495,37 +4495,16 @@ gth() %7B%0A - var self = this;%0A retu @@ -4529,28 +4529,28 @@ h(Frame.RW, -self +this );%0A%7D;%0A%0AFrame @@ -4603,37 +4603,16 @@ ffer) %7B%0A - var self = this;%0A retu @@ -4641,20 +4641,20 @@ ame.RW, -self +this , buffer @@ -4713,29 +4713,8 @@ ) %7B%0A - var self = this;%0A @@ -4749,12 +4749,12 @@ RW, -self +this );%0A%7D
8e187489b8a4cfdcc7a88bef6173cd401d069765
Fix NullableBooleanInput
src/mui/input/NullableBooleanInput.js
src/mui/input/NullableBooleanInput.js
import React, { PropTypes } from 'react'; import SelectInput from './SelectInput'; import translate from '../../i18n/translate'; export const NullableBooleanInput = ({ input, meta: { touched, error }, label, source, elStyle, resource, translate }) => ( <SelectInput input={input} label={label} source={source} resource={resource} choices={[ { id: null, name: '' }, { id: false, name: translate('aor.boolean.false') }, { id: true, name: translate('aor.boolean.true') }, ]} errorText={touched && error} style={elStyle} /> ); NullableBooleanInput.propTypes = { addField: PropTypes.bool.isRequired, elStyle: PropTypes.object, input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object, resource: PropTypes.string, source: PropTypes.string, translate: PropTypes.func.isRequired, }; NullableBooleanInput.defaultProps = { addField: true, }; export default translate(NullableBooleanInput);
JavaScript
0
@@ -177,28 +177,8 @@ meta -: %7B touched, error %7D , la @@ -546,35 +546,18 @@ -errorText=%7Btouched && error +meta=%7Bmeta %7D%0A
5d07f83f1d18d3779369987f67e49330920f0e3d
set flow config for core client module
lib/client/engine.js
lib/client/engine.js
var Flow = require('./flow'); var Instance = require('./instance'); // client flag engine.client = true; engine._name = '@'; // extend engine with flow emitter engine = Flow(engine); // extend engine with logging methods engine.log = require('./logs') || function (err) {return err}; // listen to core engine events engine.MIND([ 'C', ['flow', {'emit': '@C'}] ]).MIND([ 'M', ['flow', {'emit': '@M'}] ]); /** * Create server module instances */ engine.load = function (name, role, callback, loaderInstance) { // ensure callback callback = callback || function () {}; // check instance chache if (engine.instances[name]) { return callback(null, engine.instances[name]); } // get composition engine.flow('C', true).error(function (stream, options, err) { stream.end(); callback(engine.log('E', err)); }).data(function (stream, options, composition) { // require module require(composition.module, function (module) { // create instance Instance(module, composition, role, callback, loaderInstance); }); stream.end(); }).write(null, name); }; // load entrypoint engine.load();
JavaScript
0
@@ -324,22 +324,25 @@ ine. -MIND(%5B +_flow = %7B %0A 'C' ,%0A @@ -337,22 +337,20 @@ %0A 'C' -,%0A +: %5B%5B %5B'flow', @@ -369,26 +369,19 @@ C'%7D%5D -%0A%5D).MIND(%5B +%5D%5D, %0A 'M' ,%0A @@ -376,22 +376,20 @@ %0A 'M' -,%0A +: %5B%5B %5B'flow', @@ -408,11 +408,12 @@ M'%7D%5D -%0A%5D) +%5D%5D%0A%7D ;%0A%0A/
82d4c874e599ba1a9c657f2b4274728681e7ae35
initialize new game in document ready
js/application.js
js/application.js
$(document).ready(function() { });
JavaScript
0.000001
@@ -24,13 +24,33 @@ ion() %7B%0A + game = new Game(); %0A%7D);%0A
1a511264c2fedbac83975326a92f504aa5eff59f
remove uppercase on buttons
agir/front/components/genericComponents/Button.js
agir/front/components/genericComponents/Button.js
import style from "./style.scss"; import styled from "styled-components"; import PropTypes from "prop-types"; import { transparentize } from "polished"; import { icons } from "feather-icons"; const buttonColors = { default: { background: style.black50, hoverBackground: style.black100, labelColor: style.black1000, }, primary: { background: style.primary500, labelColor: style.white, hoverBackground: style.primary600, }, secondary: { background: style.secondary500, labelColor: style.white, hoverBackground: style.secondary600, }, confirmed: { background: style.primary100, hoverBackground: style.primary150, labelColor: style.primary500, }, unavailable: { background: style.white, hoverBackground: style.white, labelColor: style.black500, borderColor: style.black100, }, }; const Button = styled.button.attrs(({ color }) => buttonColors[color])` display: inline-block; padding: ${({ small }) => (small ? "0.5rem 0.75rem" : "0.75rem 1.5rem")}; line-height: ${({ small }) => small ? "95%" : "1.5rem"}; /* pour s'assurer que les liens sont correctement centrés */ margin: 0; border-radius: 0.5rem; min-height: ${({ small }) => (small ? "2rem" : "3rem")}; text-align: center; text-transform: uppercase; font-weight: 700; font-size: ${({ small }) => (small ? "0.6875rem" : "0.875rem")}; color: ${({ labelColor, disabled }) => disabled ? transparentize(0.3, labelColor) : labelColor}; background-color: ${({ background, disabled }) => disabled ? transparentize(0.7, background) : background}; border: ${({ borderColor }) => borderColor ? `1px solid ${borderColor}` : "0"}; &:hover { ${({ disabled, hoverBackground }) => disabled ? "" : `background-color: ${hoverBackground};`} // disabled buttons must not change color on hover text-decoration: none; color: ${({ labelColor }) => labelColor}; // we need to overwrite link hover colors } ${({ disabled }) => disabled && "cursor: not-allowed;"} ${({ icon, labelColor, small }) => icon ? ` &:before { content: url('data:image/svg+xml;utf8,${ icons[icon] .toSvg({ color: encodeURI(labelColor), height: small ? 11 : 16, width: small ? 11 : 16, }) .replace("#", "%23") /* * problème bizarre, quand le SVG est utilisé dans un URL data: * Il faut remplacer les # des couleurs par l'équivalent url-encoded, mais * appliquer la même procédure aux autres substitutions (avec encodeURI par * exemple) ne fonctionne pas. * */ }'); position: relative; top: 0.15rem; margin-right: ${small ? "0.25rem" : "0.5rem"}; } ` : ""} }} `; Button.colors = Object.keys(buttonColors); Button.propTypes = { onClick: PropTypes.func, color: PropTypes.oneOf(Button.colors), small: PropTypes.bool, disabled: PropTypes.bool, href: PropTypes.string, block: PropTypes.bool, }; Button.defaultProps = { color: "default", small: false, block: false, }; export default Button;
JavaScript
0.999624
@@ -1287,37 +1287,8 @@ er;%0A - text-transform: uppercase;%0A fo
e6bb457f3bab8b5383b49f736410439e8f9ca5ef
Update client.js
src/config/client.js
src/config/client.js
// This is the entry point for our client-side logic // The server-side has a similar configuration in `src/server/middleware/render.js` import '../assets/css/index.scss' import 'isomorphic-fetch' import 'core/polyfills' import 'core/globals' import 'core/logger' import onEnter from 'core/onEnter' import Inferno from 'inferno' import { Router, match } from 'inferno-router' import { Provider } from 'inferno-mobx' import createBrowserHistory from 'history/createBrowserHistory'; import autorun from './autorun' import createContext from './context' import State from '../stores/State' import routes from './routes' if (process.env.NODE_ENV !== 'production') { require('inferno-devtools') require('mobx-logger').enableLogging({ action: true, reaction: false, transaction: true, compute: false }) } else { require('./sw') } const context = createContext(new State(window.__STATE)) const history = createBrowserHistory() // React to changes autorun(context) // Fetch data on route change history.listen(location => { onEnter(match(routes, location), context) }) console.warn(history.location.pathname) // Render our component according to our routes function renderApp() { Inferno.render(<Provider {...context}> <Router history={history} url={history.location.pathname}> {routes} </Router> </Provider>, document.getElementById('container')) } renderApp() // Enable hot reloading if available if (module.hot) { module.hot.accept(renderApp) }
JavaScript
0.000001
@@ -1089,49 +1089,8 @@ %7D)%0A%0A -console.warn(history.location.pathname)%0A%0A // R
003f0ee466533c5096aa7c85fc35982395af9b13
Bind correct context
src/mw-utils/services/mw_scheduler.js
src/mw-utils/services/mw_scheduler.js
window.mwUI.Utils.Scheduler = {}; window.mwUI.Utils.Scheduler.Task = window.mwUI.Backbone.Model.extend({ defaults: function () { return { callback: function () { }, executeInMs: 0, _time: 0 } }, getRemainingSleepTime: function () { return this.get('executeInMs') - this.get('_time'); }, decrementTime: function (time) { time = time || 1; var currentTime = this.get('_time'); this.set('_time', currentTime + time); }, canBeExecuted: function () { return this.getRemainingSleepTime() <= 0; }, execute: function () { this.get('callback').apply(this.get('scope')); if (this.collection) { this.collection.remove(this); } }, resetTime: function () { this.set('_time', 0); }, kill: function () { if (this.collection) { return this.collection.remove(this); } else { return false; } } }); window.mwUI.Utils.Scheduler.TaskRunner = window.mwUI.Backbone.Collection.extend({ _timer: false, _stopped: false, _startTime: null, _prevValue: null, model: window.mwUI.Utils.Scheduler.Task, _step: function (timestamp) { var progress, delta; if (this.isStopped()) { return; } if (this._startTime) { this._startTime = timestamp; } progress = timestamp - this._startTime; delta = this._prevValue ? progress - this._prevValue : 0; if (this.length > 0) { this.secureEach(function (task) { if (task.canBeExecuted()) { task.execute(); } else { task.decrementTime(delta); } }); this._prevValue = progress; window.requestAnimationFrame(this._step.bind(this)); } }, start: function () { this._stopped = false; this._startTime = null; this._prevValue = null; if (this.length > 0) { window.requestAnimationFrame(this._step.bind(this)); } }, isRunning: function () { return this.length > 0 && !this._stopped; }, isStopped: function () { return this._stopped; }, stop: function () { this._stopped = true; }, add: function (task, executeInMs, id, scope) { if (typeof task === 'function') { task = new window.mwUI.Utils.Scheduler.Task({ id: id || _.uniqueId('task'), callback: task, executeInMs: executeInMs, scope: scope || window }); } mwUI.Backbone.Collection.prototype.add.call(this, task); if (task && !_.isFunction(task.get('callback'))) { throw new Error('[mwScheduler] Task has to be a function'); } if (!this.isStopped()) { this.start(); } return task; }, remove: function (task) { var existingTask = this.findWhere({callback: task}); return mwUI.Backbone.Collection.prototype.remove.call(this, existingTask || task); }, get: function (task) { if (typeof task === 'function') { return this.findWhere({callback: task}); } else { return mwUI.Backbone.Collection.prototype.get.apply(this, arguments); } } }); angular.module('mwUI.Utils') .service('mwScheduler', function () { var scheduler = new window.mwUI.Utils.Scheduler.TaskRunner(); angular.element(document).on('visibilitychange', function () { if (document.hidden) { scheduler.stop(); } else { scheduler.start(); } }.bind(this)); angular.element(window).on('blur', scheduler.stop); angular.element(window).on('focus', scheduler.start); return scheduler; });
JavaScript
0.99992
@@ -3409,16 +3409,32 @@ ler.stop +.bind(scheduler) );%0A a @@ -3483,16 +3483,32 @@ er.start +.bind(scheduler) );%0A%0A
0901ecf4dbd5da49a7208499981e927f195bd490
add download url
routes/f2e.js
routes/f2e.js
var express = require('express'); var router = express.Router(); var path = require('path'); var shell = require('shelljs'); var config = require('../config'); var build = require('../service/build'); var origin_sync = require('../service/origin_sync'); var qiniu_sync = require('../service/qiniu-sync'); var version = require('../service/version'); module.exports = router; router.get('/alpha/:name', function(req, res) { var logger = require('../logger')('log/down_gz.log', 'downgz'); var owner = req.query.owner; var name = req.params.name; var repos_work_dir = path.resolve(config.alpha_work_path, owner, name); var deployed_dir = path.resolve(config.static_server.alpha, owner, name); if (!shell.test('-e', repos_work_dir)) { res.status(200).json({ data: owner + '/' + name + '项目不存在或从未发布' }); } var pkg = require(path.resolve(repos_work_dir, './package.json')); var filename = pkg.version + '.tar.gz'; var fileurl = path.resolve(deployed_dir, filename); if (!shell.test('-f', fileurl)) { res.status(200).json({ data: owner + '/' + name + '项目从未发布成功' }); } res.download(fileurl, name + '-' + pkg.version + '.tar.gz', function(err) { if (err) { logger.error(fileurl + '下载失败'); logger.info('错误信息如下: \n' + err.message); res.status(err.status).end(); return; } logger.info(fileurl + '下载成功'); }); }); router.post('/alpha', function (req, res) { var repos = req.body.repository; var log_dir = 'log/' + repos.owner.username; var log_file = log_dir + '/' + repos.name + '.log'; shell.exec('mkdir -p ' + log_dir); shell.exec('touch ' + log_file); shell.exec('> ' + log_file); var logger = require('../logger')(log_file, 'publish'); logger.info('准备发布 alpha 环境...'); logger.info('正在预处理静态资源...'); var build_rs = build( req.body, config.alpha_work_path ); if (!build_rs) { logger.fatal('预处理静态资源失败'); return res.status(200).json({ code: 500, data: '预处理静态资源过程中发生错误' }); } logger.info('预处理静态资源完成'); var pkg = require(path.resolve(build_rs.out_dir, './package.json')); var src = path.resolve(build_rs.out_dir, pkg.dest, './*'); var dest_dir = path.resolve(config.static_server.alpha, repos.owner.username, pkg.name, pkg.version); logger.info('正在发布静态资源到服务器...'); var origin_sync_rs = origin_sync(src, dest_dir); if (origin_sync_rs.code !== 0) { logger.fatal('静态资源发布到服务器失败'); logger.info('错误信息:\n' + origin_sync_rs.output); res.status(200).json({ code: 500, data: '静态资源发布到服务器失败' }); return; } logger.info('正在发布静态资源到七牛服务器...'); try { var qiniu_sync_rs = qiniu_sync(); if (qiniu_sync_rs.code !== 0) { logger.error('上传静态资源到七牛服务器出错...'); logger.error('错误信息:\n' + qiniu_sync_rs.output); } } catch(e) { // 暂不做处理,因为七牛服务器不接受 html 文件,所以导致错误 logger.info(e); } logger.info('静态资源发布成功'); logger.info('正在生成静态资源压缩包...'); // TODO // 优化:工作区压缩,然后上传到静态服务器 // 进入静态服务器目录 shell.cd(path.dirname(dest_dir)); console.log(shell.pwd()); var tar_gz = shell.exec('sudo tar -czvf ' + pkg.version + '.tar.gz ' + pkg.version); var tar_gz_tip_prefix = '生成静态资源压缩包' + path.resolve(dest_dir, pkg.version); if (tar_gz.code !== 0) { var err_tip = tar_gz_tip_prefix + '失败'; logger.fatal(err_tip); logger.info('错误信息:\n' + tar_gz.output); res.status(200).json({ code: 500, data: err_tip }); return; } logger.info(tar_gz_tip_prefix + '成功'); logger.info('正在更新版本数据库...'); version({ owner: build_rs.repository.owner.username, name: build_rs.repository.name, version: pkg.version, url: build_rs.repository.url }, function() { logger.info('版本更新成功'); // logger.info('正在清理发布目录...'); // shell.exec(['rm', '-rf', build_rs.out_dir].join(' ')); // logger.info('清理发布目录完成'); // logger.warn('other info:'); // logger.info(log); res.status(200).json({ code: 200, data: '项目发布成功' }); }); });
JavaScript
0
@@ -3685,16 +3685,157 @@ tory.url +,%0A download: 'http://d.ifdiu.com/f2e/alpha/' + build_rs.repository.name + '?secret=yunhua@926&owner=' + build_rs.repository.owner.username %0A %7D, fu
40c4050d42a9ab44f917e664c45f3d98672c5344
change size
js/application.js
js/application.js
// Wait till the browser is ready to render the game (avoids glitches) window.requestAnimationFrame(function () { new GameManager(4, KeyboardInputManager, HTMLActuator, LocalScoreManager); });
JavaScript
0.000001
@@ -129,9 +129,9 @@ ger( -4 +3 , Ke
b60908537af13b1a41a69bdf9f35b1c00810ded6
drop HtmlWebpackPlugin
webpack.config.babel.js
webpack.config.babel.js
import webpack from 'webpack'; import fs from 'fs'; import path from 'path'; const HtmlWebpackPlugin = require('html-webpack-plugin'); export default { cache: true, entry: [ './src/index.js' ], devtool: 'inline-source-map', devServer: { contentBase: './game/', hot: true }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'game/js/plugins/') }, module: { loaders: [{ test: /\.js$/, loader: 'babel-loader', exclude: [ path.resolve(__dirname, "node_modules"), ], }, { test: /\.json$/, loader: 'json-loader' }] }, plugins: [ new HtmlWebpackPlugin({ title: 'Hot Module Replacement' }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), ], resolve: { extensions: ['*', '.js', '.json'] } }
JavaScript
0
@@ -70,16 +70,18 @@ 'path';%0A +// const Ht @@ -284,17 +284,36 @@ se: -'./ +path.join(__dirname, %22 game -/' +%22) ,%0A @@ -747,24 +747,35 @@ plugins: %5B%0A + /*%0A new @@ -852,16 +852,29 @@ %7D),%0A + */%0A
085cddcad728e0ce88ecbb93b06ac3ab709b50d1
fix enabled again
src/bot/commands/default/channel.js
src/bot/commands/default/channel.js
const channels = require("../../modules/channels.js"); module.exports = { process: async message => { let enabled = await channels.enabled(message.channel.guild.id); if(!enabled || !enabled.value) return __("commands.default.channel.notEnabled", message); let botPerms = message.channel.guild.members.get(bot.user.id).permission; if(!botPerms.has("manageChannels")) return __("commands.default.channel.noPerms", message); if(message.args[0] === "create") { let current = await channels.get(message.member); if(current) return __("commands.default.channel.hasChannelAlready", message, { name: current.name }); let channel = await channels.create(message.member, message.args[1]); return __("commands.default.channel.created", message, { name: message.args[1] }); } else if(message.args[0] === "kick") { let current = await channels.get(message.member); if(!current) return __("commands.default.channel.needsChannel", message); try { message.args[1] = await bot.utils.resolver.user(message, message.args[1]); } catch(err) { return err.message; } if(!current.voiceMembers.has(message.args[1].id)) return __("commands.default.channel.cantKick", message); await bot.editChannelPermission(current.id, message.args[1].id, 0, 1048576, "member"); let tempChannel = await bot.createChannel(message.channel.guild.id, "VOICEKICK", 2); await current.voiceMembers.get(message.args[1].id).edit({ channelID: tempChannel.id }); await tempChannel.delete(); return __("commands.default.channel.kicked", message, { user: `${message.args[1].username}#${message.args[1].discriminator}` }); } else if(message.args[0] === "bitrate") { let current = await channels.get(message.member); if(!current) return __("commands.default.channel.needsChannel", message); try { message.args[1] = await bot.utils.resolver.num(message, message.args[1], { min: 8, max: 96 }); } catch(err) { return err.message; } await current.edit({ bitrate: message.args[1] }); return __("commands.default.channel.changedBitrate", message, { bitrate: message.args[1] }); } else if(message.args[0] === "userlimit") { let current = await channels.get(message.member); if(!current) return __("commands.default.channel.needsChannel", message); try { message.args[1] = await bot.utils.resolver.num(message, message.args[1], { min: 0, max: 99 }); } catch(err) { return err.message; } await current.edit({ userLimit: message.args[1] }); return __("commands.default.channel.changedUserLimit", message, { limit: message.args[1] }); } else if(message.args[0] === "privacy") { let current = await channels.get(message.member); if(!current) return __("commands.default.channel.needsChannel", message); if(message.args[1] === "private") { await bot.editChannelPermission(current.id, message.channel.guild.id, 0, 1048576, "role"); return __("commands.default.channel.nowPrivate", message); } else if(message.args[1] === "public") { await bot.editChannelPermission(current.id, message.channel.guild.id, 1048576, 0, "role"); return __("commands.default.channel.nowPublic", message); } else { return __("commands.default.channel.invalidPrivacy", message); } } else if(message.args[0] === "whitelist" || message.args[0] === "wl") { let current = await channels.get(message.member); if(!current) return __("commands.default.channel.needsChannel", message); try { message.args[1] = await bot.utils.resolver.num(message, message.args[1], { min: 8, max: 96 }); } catch(err) { return err.message; } await bot.editChannelPermission(current.id, message.args[1], 1048576, 0, "member") .catch(err => {}); // eslint-disable-line return __("command.default.channel.whitelisted", message, { user: `${message.args[1].username}#${message.args[1].discriminator}` }); } else { return __("command.default.channel.invalidSubcommand", message); } }, guildOnly: true, description: "Have users create their own channels, with options to make it private, kick users, and more", args: [{ type: "text", label: "create|kick|bitrate|userlimit|privacy|whitelist" }, { type: "text", label: "name|user|number|private/public|user" }] };
JavaScript
0
@@ -179,26 +179,8 @@ bled - %7C%7C !enabled.value ) re
c9fa47e3c9fd49f601691671bb44ef7806c071c0
Update Webpack configs
webpack.config.bower.js
webpack.config.bower.js
'use strict'; var webpack = require('webpack'); var path = require('path'); var babelLoader = 'babel?' + JSON.stringify({ presets: ['es2015', 'react'], plugins: ['transform-es2015-modules-commonjs', 'transform-object-rest-spread'] }); module.exports = { devtool: 'source-map', entry: './src/index.js', output: { filename: require('./package.json').name + '.js', path: path.resolve('build'), library: 'Component', libraryTarget: 'umd' }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }) ], module: { loaders: [ {test: /\.js$/, loader: babelLoader, include: [path.resolve('src')]} ] }, resolve: {extensions: ['', '.js']}, stats: {colors: true}, externals: { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } } };
JavaScript
0
@@ -75,179 +75,8 @@ ');%0A -var babelLoader = 'babel?' +%0A JSON.stringify(%7B%0A presets: %5B'es2015', 'react'%5D,%0A plugins: %5B'transform-es2015-modules-commonjs', 'transform-object-rest-spread'%5D%0A %7D);%0A %0A%0Amo @@ -480,19 +480,15 @@ er: +' babel -Loader +' , in
7deb43a8b67667ea4aece052d14fc5e802e1ab64
Attach ReactPerf to window for easier debugging (#3318)
app/javascript/mastodon/performance.js
app/javascript/mastodon/performance.js
// // Tools for performance debugging, only enabled in development mode. // Open up Chrome Dev Tools, then Timeline, then User Timing to see output. // Also see config/webpack/loaders/mark.js for the webpack loader marks. // let marky; if (process.env.NODE_ENV === 'development') { if (typeof performance !== 'undefined' && performance.setResourceTimingBufferSize) { // Increase Firefox's performance entry limit; otherwise it's capped to 150. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1331135 performance.setResourceTimingBufferSize(Infinity); } marky = require('marky'); require('react-addons-perf').start(); } export function start(name) { if (process.env.NODE_ENV === 'development') { marky.mark(name); } } export function stop(name) { if (process.env.NODE_ENV === 'development') { marky.stop(name); } }
JavaScript
0
@@ -598,16 +598,108 @@ rky');%0A + // allows us to easily do e.g. ReactPerf.printWasted() while debugging%0A window.ReactPerf = require @@ -719,16 +719,36 @@ s-perf') +;%0A window.ReactPerf .start()
963f4c6da5a81b9178d5323441339e0c24e93881
clear linklibrary
js/authManager.js
js/authManager.js
/** * Created by matthias on 30/03/2015. */ window.AuthManager = Ember.Object.extend({ cookieName : "authToken", redirectUrl : "dashboard", // TODO: change to actual route authToken : null, _private_user : null, user : function() { if (!this.get("_private_user")) this.fetchUserInfo(); return this.get("_private_user"); }.property("_private_user"), isLoggedIn : function() { return this.token() != null; }.property("authToken"), logout: function(){ $.removeCookie(this.get("cookieName")); this.set("authToken", null); }, login : function(selfCaller, email, password) { var result = this.adapter.post("login", { "emailAddress" : email, "password" : password }); var temp = this.get("cookieName"); var self = this; return result.then(function(data) { $.cookie(temp, data.authToken); self.set("authToken", data.authToken); self.fetchUserInfo(); }); }, fetchUserInfo : function() { var self = this; return this.adapter.find("user", null, "me").then(function(data) { self.set("_private_user", data); }); }, token : function() { if (this.authToken == null) { var token = $.cookie(this.cookieName); if (token == null){ return null; } else { this.set("authToken", token); } } return this.get("authToken"); } });
JavaScript
0
@@ -520,16 +520,106 @@ tion()%7B%0A + this.adapter.set(%22linkLibrary%22,%7B%7D);%0A this.set(%22_private_user%22, undefined);%0A
4ac2ed4e10e55d611050ad0243d51025fce38778
Use ssl reports endpoint
src/reporter.js
src/reporter.js
import request from "browser-request"; const url = "http://beta.accesslint.com/api/v1/reports"; export default function (message) { const violations = message.violations; if (violations.length > 0) { let descriptions = []; violations.map((violation) => { descriptions.push(violation.help); }); request({ method: "POST", url: url, json: message, }, function() {}); throw new Error( `AccessLintError: ${violations.length} violations:` + "\n" + descriptions.join(",\n") ); } }
JavaScript
0
@@ -50,16 +50,17 @@ = %22http +s ://beta.
b784d8e32b5502b840e0d5d72d2dcfb784410841
remove location query
app/javascript/services/forest-data.js
app/javascript/services/forest-data.js
import axios from 'axios'; const DATASET = process.env.COUNTRIES_PAGE_DATASET; const REQUEST_URL = `${process.env.GFW_API_HOST_PROD}/query/${DATASET}?sql=`; const CARTO_REQUEST_URL = `${process.env.CARTO_API_URL}/sql?q=`; const SQL_QUERIES = { extent: "SELECT SUM({extentYear}) as value, SUM(area_gadm28) as total_area FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}'", gain: "SELECT {calc} as value FROM data WHERE {location} AND polyname = '{indicator}' AND thresh = {threshold}", gainExtent: "SELECT {region} as region, SUM(area_gain) AS gain, SUM({extentYear}) AS extent FROM data WHERE {location} AND polyname = '{polyname}' AND extent <> -9999 AND thresh = 0 GROUP BY region", loss: "SELECT polyname, year_data.year as year, SUM(year_data.area_loss) as area, SUM(year_data.emissions) as emissions FROM data WHERE polyname = '{indicator}' AND {location} AND thresh= {threshold} GROUP BY polyname, iso, nested(year_data.year)", locations: "SELECT {location} as region, {extentYear} as extent, {extent} as total FROM data WHERE iso = '{iso}' AND thresh = {threshold} AND polyname = '{indicator}' {grouping}", fao: "SELECT fao.iso, fao.name, forest_planted, forest_primary, forest_regenerated, fao.forest_primary, fao.extent, a.land as area_ha FROM gfw2_countries as fao INNER JOIN umd_nat_staging as a ON fao.iso = a.iso WHERE fao.forest_primary is not null AND fao.iso = '{country}' AND a.year = 2001 AND a.thresh = 30", faoExtent: 'SELECT country AS iso, name, year, reforest AS rate, forest*1000 AS extent FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {period} AND reforest > 0 ORDER BY rate DESC' }; const getExtentYear = year => (year === 2000 ? 'area_extent_2000' : 'area_extent'); const getLocationQuery = (country, region, subRegion) => `iso = '${country}'${region ? ` AND adm1 = ${region}` : ''}${ subRegion ? ` AND adm2 = ${subRegion}` : '' }`; const getRankingLocationQuery = (country, region, subRegion) => `${ region ? `iso = '${country}' ${subRegion ? `AND adm1 = ${region}` : ''}` : '1 = 1' }`; export const getLocations = ({ country, region, indicator, threshold, extentYear }) => { const url = `${REQUEST_URL}${SQL_QUERIES.locations}` .replace('{location}', region ? 'adm2' : 'adm1') .replace( '{extentYear}', `${!region ? 'sum(' : ''}${getExtentYear(extentYear)}${ !region ? ')' : '' }` ) .replace('{extent}', region ? 'area_gadm28' : 'sum(area_gadm28)') .replace('{iso}', country) .replace('{threshold}', threshold) .replace('{indicator}', indicator) .replace('{grouping}', region ? `AND adm1 = '${region}'` : 'GROUP BY adm1'); return axios.get(url); }; export const getExtent = ({ country, region, subRegion, indicator, threshold, extentYear }) => { const url = `${REQUEST_URL}${SQL_QUERIES.extent}` .replace('{location}', getLocationQuery(country, region, subRegion)) .replace('{threshold}', threshold) .replace('{indicator}', indicator) .replace( '{extentYear}', `area_extent${extentYear === 2000 ? `_${extentYear}` : ''}` ); return axios.get(url); }; export const getGain = ({ country, region, subRegion, indicator, threshold }) => { const url = `${REQUEST_URL}${SQL_QUERIES.gain}` .replace('{location}', getLocationQuery(country, region, subRegion)) .replace('{threshold}', threshold) .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)') .replace('{indicator}', indicator); return axios.get(url); }; export const getLoss = ({ country, region, subRegion, indicator, threshold }) => { const url = `${REQUEST_URL}${SQL_QUERIES.loss}` .replace('{location}', getLocationQuery(country, region, subRegion)) .replace('{threshold}', threshold) .replace('{indicator}', indicator); return axios.get(url); }; export const getFAO = ({ country }) => { const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.fao}`.replace( '{country}', country ); return axios.get(url); }; export const getFAOExtent = ({ period }) => { const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoExtent}`.replace( '{period}', period ); return axios.get(url); }; export const getGainExtent = ({ country, region, subRegion, indicator, extentYear }) => { let regionValue = 'iso'; if (subRegion) { regionValue = 'adm2'; } else if (region) { regionValue = 'adm1'; } const url = `${REQUEST_URL}${SQL_QUERIES.gainExtent}` .replace('{region}', regionValue) .replace('{location}', getRankingLocationQuery(country, region, subRegion)) .replace( '{extentYear}', extentYear === 2000 ? 'area_extent_2000' : 'area_extent' ) .replace('{polyname}', indicator); return axios.get(url); };
JavaScript
0.001226
@@ -1967,184 +1967,8 @@ %60;%0A%0A -const getRankingLocationQuery = (country, region, subRegion) =%3E%0A %60$%7B%0A region%0A ? %60iso = '$%7Bcountry%7D' $%7BsubRegion ? %60AND adm1 = $%7Bregion%7D%60 : ''%7D%60%0A : '1 = 1'%0A %7D%60;%0A%0A expo @@ -4332,16 +4332,128 @@ ';%0A %7D%0A%0A + const location = region%0A ? %60iso = '$%7Bcountry%7D' $%7BsubRegion ? %60AND adm1 = $%7Bregion%7D%60 : ''%7D%60%0A : '1 = 1';%0A%0A const @@ -4569,59 +4569,16 @@ %7D', -getRankingLocationQuery(country, region, subRegion) +location )%0A
0fbb1cc5167ea049896f62e058bc06768276c326
ANDROID_CHROME_VERSION was undefined
src/abstract-fullscreen.js
src/abstract-fullscreen.js
var ua = navigator.userAgent; var fsEnabled = native('fullscreenEnabled'); var parsedChromeUA = ua.match(/Android.*Chrome\/(\d+)\./); var IS_ANDROID_CHROME = !!parsedChromeUA; var CHROME_VERSION; if (IS_ANDROID_CHROME) { ANDROID_CHROME_VERSION = parseInt(parsedChromeUA[1]); } var IS_NATIVELY_SUPPORTED = (!IS_ANDROID_CHROME || ANDROID_CHROME_VERSION > 37) && defined(native('fullscreenElement')) && (!defined(fsEnabled) || fsEnabled === true); var version = $.fn.jquery.split('.'); var JQ_LT_17 = (parseInt(version[0]) < 2 && parseInt(version[1]) < 7); var FullScreenAbstract = function() { this.__options = null; this._fullScreenElement = null; this.__savedStyles = {}; }; FullScreenAbstract.prototype = { 'native': native, _DEFAULT_OPTIONS: { styles: { 'boxSizing': 'border-box', 'MozBoxSizing': 'border-box', 'WebkitBoxSizing': 'border-box' }, toggleClass: null }, __documentOverflow: '', __htmlOverflow: '', _preventDocumentScroll: function() { this.__documentOverflow = document.body.style.overflow; this.__htmlOverflow = document.documentElement.style.overflow; if(!$(this._fullScreenElement).is('body, html')){ $('body, html').css('overflow', 'hidden'); } }, _allowDocumentScroll: function() { document.body.style.overflow = this.__documentOverflow; document.documentElement.style.overflow = this.__htmlOverflow; }, _fullScreenChange: function() { if (!this.__options) { return; // only process fullscreenchange events caused by this plugin } if (!this.isFullScreen()) { this._allowDocumentScroll(); this._revertStyles(); this._triggerEvents(); this._fullScreenElement = null; } else { this._preventDocumentScroll(); this._triggerEvents(); } }, _fullScreenError: function(e) { if (!this.__options) { return; // only process fullscreenchange events caused by this plugin } this._revertStyles(); this._fullScreenElement = null; if (e) { $(document).trigger('fscreenerror', [e]); } }, _triggerEvents: function() { $(this._fullScreenElement).trigger(this.isFullScreen() ? 'fscreenopen' : 'fscreenclose'); $(document).trigger('fscreenchange', [this.isFullScreen(), this._fullScreenElement]); }, _saveAndApplyStyles: function() { var $elem = $(this._fullScreenElement); this.__savedStyles = {}; for (var property in this.__options.styles) { // save this.__savedStyles[property] = this._fullScreenElement.style[property]; // apply this._fullScreenElement.style[property] = this.__options.styles[property]; } if ($elem.is('body')) { // in order to manipulate scrollbar of BODY in Chrome/OPR // you have to change 'overflow' property HTML element document.documentElement.style.overflow = this.__options.styles.overflow; } if (this.__options.toggleClass) { $elem.addClass(this.__options.toggleClass); } }, _revertStyles: function() { var $elem = $(this._fullScreenElement); for (var property in this.__options.styles) { this._fullScreenElement.style[property] = this.__savedStyles[property]; } if ($elem.is('body')) { // in order to manipulate scrollbar of BODY in Chrome/OPR // you have to change 'overflow' property HTML element document.documentElement.style.overflow = this.__savedStyles.overflow; } if (this.__options.toggleClass) { $elem.removeClass(this.__options.toggleClass); } }, open: function(elem, options) { // do nothing if request is for already fullscreened element if (elem === this._fullScreenElement) { return; } // exit active fullscreen before opening another one if (this.isFullScreen()) { this.exit(); } // save fullscreened element this._fullScreenElement = elem; // apply options, if any this.__options = $.extend(true, {}, this._DEFAULT_OPTIONS, options); // save current element styles and apply new this._saveAndApplyStyles(); }, exit: null, isFullScreen: null, isNativelySupported: function() { return IS_NATIVELY_SUPPORTED; } };
JavaScript
0.999998
@@ -190,16 +190,45 @@ ERSION;%0A +var ANDROID_CHROME_VERSION;%0A%0A if (IS_A
f016756118fa3647a3492b77529a060f69f4e059
Add state and plugins to globalSettings
app/js/arethusa.core/globalSettings.js
app/js/arethusa.core/globalSettings.js
"use strict"; angular.module('arethusa.core').service('globalSettings', [ 'configurator', function(configurator) { var self = this; var confKeys = [ "alwaysDeselect", "colorizer" ]; self.defaultConf = { alwaysDeselect: false, colorizer: 'morph' }; function configure() { self.conf = configurator.configurationFor('main').globalSettings || {}; configurator.delegateConf(self, confKeys, true); // true makes them sticky self.settings = {}; self.colorizers = {}; defineSettings(); } function Conf(property, type, options) { this.property = property; this.label = "globalSettings." + property; this.type = type || 'checkbox'; if (this.type === 'select') { this.options = options; } } function defineSettings() { defineSetting('alwaysDeselect'); defineSetting('colorizer', 'select', self.colorizers); } function defineSetting(property, type, options) { self.settings[property] = new Conf(property, type, options); } this.toggle = function() { self.active = !self.active; }; configure(); } ]);
JavaScript
0
@@ -86,16 +86,44 @@ rator',%0A + '$injector',%0A 'plugins',%0A functi @@ -137,16 +137,36 @@ igurator +, $injector, plugins ) %7B%0A @@ -183,16 +183,207 @@ this;%0A%0A + // Need to do this lazy to avoid circular dependencies!%0A var lazyState;%0A function state() %7B%0A if (!lazyState) lazyState = $injector.get('state');%0A return lazyState;%0A %7D%0A%0A var
1e4e6eadd966f6f2e98cf43cac084781155a5cf1
Make search result code a bit more compact (#7995)
src/actions/file-search.js
src/actions/file-search.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ // @flow import { clearSearch, find, findNext, findPrev, removeOverlay, searchSourceForHighlight } from "../utils/editor"; import { isWasm, renderWasmText } from "../utils/wasm"; import { getMatches } from "../workers/search"; import type { Action, FileTextSearchModifier, ThunkArgs } from "./types"; import type { WasmSource } from "../types"; import { getSelectedSource, getFileSearchModifiers, getFileSearchQuery, getFileSearchResults } from "../selectors"; import { closeActiveSearch, clearHighlightLineRange, setActiveSearch } from "./ui"; type Editor = Object; type Match = Object; export function doSearch(query: string, editor: Editor) { return ({ getState, dispatch }: ThunkArgs) => { const selectedSource = getSelectedSource(getState()); if (!selectedSource || !selectedSource.text) { return; } dispatch(setFileSearchQuery(query)); dispatch(searchContents(query, editor)); }; } export function doSearchForHighlight( query: string, editor: Editor, line: number, ch: number ) { return async ({ getState, dispatch }: ThunkArgs) => { const selectedSource = getSelectedSource(getState()); if (!selectedSource || !selectedSource.text) { return; } dispatch(searchContentsForHighlight(query, editor, line, ch)); }; } export function setFileSearchQuery(query: string): Action { return { type: "UPDATE_FILE_SEARCH_QUERY", query }; } export function toggleFileSearchModifier( modifier: FileTextSearchModifier ): Action { return { type: "TOGGLE_FILE_SEARCH_MODIFIER", modifier }; } export function updateSearchResults( characterIndex: number, line: number, matches: Match[] ): Action { const matchIndex = matches.findIndex( elm => elm.line === line && elm.ch === characterIndex ); return { type: "UPDATE_SEARCH_RESULTS", results: { matches, matchIndex, count: matches.length, index: characterIndex } }; } export function searchContents(query: string, editor: Object) { return async ({ getState, dispatch }: ThunkArgs) => { const modifiers = getFileSearchModifiers(getState()); const selectedSource = getSelectedSource(getState()); if (!editor || !selectedSource || !selectedSource.text || !modifiers) { return; } const ctx = { ed: editor, cm: editor.codeMirror }; if (!query) { clearSearch(ctx.cm, query); return; } const _modifiers = modifiers.toJS(); let text = selectedSource.text; if (isWasm(selectedSource.id)) { text = renderWasmText(((selectedSource: any): WasmSource)).join("\n"); } const matches = await getMatches(query, text, _modifiers); const res = find(ctx, query, true, _modifiers); if (!res) { return; } const { ch, line } = res; dispatch(updateSearchResults(ch, line, matches)); }; } export function searchContentsForHighlight( query: string, editor: Object, line: number, ch: number ) { return async ({ getState, dispatch }: ThunkArgs) => { const modifiers = getFileSearchModifiers(getState()); const selectedSource = getSelectedSource(getState()); if ( !query || !editor || !selectedSource || !selectedSource.text || !modifiers ) { return; } const ctx = { ed: editor, cm: editor.codeMirror }; const _modifiers = modifiers.toJS(); searchSourceForHighlight(ctx, false, query, true, _modifiers, line, ch); }; } export function traverseResults(rev: boolean, editor: Editor) { return async ({ getState, dispatch }: ThunkArgs) => { if (!editor) { return; } const ctx = { ed: editor, cm: editor.codeMirror }; const query = getFileSearchQuery(getState()); const modifiers = getFileSearchModifiers(getState()); const { matches } = getFileSearchResults(getState()); if (query === "") { dispatch(setActiveSearch("file")); } if (modifiers) { const matchedLocations = matches || []; const results = rev ? findPrev(ctx, query, true, modifiers.toJS()) : findNext(ctx, query, true, modifiers.toJS()); if (!results) { return; } const { ch, line } = results; dispatch(updateSearchResults(ch, line, matchedLocations)); } }; } export function closeFileSearch(editor: Editor) { return ({ getState, dispatch }: ThunkArgs) => { if (editor) { const query = getFileSearchQuery(getState()); const ctx = { ed: editor, cm: editor.codeMirror }; removeOverlay(ctx, query); } dispatch(setFileSearchQuery("")); dispatch(closeActiveSearch()); dispatch(clearHighlightLineRange()); }; }
JavaScript
0.000004
@@ -4231,41 +4231,20 @@ nst -results = rev%0A ? findPrev( +findArgs = %5B ctx, @@ -4277,63 +4277,83 @@ JS() -) +%5D; %0A - : findNext(ctx, query, true, modifiers.toJS() +const results = rev ? findPrev(...findArgs) : findNext(...findArgs );%0A%0A
277f8035f7e01931b3a7d5df2ac9d07bf850a300
Update changelog
src/parser/priest/shadow/CHANGELOG.js
src/parser/priest/shadow/CHANGELOG.js
import React from 'react'; import { Zerotorescue, Khadaj} from 'CONTRIBUTORS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { change, date } from 'common/changelog'; export default [ change(date(2018, 11, 19), <>Added <SpellLink id={SPELLS.DEATH_THROES.id} /> module.</>, [Khadaj]), change(date(2018, 11, 19), <>Added <SpellLink id={SPELLS.VAMPIRIC_EMBRACE.id} /> module.</>, [Khadaj]), change(date(2018, 11, 8), <>Added <SpellLink id={SPELLS.DARK_VOID_TALENT.id} />.</>, [Khadaj]), change(date(2018, 11, 7), <>Fixed the last proc of <SpellLink id={SPELLS.VOIDFORM_BUFF.id} /> in the checklist. Added azerite trait <SpellLink id={SPELLS.CHORUS_OF_INSANITY.id} />.</>, [Khadaj]), change(date(2018, 8, 5), <>Fixed a bug where the Haste gained from <SpellLink id={SPELLS.VOIDFORM_BUFF.id} /> was never removed when not using <SpellLink id={SPELLS.LINGERING_INSANITY_TALENT.id} />.</>, [Zerotorescue]), change(date(2018, 8, 5), <>Fixed crash when using <SpellLink id={SPELLS.DARK_ASCENSION_TALENT.id} />.</>, [Zerotorescue]), change(date(2018, 6, 22), 'Updated spells and several modules to be compatible with BFA.', [Zerotorescue]), ];
JavaScript
0.000001
@@ -50,16 +50,25 @@ , Khadaj +, Adoraci %7D from ' @@ -227,16 +227,128 @@ fault %5B%0A + change(date(2019, 8, 17), %3C%3EAdded %3CSpellLink id=%7BSPELLS.WHISPERS_OF_THE_DAMNED.id%7D /%3E module.%3C/%3E, %5BAdoraci%5D),%0A change
61e7bba1f52abae6f4f112932139b73e61ce22a8
Remove child function already existing in parent
src/Controls/Dropzone/DropzoneViewBridge.js
src/Controls/Dropzone/DropzoneViewBridge.js
scms.create('DropzoneViewBridge', function(){ return { attachEvents:function() { var self = this; var timeout; var path = $('.dropzone-post-url').val(); var dz = new window.Dropzone("div#" + this.leafPath + ' div', { url:path, parallelUploads: 100, init: function() { this.on('queuecomplete', function(file) { var files = this.files; for(var i = 0; i < files.length; i++) { files[i].imageSrc = $(this.files[i].previewElement).find('img').attr('src'); } self.raiseProgressiveServerEvent('fileUploadedEvent', path); }) }, previewTemplate: self.viewNode.querySelector('.dz-template').innerHTML }); dz.on("addedfile", function(file) { refreshGridly(); }); $('.dz-close-button').click(function() { var image = $(this).parent().find('.dz-image img').attr('src'); var element = $(this); self.raiseProgressiveServerEvent('deleteImage', image, function() { element.parent().remove(); }); }); var gridly = $.extend(true, {}, getGridlySettings(), { callbacks: { reordered: reorderImages } }); $('#' + this.leafPath + ' .gridly .brick').width(gridly.base).height(gridly.base); $('#' + this.leafPath + ' .gridly').gridly(gridly); function refreshGridly() { $('#' + self.leafPath + ' .gridly').gridly('refresh', getGridlySettings()); } function getGridlySettings() { var gridWidth = $('.gridly').width(); var columns = Math.round(gridWidth / 140); var base = Math.round((gridWidth - (20 * columns)) / columns); return { base: base, gutter: 20, columns: columns }; } function reorderImages(order, a, b) { var imageList = []; order.each(function(){ imageList.push($(this).data('id')); }); self.raiseProgressiveServerEvent('imageReorder', imageList); } $(window).resize(function(){ // buffer execution by 50ms // this way we dont do multiple resizes // if user keeps resizing browser window clearTimeout(timeout); timeout = setTimeout(refreshGridly, 50); }); refreshGridly(); }, findEventHost:function(){ var selfNode = document.getElementById(this.leafPath); while (selfNode) { var testNode = selfNode; selfNode = selfNode.parentNode; var className = ( testNode.className ) ? testNode.className : ""; if (className.indexOf("event-host") == 0 || className.indexOf("event-host") > 0) { if (!testNode.viewBridge) { if (!testNode.id) { testNode.id = "event-host"; } new window.ViewBridge(testNode.id); if ((testNode.className.indexOf("event-host") == 0 || testNode.className.indexOf("event-host") > 0) && testNode.viewBridge != undefined) { testNode.viewBridge.host = true; } } } if (testNode.viewBridge && testNode.viewBridge.host && testNode.className.indexOf("configured") == -1) { return testNode.viewBridge; } } return false; } } });
JavaScript
0.000028
@@ -2863,1168 +2863,8 @@ %7D -,%0A%09%09findEventHost:function()%7B%0A var selfNode = document.getElementById(this.leafPath);%0A%0A while (selfNode) %7B%0A var testNode = selfNode;%0A%0A selfNode = selfNode.parentNode;%0A%0A var className = ( testNode.className ) ? testNode.className : %22%22;%0A%0A if (className.indexOf(%22event-host%22) == 0 %7C%7C className.indexOf(%22event-host%22) %3E 0) %7B%0A if (!testNode.viewBridge) %7B%0A if (!testNode.id) %7B%0A testNode.id = %22event-host%22;%0A %7D%0A%0A new window.ViewBridge(testNode.id);%0A%0A if ((testNode.className.indexOf(%22event-host%22) == 0 %7C%7C testNode.className.indexOf(%22event-host%22) %3E 0) && testNode.viewBridge != undefined) %7B%0A testNode.viewBridge.host = true;%0A %7D%0A %7D%0A %7D%0A%0A if (testNode.viewBridge && testNode.viewBridge.host && testNode.className.indexOf(%22configured%22) == -1) %7B%0A return testNode.viewBridge;%0A %7D%0A %7D%0A%0A return false;%0A%09%09%7D %0A%09%7D%0A
50ab97c079120221011c481a08201a367d2f8688
Move elements at end of tests
js/canvas-test.js
js/canvas-test.js
module("Canvas"); test("Canvas Creation", function() { notEqual(canvas, undefined, "Test if canvas is undefined"); notEqual(canvas, null, "Test if canvas is null"); }); test("Add Process", function() { var p = canvas.addProcess(100, 100); equal(p.x(), 100, "Test process x location"); equal(p.y(), 100, "Test process y location"); ok(!p.is('rect'), "Test if process is a rectangle"); ok(p.is('circle'), "Test if process is a circle"); }); test("Add External Interactor", function() { var p = canvas.addExtInteractor(100, 100); equal(p.x(), 75, "Test process x location"); equal(p.y(), 75, "Test process y location"); ok(p.is('rect'), "Test if process is a rectangle"); ok(!p.is('circle'), "Test if process is a circle"); }); test("Advanced Bounding Box", function() { var x = 50; var y = 50; var b = canvas.addExtInteractor(50, 50).getABBox(); equal(b.x, 25, "top left corner x"); equal(b.y, 25, "top left corner y"); equal(b.width, 50, "width"); equal(b.height, 50, "height"); equal(b.xLeft, 25, "left edge"); equal(b.xCenter, 50, "center x"); equal(b.xRight, 75, "right edge"); equal(b.yTop, 25, "top edge"); equal(b.yMiddle, 50, "middle y"); equal(b.yBottom, 75, "bottom edge"); deepEqual(b.center, {x: 50, y: 50}, "center point"); deepEqual(b.topLeft, {x: 25, y: 25}, "top left point"); deepEqual(b.topRight, {x: 75, y: 25}, "top right point"); deepEqual(b.bottomLeft, {x: 25, y: 75}, "bottom left point"); deepEqual(b.bottomRight, {x: 75, y: 75}, "bottom right point"); deepEqual(b.top, {x: 50, y: 25}, "top center point"); deepEqual(b.bottom, {x: 50, y: 75}, "bottom center point"); deepEqual(b.left, {x: 25, y: 50}, "left middle point"); deepEqual(b.right, {x: 75, y: 50}, "right middle point"); })
JavaScript
0
@@ -428,32 +428,46 @@ s is a circle%22); +%0A%0A%09p.remove(); %0A%7D);%0A%0Atest(%22Add @@ -742,16 +742,30 @@ ircle%22); +%0A%0A%09p.remove(); %0A%7D);%0A%0Ate @@ -836,17 +836,17 @@ 0;%0A%09var -b +p = canva @@ -871,12 +871,23 @@ (50, - 50) +;%0A%09var b = p .get @@ -1777,11 +1777,25 @@ point%22); +%0A%0A%09p.remove(); %0A%7D)
4d7b535cb6deabff4b2c94bf484533fb242ddbdd
Update changelog
src/parser/priest/shadow/CHANGELOG.js
src/parser/priest/shadow/CHANGELOG.js
import React from 'react'; import { Zerotorescue, Khadaj, Adoraci} from 'CONTRIBUTORS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { change, date } from 'common/changelog'; export default [ change(date(2019, 8, 17), <>Added <SpellLink id={SPELLS.WHISPERS_OF_THE_DAMNED.id} /> module.</>, [Adoraci]), change(date(2018, 11, 19), <>Added <SpellLink id={SPELLS.DEATH_THROES.id} /> module.</>, [Khadaj]), change(date(2018, 11, 19), <>Added <SpellLink id={SPELLS.VAMPIRIC_EMBRACE.id} /> module.</>, [Khadaj]), change(date(2018, 11, 8), <>Added <SpellLink id={SPELLS.DARK_VOID_TALENT.id} />.</>, [Khadaj]), change(date(2018, 11, 7), <>Fixed the last proc of <SpellLink id={SPELLS.VOIDFORM_BUFF.id} /> in the checklist. Added azerite trait <SpellLink id={SPELLS.CHORUS_OF_INSANITY.id} />.</>, [Khadaj]), change(date(2018, 8, 5), <>Fixed a bug where the Haste gained from <SpellLink id={SPELLS.VOIDFORM_BUFF.id} /> was never removed when not using <SpellLink id={SPELLS.LINGERING_INSANITY_TALENT.id} />.</>, [Zerotorescue]), change(date(2018, 8, 5), <>Fixed crash when using <SpellLink id={SPELLS.DARK_ASCENSION_TALENT.id} />.</>, [Zerotorescue]), change(date(2018, 6, 22), 'Updated spells and several modules to be compatible with BFA.', [Zerotorescue]), ];
JavaScript
0.000001
@@ -227,16 +227,126 @@ fault %5B%0A + change(date(2019, 8, 18), %3C%3EAdded %3CSpellLink id=%7BSPELLS.SPITEFUL_APPARITIONS.id%7D /%3E module.%3C/%3E, %5BAdoraci%5D),%0A change
c6421b56b5889cc71d554ca57ecbb6e6576813b2
bump version to 1.4.1 (#8904)
website/data/version.js
website/data/version.js
export const VERSION = '1.4.0' export const CHANGELOG_URL = 'https://github.com/hashicorp/vault/blob/master/CHANGELOG.md#140-april-7th-2020'
JavaScript
0
@@ -21,17 +21,17 @@ = '1.4. -0 +1 '%0Aexport @@ -122,17 +122,18 @@ d#14 -0 +1 -april- -7 +30 th-2
8e591108ed0abc66218b46df094566936402fc2a
add verb-readme-generator to verbfile
verbfile.js
verbfile.js
'use strict'; var apidocs = require('./'); module.exports = function(verb) { verb.data({nickname: 'apidocs'}); verb.helper('apidocs', apidocs({ delims: ['{%', '%}'] })); verb.helper('wrap', function(name) { return '{%= ' + name + '(\'index.js\') %}'; }); verb.task('default', function(cb) { verb.toStream('docs', function(key, view) { return key === '.verb'; }) .pipe(verb.renderFile()) .on('error', cb) .pipe(verb.pipeline()) .on('error', cb) .pipe(verb.dest('.')) .on('finish', cb) }); };
JavaScript
0.000259
@@ -83,37 +83,46 @@ erb. -data(%7Bnickname: 'apidocs'%7D +extendWith('verb-readme-generator' );%0A +%0A ve @@ -306,271 +306,18 @@ t', -function(cb) %7B%0A verb.toStream('docs', function(key, view) %7B%0A return key === '.verb';%0A %7D)%0A .pipe(verb.renderFile())%0A .on('error', cb)%0A .pipe(verb.pipeline())%0A .on('error', cb)%0A .pipe(verb.dest('.'))%0A .on('finish', cb)%0A %7D +%5B'readme'%5D );%0A%7D
ca0453b0ceee2cbc3000ec227b653facf3e78b93
Set min-width for tabs to fit spinner
src/app/righthand-panel.js
src/app/righthand-panel.js
var yo = require('yo-yo') var $ = require('jquery') var tabbedMenu = require('./tabbed-menu') var contractTab = require('./contract-tab') var settingsTab = require('./settings-tab') var analysisTab = require('./analysis-tab') var debuggerTab = require('./debugger-tab') var filesTab = require('./files-tab') var csjs = require('csjs-inject') var css = csjs` .options { float: left; padding: 0.7em 0.3em; font-size: 0.9em; cursor: pointer; background-color: transparent; margin-right: 0.5em; font-size: 1em; } ` // ------------------------------------------------------------------ module.exports = RighthandPanel function RighthandPanel (container, appAPI, events, opts) { var optionViews = yo`<div id="optionViews" class="settingsView"></div>` var element = yo` <div id="righthand-panel"> <div id="header"> <div id="menu"> <img id="solIcon" title="Solidity realtime compiler and runtime" src="assets/img/remix_logo_512x512.svg" alt="Solidity realtime compiler and runtime"> <ul id="options"> <li class="envView" title="Environment">Contract</li> <li class="settingsView" title="Settings">Settings</li> <li class="publishView" title="Publish" >Files</li> <li class="debugView" title="Debugger">Debugger</li> <li class="staticanalysisView" title="Static Analysis">Analysis</li> <li id="helpButton"><a href="https://remix.readthedocs.org" target="_blank" title="Open Documentation">Docs</a></li> </ul> </div> ${optionViews} </div> </div> ` contractTab(optionViews, appAPI, events, opts) settingsTab(optionViews, appAPI, events, opts) analysisTab(optionViews, appAPI, events, opts) debuggerTab(optionViews, appAPI, events, opts) filesTab(optionViews, appAPI, events, opts) container.appendChild(element) ;[...container.querySelectorAll('#header #options li')].forEach((el) => { el.classList.add(css.options) }) // ----------------- toggle right hand panel ----------------- var hidingRHP = false $('.toggleRHP').click(function () { hidingRHP = !hidingRHP setEditorSize(hidingRHP ? 0 : appAPI.config.get(EDITOR_WINDOW_SIZE)) $('.toggleRHP i').toggleClass('fa-angle-double-right', !hidingRHP) $('.toggleRHP i').toggleClass('fa-angle-double-left', hidingRHP) }) // ----------------- tabbed menu ----------------- var tabbedMenuAPI = { warnCompilerLoading: appAPI.warnCompilerLoading } // load tabbed menu component var tabContainer // @TODO var tabEvents = {compiler: events.compiler, app: events.app} tabbedMenu(tabContainer, tabbedMenuAPI, tabEvents, {}) // ----------------- resizeable ui --------------- var EDITOR_WINDOW_SIZE = 'editorWindowSize' var dragging = false $('#dragbar').mousedown(function (e) { e.preventDefault() dragging = true var main = $('#righthand-panel') var ghostbar = $('<div id="ghostbar">', { css: { top: main.offset().top, left: main.offset().left } }).prependTo('body') $(document).mousemove(function (e) { ghostbar.css('left', e.pageX + 2) }) }) var $body = $('body') function setEditorSize (delta) { $('#righthand-panel').css('width', delta) $('#editor').css('right', delta) appAPI.onResize() } function getEditorSize () { return $('#righthand-panel').width() } $(document).mouseup(function (e) { if (dragging) { var delta = $body.width() - e.pageX + 2 $('#ghostbar').remove() $(document).unbind('mousemove') dragging = false delta = (delta < 50) ? 50 : delta setEditorSize(delta) appAPI.config.set(EDITOR_WINDOW_SIZE, delta) appAPI.reAdjust() } }) if (appAPI.config.exists(EDITOR_WINDOW_SIZE)) { setEditorSize(appAPI.config.get(EDITOR_WINDOW_SIZE)) } else { appAPI.config.set(EDITOR_WINDOW_SIZE, getEditorSize()) } }
JavaScript
0
@@ -410,24 +410,47 @@ .7em 0.3em;%0A + min-width: 65px;%0A font-s
5833e3b9ad7280af120106de904489e690300fec
Add blank line at beginning of a function
examples/google.js
examples/google.js
// Load modules var Hapi = require('hapi'); var Bell = require('../'); var server = new Hapi.Server(); server.connection({ host: 'localhost', port: 4567}); server.register(Bell, function (err) { server.auth.strategy('google', 'bell', { provider: 'google', password: 'password', isSecure: false, // You'll need to go to https://console.developers.google.com and set up an application to get started // Once you create your app, fill out "APIs & auth >> Consent screen" and make sure to set the email field // Next, go to "APIs & auth >> Credentials and Create new Client ID // Select "web application" and set "AUTHORIZED JAVASCRIPT ORIGINS" and "AUTHORIZED REDIRECT URIS" // This will net you the clientId and the clientSecret needed. // Also be sure to pass the redirect_uri as well. It must be in the list of "AUTHORIZED REDIRECT URIS" clientId: '', clientSecret: '', providerParams: { redirect_uri: server.info.uri + '/bell/door' } }); server.route({ method: '*', path: '/bell/door', config: { auth: { strategy: 'google', mode: 'try' }, handler: function (request, reply) { if (!request.auth.isAuthenticated) { return reply('Authentication failed due to: ' + request.auth.error.message); } reply('<pre>' + JSON.stringify(request.auth.credentials, null, 4) + '</pre>'); } } }); server.start(function (err) { console.log('Server started at:', server.info.uri); }); });
JavaScript
0.00814
@@ -1292,24 +1292,25 @@ t, reply) %7B%0A +%0A
30b8dac07dab1f6fbc3b3a13037be8db73a186d9
add back conditional check to see if playback should start automatically
src/app/stories/stories.js
src/app/stories/stories.js
angular.module('prx.stories', ['ui.router', 'angular-hal', 'ngPlayerHater']) .config(function ($stateProvider, ngHalProvider, $urlRouterProvider) { $stateProvider.state('story', { url: '/stories/:storyId?autoPlay', controller: 'StoryCtrl', templateUrl: 'stories/story.html', resolve: { story: ['ngHal', '$stateParams', function (ngHal, $stateParams) { return ngHal.followOne('prx:story', {id: $stateParams.storyId}); }], account: ['story', function (story) { return story.follow('prx:account'); }] } }) .state('story.details', { url: '/details', views: { 'modal@': { controller: 'StoryDetailCtrl', templateUrl: 'stories/detail_modal.html' } } }); if (FEAT.LISTEN_LATER) { $stateProvider.state('story.remindMe', { views: { 'modal@': { controller: 'StoryDetailCtrl', templateUrl: 'stories/remind_me_modal.html' } } }); } $urlRouterProvider.when('/pieces/:pieceId', "/stories/{pieceId}"); ngHalProvider.setRootUrl(FEAT.apiServer) .mixin('http://meta.prx.org/model/story', ['resolved', 'playerHater', function (resolved, playerHater) { resolved.$audioFiles = resolved.follow('prx:audio'); resolved.imageUrl = resolved.follow('prx:image').get('enclosureUrl'); return { sound: function () { if (typeof this.$sound === 'undefined') { var audioFiles = []; angular.forEach(this.$audioFiles, function (audioFile) { audioFiles.push({url: audioFile.links('enclosure').url()}); }); this.$sound = playerHater.newSong.apply(playerHater, audioFiles); this.$sound.story = this; } return this.$sound; }, play: function () { if (this.sound() == playerHater.nowPlaying) { playerHater.resume(); } else { playerHater.play(this.sound()); } }, pause: function () { playerHater.pause(this.sound()); }, togglePlay: function () { if (this.paused()) { this.play(); } else { this.pause(); } }, paused: function () { return (typeof this.$sound === 'undefined' || this.$sound.paused); } }; }]) .mixin('http://meta.prx.org/model/story', ['$sce', function ($sce) { return function (story) { story.description = $sce.trustAsHtml(story.description); }; }]) .mixin('http://meta.prx.org/model/image/*splat', ['resolved', function (resolved) { resolved.enclosureUrl = resolved.call('link', 'enclosure').call('url'); }]) .mixin('http://meta.prx.org/model/account/:type', ['type', 'resolved', function (type, resolved) { resolved.imageUrl = resolved.follow('prx:image').get('enclosureUrl').or(null); resolved.address = resolved.follow('prx:address'); }]) .mixin('http://meta.prx.org/model/address', { toString: function () { return this.city + ', ' + this.state; } }); }) .controller('StoryCtrl', function ($scope, story, account, $stateParams) { $scope.story = story; $scope.account = account; $scope.activeStory = $scope.activeStory || {}; $scope.activeStory.id = ~~$stateParams.storyId; }) .controller('StoryDetailCtrl', function ($scope, story) { $scope.story = story; });
JavaScript
0
@@ -3253,16 +3253,69 @@ toryId;%0A + if ($stateParams.autoPlay) %7B%0A story.play();%0A %7D%0A %7D)%0A.cont
1b5a5ebb300e7a342d038b17ece79a307dc43cc9
Add checkPlace(cheackAvailability before)
app/scripts/services/service.places.js
app/scripts/services/service.places.js
import {autobind} from 'core-decorators'; const firebaseArray = new WeakMap(); const firebaseObject = new WeakMap(); const REF = new WeakMap(); const AUTH = new WeakMap(); class Places { constructor($firebaseArray, $firebaseObject, Auth, FURL) { let baseref = new Firebase(FURL); firebaseArray.set(this, $firebaseArray); firebaseObject.set(this, $firebaseObject); REF.set(this, baseref.child('places')); AUTH.set(this, Auth); this.places = $firebaseArray(REF.get(this)); } @autobind all() { let activePlaces = firebaseArray.get(this)(REF.get(this) .orderByChild('status').equalTo('active')); return activePlaces.$loaded(); } @autobind get(placeId) { return firebaseObject.get(this)(REF.get(this).child(placeId)).$loaded(); } @autobind create(placeInfo) { let {name, lastname} = AUTH.get(this).user.profile; placeInfo.TIMESTAMP = Firebase.ServerValue.TIMESTAMP; placeInfo.status = 'active'; placeInfo.creator = AUTH.get(this).user.profile.username; placeInfo.creatorEmail = AUTH.get(this).user.profile.email; placeInfo.creatorFullName = `${name} ${lastname}`; return this.places.$add(placeInfo); } @autobind edit(placeId, newInfo) { let place = REF.get(this).child(placeId); let {name, capacity, location} = newInfo; // Set Exacts Values for our place let toSave = { name: name, capacity: capacity, location: location }; return place.update(toSave); } // Removes don't really removes only set place.status to 'disabled' @autobind remove(placeId) { let place = REF.get(this).child(placeId); return place.update({status: 'disabled'}); } } Places.$inject = ['$firebaseArray', '$firebaseObject', 'Auth', 'FURL']; export default Places;
JavaScript
0
@@ -1,24 +1,27 @@ import %7B +%0A autobind %7D from ' @@ -12,18 +12,19 @@ autobind -%7D +%0A%7D%0A from 'co @@ -169,16 +169,46 @@ akMap(); +%0Aconst SEARCH = new WeakMap(); %0A%0Aclass @@ -263,19 +263,38 @@ Object, -Aut +Utilities, Auth, Searc h, FURL) @@ -496,16 +496,78 @@ Auth);%0A + SEARCH.set(this, Search);%0A%0A this.Utilities = Utilities; %0A thi @@ -778,32 +778,1469 @@ $loaded();%0A %7D%0A%0A + @autobind%0A checkPlace(placeId, date, start, end) %7B%0A let errMessage = %7B%0A name: '',%0A message: ''%0A %7D;%0A start = this.Utilities.fixTime(date, start);%0A end = this.Utilities.fixTime(date, end);%0A%0A let response = new Promise((resolve, reject) =%3E %7B%0A SEARCH.get(this).searchReservacionByDate(date)%0A .then(reservas =%3E %7B%0A let reservasInPlace = reservas.filter(res =%3E res.place === placeId);%0A let filteredReservas = reservasInPlace.filter(res =%3E %7B%0A let answer;%0A if (start.isSame(res.starts) %7C%7C start.isBetween(res.starts, res.ends)) %7B%0A errMessage.name = 'START_AT_SAME_TIME';%0A errMessage.message = 'Both reservations has same or closer time';%0A answer = true;%0A %7D else if (start.isBefore(res.starts) && end.isAfter(res.starts)) %7B%0A errMessage.name = 'ENDS_TOO_LATE';%0A errMessage.message = 'Your reservation colides with other';%0A answer = true;%0A %7D else %7B%0A answer = false;%0A %7D%0A%0A return answer;%0A %7D);%0A if (filteredReservas.length) %7B%0A reject(%7B%0A data: filteredReservas,%0A message: errMessage%0A %7D);%0A %7D else %7B%0A resolve(%7B%0A data: %5B%5D,%0A message: 'No colitions found'%0A %7D);%0A %7D%0A %7D);%0A %7D);%0A%0A return response;%0A %7D%0A%0A @autobind%0A ge @@ -2373,24 +2373,31 @@ %7B%0A let %7B +%0A name, lastna @@ -2398,16 +2398,21 @@ lastname +%0A %7D = AUTH @@ -2847,16 +2847,23 @@ let %7B +%0A name, ca @@ -2878,16 +2878,21 @@ location +%0A %7D = newI @@ -3242,16 +3242,23 @@ update(%7B +%0A status: @@ -3267,16 +3267,21 @@ isabled' +%0A %7D);%0A %7D%0A @@ -3341,13 +3341,38 @@ ct', - 'Aut +%0A 'Utilities', 'Auth', 'Searc h',
f2f4754dd93901dbc68e716a0dca286ac2bd3783
remove external toolbar option, does not work with multiple editors
app/assets/javascripts/kuhsaft/cms/application.js
app/assets/javascripts/kuhsaft/cms/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require redactor //= require bootstrap //= require_tree . function loadTextEditor(elem){ elem.find(".js-editor").redactor({ toolbarExternal: "#toolbar" }) } $(function(){ loadTextEditor($("body")) }) $("body").ajaxSuccess(function(){ loadTextEditor($("body")) })
JavaScript
0
@@ -571,43 +571,8 @@ or(%7B -%0A toolbarExternal: %22#toolbar%22%0A %7D)%0A%7D
2cc73096360a064b446bb16e35986e80ccfa0854
Rename room to auction
app/viewmodels/shell.js
app/viewmodels/shell.js
define(['plugins/router', 'durandal/app', 'userContext', 'knockout'], function (router, app, userContext, ko) { router.searchText = ko.observable(''); var routes = { title: ko.observable(''), appTitle: app.title, router: router, searchBar: false, logout: function () { userContext.logout(); router.updateMenu(userContext.isLoggedIn()); router.navigate('login'); }, cancel: function () { router.navigateBack(); }, search: function () { app.showMessage('Search not yet implemented...'); }, navigate: function () { }, activate: function () { return router.activate(); }, toggleSearch: function() { this.searchBar = !this.searchBar; var search = document.querySelector('#search'); var input = document.querySelector('#search input'); if (this.searchBar) { search.setAttribute('show', ''); input.style.display = 'inline-block'; router.searchText(''); input.focus(); } else { search.removeAttribute('show'); input.style.display = 'none'; } } }; function computeMenu() { var showUserMenu = router.updateMenu(); var menu = [ {route: '', moduleId: 'viewmodels/landing', nav: false}, {route: 'home', title: 'Home', moduleId: 'viewmodels/landing', nav: !showUserMenu, icon: 'home'}, {route: 'login', title: 'Login', moduleId: 'viewmodels/login', nav: !showUserMenu, icon: 'account-circle'}, { route: 'registration', title: 'Registration', moduleId: 'viewmodels/registration', nav: !showUserMenu, icon: 'add-circle' }, {route: 'all', title: 'All auctions', moduleId: 'viewmodels/content', nav: showUserMenu, icon: "list"}, { route: 'myauctions', title: 'My auctions', moduleId: 'viewmodels/myauctions', nav: showUserMenu, icon: "grade" }, {route: 'logout', title: 'Logout', moduleId: 'viewmodels/logout', nav: showUserMenu, icon: "exit-to-app"}, {route: 'settings', title: 'Settings', moduleId: 'viewmodels/settings', nav: false, icon: "settings"}, {route: 'add', title: 'Add Auction', moduleId: 'viewmodels/add', nav: false, icon: "add"}, {route: 'room/:id', title: 'Room', moduleId: 'viewmodels/room', nav: false, icon: "info"} ]; router.reset(); router.map(menu).buildNavigationModel(); return menu; } router.updateMenu = ko.observable(userContext.isLoggedIn()); router.appMenu = ko.computed(computeMenu); router.selectedTab = ko.observable(0); router.showFullMenu = ko.observable(false); router.guardRoute = function (routeInfo, params) { routes.title(params.config.title); router.showFullMenu(userContext.isLoggedIn()); var routeMaps = router.navigationModel(); for (var i = 0; i < routeMaps.length; ++i) { if (routeMaps[i].route == params.fragment) { break; } } if (routeMaps.length == i) i = -1; if (params.fragment.indexOf('room/') != -1) i = -2; console.log(i); router.selectedTab(i); return true; }; return routes; });
JavaScript
0.998668
@@ -2660,12 +2660,15 @@ e: ' -Room +Auction ', m @@ -3504,32 +3504,8 @@ -2;%0A - console.log(i);%0A
e1078b2064782c1f5fe43916c489741e71d5172e
change local storage
misc/demo/js/controllers/demo.js
misc/demo/js/controllers/demo.js
'use strict'; var backAndControllers = angular.module('backAnd.controllers'); backAndControllers.controller('demoController', ['$scope', '$http', '$location', function ($scope, $http, $location) { var toQueryString = function(obj) { var parts = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i])); } } return parts.join("&"); } $scope.authentication = function () { var checkAuthenticationToken = function () { var request = $http({ method: 'POST', url: backandGlobal.url + "/api/banner", headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' } }); request.success(function (data, status, headers, config) { console.log(status); }); request.error(function (data, status, headers, config) { if (status == 401) { localStorage.removeItem('Authorization'); $location.path('/'); window.location.reload() } var error_description = "The server is busy. Please contact your administrator or try again later."; if (data && data.error_description) error_description = data.error_description; else { console.error(error_description, { data: data, status: status, headers: headers, config: config }) } $scope.loginError = error_description; console.log(status) $scope.waiting = false; }); } var token = localStorage['Authorization']; if (token) { $http.defaults.headers.common['Authorization'] = token; checkAuthenticationToken(); return; } $scope.loginError = ''; $scope.waiting = true; var data = toQueryString({ grant_type: "password", username: 'guest@backand.com', password: 'guest1234', appname: 'demoapp1', }); var request = $http({ method: 'POST', url: backandGlobal.url + "/token", data: data, headers: { 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded' } }); request.success(function (data, status, headers, config) { localStorage.setItem('Authorization', data.token_type + ' ' + data.access_token); $location.path('/'); window.location.reload() }); request.error(function (data, status, headers, config) { var error_description = "The server is busy. Please contact your administrator or try again later."; if (data && data.error_description) error_description = data.error_description; else { console.error(error_description, { data: data, status: status, headers: headers, config: config }) } $scope.loginError = error_description; console.log(status) $scope.waiting = false; }); } } ])
JavaScript
0
@@ -1255,16 +1255,20 @@ rization +Demo ');%0A @@ -2026,16 +2026,20 @@ rization +Demo '%5D;%0A @@ -2940,16 +2940,20 @@ rization +Demo ', data.
c7185daaa8dc6ef3a0cf8880464f404a2adeb776
Make filetype detection more agressive to work around false mime types
rtfHandler.js
rtfHandler.js
'use strict'; function getViewerURL(fileUrl) { return chrome.extension.getURL('viewer/viewer.html') + '?file=' + encodeURIComponent(fileUrl); } function contentTypeContains(contentType, string){ if(contentType.value.indexOf(string) > -1){ return true; } return false; } function isRtfFile(details) { var contentType = details.responseHeaders.find(function(element){ if(element.name.toLowerCase() === 'content-type'){ return element; } return false; }); if (contentType) { return (contentTypeContains(contentType, 'application/rtf') || contentTypeContains(contentType, 'text/rtf') || (contentTypeContains(contentType, 'text/plain') && details.url.endsWith('.rtf'))); } } chrome.webRequest.onHeadersReceived.addListener( function(details) { if (!isRtfFile(details)) { return; } return { redirectUrl: getViewerURL(details.url) }; }, { urls: ['<all_urls>'], types: ['main_frame', 'sub_frame'] }, ['blocking','responseHeaders'] ); chrome.webRequest.onBeforeRequest.addListener( function (details) { return { redirectUrl: getViewerURL(details.url) }; }, { urls: ['ftp://*/*.rtf'], types: ['main_frame', 'sub_frame'] }, ['blocking'] ); chrome.webRequest.onBeforeRequest.addListener( function (details) { return { redirectUrl: getViewerURL(details.url) }; }, { urls: ['file://*/*.rtf'], types: ['main_frame', 'sub_frame'] }, ['blocking'] );
JavaScript
0.000026
@@ -688,70 +688,33 @@ -(contentTypeContains(contentType, 'text/plain') && details.url +details.url.toLowerCase() .end @@ -727,17 +727,16 @@ '.rtf')) -) ;%0A %7D%0A
3c76706afdd2bffc04d6d4a19f6bdb789638c7cb
remove APPLICATION_INIT_TYPE
src/common/reducers/layout/index.js
src/common/reducers/layout/index.js
// @flow import { UI_OPEN_SIDEBAR, UI_CLOSE_SIDEBAR, UI_WINDOW_RESIZE } from 'actions/layout' import {LOCATION_CHANGE} from 'actions/common' // import type {LOCATION_CHANGE_TYPE, APPLICATION_INIT_TYPE} from 'actions/common' import type { UI_OPEN_SIDEBAR_TYPE, UI_CLOSE_SIDEBAR_TYPE, UI_WINDOW_RESIZE_TYPE } from 'actions/layout' export type State = { sidebarOpened: boolean, isMobile: boolean, isMobileXS: boolean, isMobileSM: boolean } type Action = | UI_OPEN_SIDEBAR_TYPE | UI_CLOSE_SIDEBAR_TYPE | UI_WINDOW_RESIZE_TYPE | LOCATION_CHANGE_TYPE | APPLICATION_INIT_TYPE export const initialState: State = { sidebarOpened: false, isMobile: false, isMobileXS: false, isMobileSM: false } export function layout (state: State = initialState, action: Action): State { const computeMobileStatuses = (innerWidth: number) => { const isMobile: boolean = innerWidth < 1025 // 1024px - is the main breakpoint in ui const isMobileXS: boolean = innerWidth < 481 const isMobileSM: boolean = innerWidth > 480 && innerWidth < 767 return {isMobileSM, isMobileXS, isMobile} } switch (action.type) { case UI_WINDOW_RESIZE: { const {innerWidth} = action.payload const mobileStates = computeMobileStatuses(innerWidth) return { ...state, ...mobileStates } } case UI_OPEN_SIDEBAR: return { ...state, sidebarOpened: true } case LOCATION_CHANGE: case UI_CLOSE_SIDEBAR: return { ...state, sidebarOpened: false } default: return state } }
JavaScript
0.000022
@@ -177,31 +177,8 @@ TYPE -, APPLICATION_INIT_TYPE %7D fr @@ -534,33 +534,8 @@ TYPE -%0A%09%7C APPLICATION_INIT_TYPE %0A%0Aex
3cd9713e0d32033e4fde7b1c351708f53672d2c4
Improve async request handling.
src/dataflow/load.js
src/dataflow/load.js
import {read} from 'vega-loader'; export function ingest(target, data, format) { return this.pulse(target, this.changeset().insert(read(data, format))); } function loadPending(df) { var pending = new Promise(function(accept) { resolve = accept; }), resolve; pending.requests = 0; pending.done = function() { if (--pending.requests === 0) { df.runAfter(function() { df._pending = null; df.run(); resolve(df); }); } } return (df._pending = pending); } export function request(target, url, format) { var df = this, pending = df._pending || loadPending(df); pending.requests += 1; df.loader() .load(url, {context:'dataflow'}) .then( function(data) { df.ingest(target, data, format); }, function(error) { df.warn('Loading failed: ' + url, error); pending.done(); }) .then(pending.done) .catch(function(error) { df.error(error); }); }
JavaScript
0
@@ -185,16 +185,38 @@ %7B%0A var +accept, reject,%0A pending @@ -243,52 +243,63 @@ on(a -ccept) %7B resolve = accept; %7D),%0A resolve +, r) %7B%0A accept = a;%0A reject = r;%0A %7D) ;%0A%0A @@ -447,16 +447,32 @@ = null;%0A + try %7B%0A @@ -493,20 +493,78 @@ -resolve(df); + accept(df);%0A %7D catch (err) %7B%0A reject(err);%0A %7D %0A @@ -1055,31 +1055,24 @@ r) %7B -%0A df.error + df.warn (error); %0A @@ -1067,19 +1067,15 @@ (error); -%0A %7D);%0A%7D%0A
5f414965ba5067e261779ceadd7a144bab918eb1
fix little input field bug
app/assets/javascripts/uploads/uploadImageCtrl.js
app/assets/javascripts/uploads/uploadImageCtrl.js
var app = angular.module('annaPhotography'); app.controller('UploadImageCtrl', [ '$scope', 'galleries', 'gallery', 'Upload', '$stateParams', function($scope, galleries, gallery, Upload, $stateParams){ $scope.gallery = gallery; $scope.images = galleries.images; $scope.coverBool = false; $scope.galleries = galleries.galleries; function isCoverImage(image) { return image.cover_image === true } $scope.coverImage = $scope.images.find(isCoverImage) $scope.updateGallery = function(){ if(!$scope.title || $scope.title === '') {return;} galleries.update((gallery.id), { title: $scope.title, }).success(function(data){ gallery.title = data.title; }); $scope.title = ''; }; $scope.upload = function(file){ Upload.upload({ url: '/galleries/' + gallery.id + '/images.json', method: 'POST', fields: { 'image[gallery_id]': gallery.id, 'image[cover_image]': $scope.coverBool, 'image[image]': file }, file: file, }).success(function(data){ $scope.images = data; }); }; $scope.removeImage = function(index){ var objectToDelete = $scope.images[index]; if(confirm("Are you sure you want to delete this photo?")){ galleries.deleteImg(objectToDelete.id, gallery.id) .success(function(data){ $scope.images = data; }); }; }; $scope.makeCoverImage = function(index){ var newCoverImage = $scope.images[index]; if(confirm("Are you sure you want to make this the cover image?")){ galleries.updateCoverImage(newCoverImage.id, gallery.id) .success(function(data){ $scope.coverImage = data; }); }; }; }]);
JavaScript
0.000001
@@ -737,33 +737,8 @@ %7D);%0A - $scope.title = '';%0A
e27600b036531be98593688f50a4d8da22b79356
add newrelic to social worker
workers/social/index.js
workers/social/index.js
require('coffee-script'); module.exports = require('./lib/social/main.coffee');
JavaScript
0.000185
@@ -19,16 +19,37 @@ ript');%0A +require('newrelic');%0A module.e @@ -93,8 +93,9 @@ offee'); +%0A
eadb8f6603c3760fc468afc37497b0edd06bdc70
Remove TODO - callback payload format should stay.
src/components/EditableDiv.react.js
src/components/EditableDiv.react.js
import R from 'ramda'; import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; // each suite might have its own set of Styles import Styles from '../Styles'; const baseStyles = { color: Styles.colors.base, ':hover': { color: Styles.colors.baseHover } }; /** * A div for displaying text. The text is editable. */ export default class EditableDiv extends Component { constructor(props) { super(props); this.state = { inEditMode: false }; } componentDidUpdate() { if (this.state.inEditMode) { ReactDOM.findDOMNode(this.refs.input).focus(); } } // TODO: Standardize on `{value}` as payload to `handleChange()`. handleChange(text) { this.props.valueChanged({text}); } render() { if (this.state.inEditMode) { return ( <div> <input ref="input" autofocus={true} style={R.mergeAll([ {border: 'none', padding: 0, margin: 0}, baseStyles, this.props.style ])} value={this.props.text} onChange={(e) => this.handleChange(e.target.value)} onBlur={() => this.setState({inEditMode: false})} /> </div> ) } else { return ( <div style={R.merge(baseStyles, this.props.style)} onClick={() => { if (this.props.editable) this.setState({inEditMode: true}) }} > {this.props.text} </div> ) } } } EditableDiv.propTypes = { /** * The displayed text of this component. */ text: PropTypes.string.isRequired, /** * The style of the text. */ style: PropTypes.object, /** * Whether or not this component should be rendered as editable. * Passed in from renderer. */ editable: PropTypes.bool, /** * Function that updates the state tree. */ valueChanged: PropTypes.func }; EditableDiv.defaultProps = { style: {}, editable: false, valueChanged: () => {} };
JavaScript
0
@@ -676,78 +676,8 @@ %7D%0A%0A - // TODO: Standardize on %60%7Bvalue%7D%60 as payload to %60handleChange()%60.%0A
9f2b2116615ab97fde1bef8284779ba024679698
add type to next.config file
next.config.js
next.config.js
// eslint-disable-next-line @typescript-eslint/no-var-requires const withPWA = require('next-pwa'); const isProd = process.env.NODE_ENV === 'production'; module.exports = withPWA({ pwa: { dest: 'public', disable: !isProd, }, });
JavaScript
0.000001
@@ -93,16 +93,17 @@ -pwa');%0A +%0A const is @@ -149,16 +149,61 @@ tion';%0A%0A +/**%0A * @type %7Bimport('next').NextConfig%7D%0A */%0A module.e