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
518b87bdcbc286d61b267ac785771b54cb6eccf5
Fix coinbase pinned old certificate
src/sources/coinbase.js
src/sources/coinbase.js
const assert = require('assert'); const { Client } = require('coinbase'); const { Account, Transaction } = require('../models'); const { FIAT_CURRENCIES } = require('../helpers'); function callAsync(client, method, ...args) { return new Promise((resolve, reject) => { client[method].call(client, ...args, (err, body, pagination) => { if (err) { reject(err); } else { resolve({ body, pagination }); } }); }); } module.exports = async function importCoinbase(config) { // create coinbase client const client = new Client({ apiKey: config.apiKey, apiSecret: config.apiSecret, }); // cache users to speed things up const userMap = {}; async function getUser(userId) { if (userMap[userId] === undefined) { userMap[userId] = (await callAsync(client, 'getUser', userId)).body; } return userMap[userId]; } const user = await callAsync(client, 'getCurrentUser'); console.log(`\nImporting Coinbase user ${user.body.name} (${user.body.email})`); const { email } = user.body; assert.ok(email, 'User email is missing, please check API key permissions.'); const accounts = await callAsync(client, 'getAccounts', {}); for (const a of accounts.body) { // skip fiat accounts if (FIAT_CURRENCIES.includes(a.currency)) { continue; } console.log('\nImporting:', a.name); const userAccount = (await Account.findOrBuild({ where: { source: 'coinbase', reference: a.id, }, }))[0]; userAccount.name = `${a.name} (${email})`; userAccount.currency = a.currency; await userAccount.save(); let pagination = null; while (pagination === null || pagination.next_uri) { const txns = await callAsync(a, 'getTransactions', pagination); ({ pagination } = txns); for (const t of txns.body) { // skip transactions before importStartDate if (Date.parse(t.created_at) < config.importStartDate) { process.stdout.write('.'); continue; } process.stdout.write('+'); if (t.status !== 'completed') { continue; } // console.log(t.type, t.amount.amount, t.amount.currency, t.created_at); const other = t.from || t.to || {}; let sourceAddress = other.resource; if (other.resource === 'bitcoin_address') { sourceAddress = `${sourceAddress}(${other.address})`; } else if (other.resource === 'user') { const otherUser = await getUser(other.id); sourceAddress = `${sourceAddress}(${otherUser.name || other.id})`; } else if (other.id) { sourceAddress = `${sourceAddress}(${other.id})`; } const transaction = (await Transaction.findOrBuild({ where: { accountId: userAccount.id, reference: t.id, }, }))[0]; transaction.type = (t.amount.amount < 0 ? 'send' : 'receive'); transaction.source = userAccount.source; transaction.sourceType = t.type; transaction.sourceAddress = sourceAddress; transaction.sourceDescription = t.description; transaction.sourceAmount = t.amount.amount; transaction.amount = transaction.sourceAmount; transaction.currency = userAccount.currency; transaction.timestamp = t.created_at; if (t.native_amount.currency === 'USD') { transaction.usdValue = Math.abs(t.native_amount.amount); } // mark transfers so we can reconcile them later if (other.resource === 'account' || t.type === 'exchange_deposit' || t.type === 'exchange_withdrawal' || t.type === 'transfer' || t.type === 'vault_withdrawal') { transaction.type = 'transfer'; } await transaction.save(); const updateExchange = (type, exchange) => { transaction.type = type; transaction.exchangeReference = exchange.id; transaction.exchangeValue = exchange.total.amount; transaction.exchangeCurrency = exchange.total.currency; // timestamp should reflect trade date transaction.timestamp = exchange.created_at; return transaction.save(); }; if (t.type === 'buy') { const buy = (await callAsync(a, 'getBuy', t.buy.id)).body; await updateExchange('buy', buy); } if (t.type === 'sell') { const sell = (await callAsync(a, 'getSell', t.sell.id)).body; await updateExchange('sell', sell); } } } } };
JavaScript
0
@@ -627,16 +627,34 @@ Secret,%0A + caFile: null,%0A %7D);%0A%0A
7b8f8af9be7b3606a42de12a67cea074a167115b
update drawify
client/drawify.js
client/drawify.js
// Bookmarklet helper to create a canvas to draw on within the next clicked element // - assumes Drawing is already defined function drawify(event) { window.removeEventListener('click', drawify); var canvas = document.createElement('canvas'); canvas.width = window.DRAWING_WIDTH || 600; canvas.height = window.DRAWING_HEIGHT || 400; canvas.style.background = 'white'; canvas.style.cursor = 'pointer'; event.target.appendChild(canvas); // This goes nowhere... return new Drawing(canvas); } window.addEventListener('click', drawify);
JavaScript
0.000001
@@ -134,16 +134,60 @@ drawify( +socket, our_id) %7B%0A function make_drawing( event) %7B @@ -191,16 +191,20 @@ ) %7B%0A + + window.r @@ -235,19 +235,28 @@ k', +make_ drawi -fy +ng );%0A%0A + @@ -303,24 +303,28 @@ vas');%0A%0A + + canvas.width @@ -355,24 +355,28 @@ %7C%7C 600;%0A + + canvas.heigh @@ -409,24 +409,28 @@ %7C%7C 400;%0A + + canvas.style @@ -452,24 +452,28 @@ white';%0A + + canvas.style @@ -498,16 +498,20 @@ ';%0A%0A + + event.ta @@ -533,24 +533,28 @@ d(canvas);%0A%0A + // This @@ -573,16 +573,20 @@ ...%0A + + return n @@ -606,13 +606,37 @@ nvas -);%0A%7D%0A +, socket, our_id);%0A %7D%0A wind @@ -668,14 +668,21 @@ k', +make_ drawi -fy +ng );%0A +%7D%0A
97bd51d572c96522f8f89470daa18f4f97ddf94e
Simplify stringToColor;
client/helpers.js
client/helpers.js
/* * HELPERS */ const DEBUG = true; const ASSERTS = true; export function debug() { DEBUG && console.log.apply(console, arguments); }; export function assert(x, wat) { if (!x) { var text = 'Assertion error: ' + (wat?wat:'') + '\n' + new Error().stack; ASSERTS && alert(text); console.log(text); return false; } return true; }; export function maybeHas(obj, prop) { return obj && obj.hasOwnProperty(prop); } export function has(obj, prop, wat) { return assert(maybeHas(obj, prop), wat || ('object should have property ' + prop)); } export function NYI() { throw 'Not yet implemented'; } export const NONE_CATEGORY_ID = '-1'; var translator = null; var alertMissing = null; export function setTranslator(polyglotInstance) { translator = polyglotInstance.t.bind(polyglotInstance); } export function setTranslatorAlertMissing(bool) { alertMissing = bool; } export function translate(format, bindings) { bindings = bindings || {}; bindings['_'] = ''; let ret = translator(format, bindings); if (ret === '' && alertMissing) { console.log(`Missing translation key for "${format}"`); return format; } return ret; } export var compareLocale = (function() { if (typeof Intl !== 'undefined' && typeof Intl.Collator !== 'undefined') { let cache = new Map; return function(a, b, locale) { if (!cache.has(locale)) { cache.set(locale, new Intl.Collator(locale, { sensitivity: 'base' })); } return cache.get(locale).compare(a, b); } } if (typeof String.prototype.localeCompare === 'function') { return function(a, b, locale) { return a.localeCompare(b, locale, { sensitivity : 'base' }); } } return function(a, b, locale) { let af = a.toLowerCase(); let bf = b.toLowerCase(); if (af < bf) return -1; if (af > bf) return 1; return 0; } })(); export function stringToColor(str) { let hash = 0; let color = '#'; // String to hash for (let i = 0, size = str.length; i < size; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); } // Int/hash to hex for (let i = 0; i < 3; i++) { color += ('00' + ((hash >> i * 8) & 0xFF).toString(16)).slice(-2); } return color; }
JavaScript
0.000102
@@ -2300,24 +2300,15 @@ -color += ('00' + +let s = ((h @@ -2345,19 +2345,67 @@ (16) -).slice(-2) +;%0A while (s.length %3C 2) s += '0';%0A color += s ;%0A
c223e1945f122ffe1a64e60ea7d0313ae7b2a2b7
make listeners drop on disconnect (they won't work anymore anyway)
lib/ircwrap.js
lib/ircwrap.js
var irc = require('irc') var IRC_METHODS = 'join part say whois action notice on'.split(' ') // userid -> client mapping var clients = {} function getClient(userid, cb) { if (clients.hasOwnProperty(userid)) return cb(null, clients[userid]) makeClient(userid, function(err, client) { if (err) cb(err) client = wrapClient(client) clients[userid] = client cb(null, client) }) } function makeClient(userid, cb) { var client = new irc.Client('irc.freenode.net', userid, { userName: 'ircbird-'+userid , realName: 'ircbird' , channels: [] }) client.on('connect', function() { cb(null, client) }) } function wrapClient(client) { var wrapper = {} IRC_METHODS.forEach(function(method) { wrapper[method] = function() { client[method].apply(client, arguments) } }) // we don't want disconnects or so to kill the process client.on('error', function(){}) return wrapper } module.exports = getClient
JavaScript
0
@@ -75,11 +75,8 @@ tice - on '.sp @@ -812,16 +812,247 @@ %7D%0A %7D)%0A + // when the browser disconnects, its listeners should be removed%0A wrapper.on = function(type, listener) %7B%0A client.on(type, listener)%0A this.conn.on('end', function() %7B%0A client.removeListener(type, listener)%0A %7D)%0A %7D%0A // we
f620bf015a2015f75b0787d6327f1af525d97544
Fix ESLint violations in logger
lib/logging.js
lib/logging.js
const fs = require('fs'); const winston = require('winston'); const { createLogger, format, transports } = winston; const logger = createLogger({ format: format.combine( format.timestamp(), format.simple() ), transports: [ new transports.Console({ format: format.combine( format.timestamp(), format.colorize(), format.simple() ), }), new transports.Stream({ stream: fs.createWriteStream('./omnium.log'), }), ], }); module.exports = logger;
JavaScript
0.000062
@@ -62,17 +62,16 @@ %0Aconst %7B - createLo @@ -94,17 +94,16 @@ ansports - %7D = wins
1da174cf9cccd9dd7e562bbb565592de5f531f43
Add sentinel constant in client request library
client/request.js
client/request.js
var Request = { _img: null, make(url, callback) { console.log('Making request to ' + url); this._img = new Image(); this._img.onerror = callback; this._img.src = url; }, cancel() { this._img.src = ''; } }; var Collection = { _ONE_REQUEST_DEFAULT_TIMEOUT: 5000, create(url, {amount, alignmentalphabet, oneRequestTimeout}, onOneSuccess, onAllSuccess, onError) { var requests = []; var loadingTimeout; var loadedCount = 0; if (oneRequestTimeout === 0) { throw 'oneRequestTimeout should not be zero'; } oneRequestTimeout = oneRequestTimeout || this._ONE_REQUEST_DEFAULT_TIMEOUT; console.log('Creating request collection of ' + amount + ' requests to URL: ' + url); console.log('Using one request time out value of ' + oneRequestTimeout); const resetTimeout = () => { clearTimeout(loadingTimeout); loadingTimeout = setTimeout(() => { for (var i = 0; i < amount; ++i) { requests[i].cancel(); } clearTimeout(loadingTimeout); onError(); }, oneRequestTimeout); }; const allCompleted = () => { clearTimeout(loadingTimeout); onAllSuccess(); }; const oneLoaded = (index) => { console.log(); resetTimeout(); console.log('Completed request: ' + index); ++loadedCount; onOneSuccess(index); if (loadedCount == amount) { allCompleted(); } }; antiBrowserCaching = Math.random() * Number.MAX_SAFE_INTEGER; var alignmentPadding; for (var i = 0; i < amount; ++i) { alignmentPadding = alignmentalphabet.substr(0, i % 16); var request = Request.make(url + alignmentPadding + '&' + (antiBrowserCaching + i), oneLoaded.bind({}, i)); requests.push(request); } } }; module.exports = {Request, Collection};
JavaScript
0.000001
@@ -320,16 +320,36 @@ : 5000,%0A + _SENTINEL: '%5E',%0A crea
1d00ac5fb8d8ff5e2fbb7a5b2631ec90311a02ab
Add state value for example
example/App.js
example/App.js
import React, { Component } from 'react' import { StyleSheet, StatusBar, View, Text, ScrollView } from 'react-native' import TextInput from 'react-native-material-textinput' export default class App extends Component { render() { return ( <View style={styles.layout}> <StatusBar backgroundColor="#1a237e" barStyle="light-content" /> <View style={styles.header}> <Text style={styles.headerText}>Material Design Text Fields</Text> </View> <ScrollView contentContainerStyle={styles.container}> <TextInput label="Product name" /> <TextInput label="Price" placeholder="$5,999.00" /> <TextInput label="The Matrix" value="A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers." multiline minHeight={150} /> </ScrollView> </View> ) } } const styles = StyleSheet.create({ layout: { flex: 1, backgroundColor: 'white' }, header: { justifyContent: 'flex-end', height: 100, padding: 16, backgroundColor: '#3f51b5' }, headerText: { color: 'white', fontSize: 20, fontWeight: 'bold' }, container: { padding: 16 } })
JavaScript
0.000002
@@ -219,18 +219,292 @@ %7B%0A -render() %7B +state = %7B%0A productName: '',%0A price: '',%0A multilineText:%0A 'A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.'%0A %7D%0A%0A render() %7B%0A let %7B productName, price, multilineText %7D = this.state%0A %0A @@ -825,32 +825,44 @@ %3CTextInput +%0A label=%22Product @@ -866,16 +866,131 @@ ct name%22 +%0A value=%7BproductName%7D%0A onChangeText=%7BproductName =%3E this.setState(%7B productName %7D)%7D%0A /%3E%0A @@ -1005,16 +1005,28 @@ extInput +%0A label=%22 @@ -1031,16 +1031,28 @@ =%22Price%22 +%0A placeho @@ -1071,217 +1071,271 @@ .00%22 - /%3E%0A %3CTextInput%0A label=%22The Matrix%22%0A value=%22A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.%22 +%0A value=%7Bprice%7D%0A onChangeText=%7Bprice =%3E this.setState(%7B price %7D)%7D%0A /%3E%0A %3CTextInput%0A label=%22The Matrix%22%0A value=%7BmultilineText%7D%0A onChangeText=%7BmultilineText =%3E this.setState(%7B multilineText %7D)%7D %0A
4f62fbf159e433104238306263ba5eeff911dcf6
use forEach for load required step modules
lib/manager.js
lib/manager.js
/* jslint node: true, esnext: true */ "use strict"; const fs = require('fs'), path = require('path'), koa = require('koa'), route = require('koa-route'), jwt = require('koa-jwt'), websockify = require('koa-websocket'); exports.defaultKronosPort = 10000; exports.manager = function (manager, options) { return manager.then(function (manager) { if (!options) { options = {}; } require('kronos-flow').registerWithManager(manager); require('kronos-http-routing-step').registerWithManager(manager); require('kronos-flow-control-step').registerWithManager(manager); const port = options.port || exports.defaultKronosPort; const app = websockify(koa()); manager.app = app; const hc = require('./controllers/health').initialize(manager); app.use(route.get('/health', hc.status)); /* const auth = require('./controllers/auth').initialize(manager); app.use(route.get('/auth', auth.get)); */ // secure all the following requests if jwt is present if (options.jwt) { app.use(jwt({ secret: options.jwt.secret })); } const sc = require('./controllers/state').initialize(manager); app.use(route.get('/state', sc.list)); app.ws.use(route.all('/state', sc.ws)); const fc = require('./controllers/flow').initialize(manager); app.use(route.get('/flows', fc.list)); app.use(route.get('/flows/:id', fc.fetch)); app.use(route.delete('/flows/:id', fc.delete)); app.use(route.post('/flows', fc.insert)); app.use(route.post('/flows/:id/start', fc.start)); app.use(route.post('/flows/:id/stop', fc.stop)); app.ws.use(route.all('/flows', fc.ws)); manager.httpServerPort = port; manager.httpServer = app.listen(port); const protoShutdown = manager.shutdown; manager = Object.create(manager, { controller: { value: {} }, shutdown: { value: function () { const m = this; return Promise.all([protoShutdown(), new Promise(function (resolve, reject) { m.httpServer.close(function (error) { if (error) { reject(error); } else { delete m.app; delete m.httpServer; resolve(manager); } }); })]); } }, toString: { value: function () { return `${this.name}(${this.httpServerPort})`; } } }); // load and start admin flow return new Promise(function (resolve, reject) { fs.readFile(path.join(__dirname, '..', 'admin.flow'), { encoding: 'utf8' }, function (err, data) { if (err) { reject(err); return; } try { manager.registerFlow(manager.getStepInstance(JSON.parse(data))).then(flow => flow.start()); } catch (err) { reject(err); return; } resolve(manager); }); }); //return Promise.resolve(manager); }); };
JavaScript
0.000001
@@ -399,32 +399,25 @@ %0A %7D%0A%0A -require( +%5B 'kronos-flow @@ -421,148 +421,101 @@ low' -).registerWithManager(manager);%0A require('kronos-http-routing-step').registerWithManager(manager);%0A require('kronos-flow-control-step' +, 'kronos-http-routing-step', 'kronos-flow-control-step'%5D.forEach(name =%3E require(%0A name ).re @@ -540,16 +540,17 @@ manager) +) ;%0A%0A c
c7f8fb297c28c9b0664c7c40f9ea06ad8ffd59da
Set Content-Type header on requests.
lib/request.js
lib/request.js
define(['./errors/bosherror', 'xml', 'ajax', 'events', 'class', 'debug'], function(BOSHError, xml, ajax, Emitter, clazz, debug) { debugrxd = debug('bosh:rx:data'); debugtxd = debug('bosh:tx:data'); function Request(url, body, fn) { Emitter.call(this); this.rid = body.attr('rid'); this.payloadCount = body.children().length; this.fn = fn; this.statusType = undefined; this.statusCondition = undefined; this.response = undefined; this._url = url; this._data = body.toString(); this._req = null; } clazz.inherits(Request, Emitter); // TODO: Set content-type to text/xml; charset=utf-8 on Ajax requests Request.prototype.send = function() { var self = this , req = ajax.request(this._url, 'POST'); this._req = req; req.on('response', function(res) { res.on('end', function() { debugrxd('status: ' + res.statusCode); debugrxd(res.responseText); if (res.statusCode == 200) { var body; try { body = self.response = xml(res.responseXML); } catch(err) { self.emit('error', err); return; } if (!body.is('body', 'http://jabber.org/protocol/httpbind')) { self.emit('error', new BOSHError('Bad protocol')); return; } self.statusType = body.attr('type'); self.statusCondition = body.attr('condition') || 'ok'; self.emit('end'); } else { var cond = 'internal-server-error'; switch (res.statusCode) { case 400: cond = 'bad-request'; break; case 403: cond = 'policy-violation'; break; case 404: cond = 'item-not-found'; break; } self.statusType = 'terminate'; self.statusCondition = cond; self.emit('end'); } }); res.on('error', function(err) { self.emit('error', err); }); }); req.on('error', function(err) { self.emit('error', err); }); debugtxd(this._data); req.send(this._data); } Request.prototype.abort = function() { this._req.abort(); } return Request; });
JavaScript
0
@@ -628,83 +628,8 @@ %0A %0A - // TODO: Set content-type to text/xml; charset=utf-8 on Ajax requests%0A %0A Re @@ -2172,16 +2172,78 @@ _data);%0A + req.setHeader('Content-Type', 'text/xml; charset=utf-8');%0A req.
8d0b0a4ace229d1dec23d9dee2f6210a578c73e4
consolidate conditions
lib/methods.js
lib/methods.js
// Load modules var Boom = require('boom'); var Utils = require('./utils'); var Schema = require('./schema'); // Declare internals var internals = {}; exports = module.exports = internals.Methods = function (pack) { this.pack = pack; this.methods = {}; }; internals.Methods.prototype.add = function (/* name, fn, options, env | {}, env | [{}, {}], env */) { if (typeof arguments[0] === 'string') { return internals.Methods.prototype._add.apply(this, arguments); } var items = [].concat(arguments[0]); var env = arguments[1]; for (var i = 0, il = items.length; i < il; ++i) { var item = items[i]; this._add(item.name, item.fn, item.options, env); } }; exports.methodNameRx = /^[a-zA-Z]\w*(?:\.[a-zA-Z]\w*)*$/; internals.Methods.prototype._add = function (name, fn, options, env) { var self = this; Utils.assert(typeof fn === 'function', 'fn must be a function'); Utils.assert(typeof name === 'string', 'name must be a string'); Utils.assert(name.match(exports.methodNameRx), 'Invalid name:', name); Utils.assert(!Utils.reach(this.methods, name, { functions: false }), 'Server method function name already exists'); var options = options || {}; var schemaError = Schema.method(options); Utils.assert(!schemaError, 'Invalid method options for', name, ':', schemaError); var settings = Utils.clone(options); settings.generateKey = settings.generateKey || internals.generateKey; var bind = settings.bind || (env && env.bind) || null; // Create method var cache = null; if (settings.cache) { cache = this.pack._provisionCache(settings.cache, 'method', name, settings.cache.segment); } var method = function (/* arguments, methodNext */) { if (!cache) { return fn.apply(bind, arguments); } var args = arguments; var lastArgPos = args.length - 1; var methodNext = args[lastArgPos]; var generateFunc = function (next) { args[lastArgPos] = next; // function (err, result, ttl) fn.apply(bind, args); }; var key = settings.generateKey.apply(bind, args); if (key === null) { // Value can be '' self.pack.log(['hapi', 'method', 'key', 'error'], { name: name, args: args }); } else if (typeof key !== 'string') { self.pack.log(['hapi', 'method', 'key', 'error'], { name: name, args: args, key: key }); key = null; } cache.getOrGenerate(key, generateFunc, methodNext); }; if (cache) { method.cache = { drop: function (/* arguments, callback */) { var dropCallback = arguments[arguments.length - 1]; var key = settings.generateKey.apply(null, arguments); if (key === null) { // Value can be '' return Utils.nextTick(dropCallback)(Boom.badImplementation('Invalid method key')); } return cache.drop(key, dropCallback); } }; } // create method path var path = name.split('.'); var ref = this.methods; for (var i = 0, il = path.length; i < il; ++i) { if (!ref[path[i]]) { ref[path[i]] = (i + 1 === il ? method : {}); } ref = ref[path[i]]; } }; internals.generateKey = function () { var key = 'h'; for (var i = 0, il = arguments.length - 1; i < il; ++i) { // 'arguments.length - 1' to skip 'next' var arg = arguments[i]; if (typeof arg !== 'string' && typeof arg !== 'number' && typeof arg !== 'boolean') { return null; } key += ':' + encodeURIComponent(arg.toString()); } return key; };
JavaScript
0.000005
@@ -2222,32 +2222,59 @@ if (key === null + %7C%7C typeof key !== 'string' ) %7B @@ -2312,153 +2312,8 @@ ''%0A - self.pack.log(%5B'hapi', 'method', 'key', 'error'%5D, %7B name: name, args: args %7D);%0A %7D%0A else if (typeof key !== 'string') %7B%0A
be2d77c624219c798ce942df92150b1cb096c41c
Add support for automatic title fetch in linkified issues (#1059)
source/features/linkify-urls-in-code.js
source/features/linkify-urls-in-code.js
import select from 'select-dom'; import linkifyUrls from 'linkify-urls'; import linkifyIssues from 'linkify-issues'; import {getOwnerAndRepo} from '../libs/page-detect'; import getTextNodes from '../libs/get-text-nodes'; export const linkifiedURLClass = 'rgh-linkified-code'; const { ownerName, repoName } = getOwnerAndRepo(); const options = { user: ownerName, repo: repoName, type: 'dom', baseUrl: '', attributes: { class: linkifiedURLClass // Necessary to avoid also shortening the links } }; export const editTextNodes = (fn, el) => { // Spread required because the elements will change and the TreeWalker will break for (const textNode of [...getTextNodes(el)]) { if (fn === linkifyUrls && textNode.textContent.length < 11) { // Shortest url: http://j.mp continue; } const linkified = fn(textNode.textContent, options); if (linkified.children.length > 0) { // Children are <a> textNode.replaceWith(linkified); } } }; export default () => { const wrappers = select.all(`.blob-wrapper:not(.${linkifiedURLClass})`); // Don't linkify any already linkified code if (wrappers.length === 0) { return; } // Linkify full URLs // `.blob-code-inner` in diffs // `pre` in GitHub comments for (const el of select.all('.blob-code-inner, pre', wrappers)) { editTextNodes(linkifyUrls, el); } // Linkify issue refs in comments for (const el of select.all('span.pl-c', wrappers)) { editTextNodes(linkifyIssues, el); } // Mark code block as touched for (const el of wrappers) { el.classList.add(linkifiedURLClass); } };
JavaScript
0
@@ -215,16 +215,77 @@ odes';%0A%0A +// Shared class necessary to avoid also shortening the links%0A export c @@ -331,16 +331,17 @@ -code';%0A +%0A const %7B%0A @@ -469,102 +469,8 @@ : '' -,%0A%09attributes: %7B%0A%09%09class: linkifiedURLClass // Necessary to avoid also shortening the links%0A%09%7D %0A%7D;%0A @@ -810,16 +810,16 @@ tions);%0A - %09%09if (li @@ -869,16 +869,547 @@ are %3Ca%3E%0A +%09%09%09if (fn === linkifyIssues) %7B%0A%09%09%09%09// Enable native issue title fetch%0A%09%09%09%09for (const link of linkified.children) %7B%0A%09%09%09%09%09const issue = link.href.split('/').pop();%0A%09%09%09%09%09link.setAttribute('class', %60issue-link js-issue-link tooltipped tooltipped-ne $%7BlinkifiedURLClass%7D%60);%0A%09%09%09%09%09link.setAttribute('data-error-text', 'Failed to load issue title');%0A%09%09%09%09%09link.setAttribute('data-permission-text', 'Issue title is private');%0A%09%09%09%09%09link.setAttribute('data-url', link.href);%0A%09%09%09%09%09link.setAttribute('data-id', %60rgh-issue-$%7Bissue%7D%60);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A %09%09%09textN
a368c8eebf04c0841eaee06d423cade54a2cc4e9
Add s3 ui mode to builds
lib/modules.js
lib/modules.js
// Fine Uploader's modules // // shamelessly inspired by: // https://github.com/angular/angular.js/blob/master/angularFiles.js var fineUploaderModules = { // Pre-defined forumlae "fuTraditional": [ "@fuSrcCore", "@fuSrcUi", "@fuSrcTraditional", "@fuSrcModules", "@fuUiModules" ], "fuS3": [ "@fuSrcCore", "@fuSrcUi", "@fuSrcS3", "@fuSrcModules", "@fuUiModules" ], "fuTraditionalJquery": [ "@fuTraditional", "@fuSrcJquery", "@fuSrcJqueryDnd" ], "fuS3Jquery": [ "@fuS3", "@fuSrcS3Jquery", "@fuSrcJqueryDnd" ], "fuAll": [ "@fuTraditionalJquery", "@fuSrcS3", "@fuSrcS3Jquery", ], // Groups "fuSrcModules": [ "@fuPasteModule", "@fuDndModule", "@fuDeleteFileModule", "@fuImagePreviewModule" ], "fuUiModules": [ "@fuUiEvents", "@fuDeleteFileUiModule", "@fuEditFilenameModule" ], // Source "fuSrcCore": [ "client/js/util.js", "client/js/version.js", "client/js/features.js", "client/js/promise.js", "client/js/button.js", "client/js/upload-data.js", "client/js/uploader.basic.api.js", "client/js/uploader.basic.js", "client/js/ajax.requester.js", "client/js/handler.base.js", "client/js/handler.form.api.js", "client/js/handler.xhr.api.js", "client/js/window.receive.message.js" ], "fuSrcUi": [ "client/js/uploader.api.js", "client/js/uploader.js", "client/js/templating.js" ], "fuSrcTraditional": [ "client/js/traditional/handler.form.js", "client/js/traditional/handler.xhr.js" ], "fuSrcJquery": [ "client/js/jquery-plugin.js", ], "fuSrcS3": [ "client/js/s3/util.js", "client/js/s3/uploader.basic.js", "client/js/s3/signature.ajax.requester.js", "client/js/s3/uploadsuccess.ajax.requester.js", "client/js/s3/multipart.initiate.ajax.requester.js", "client/js/s3/multipart.complete.ajax.requester.js", "client/js/s3/multipart.abort.ajax.requester.js", "client/js/s3/handler.form.js", "client/js/s3/handler.xhr.js", ], "fuSrcS3Ui": [ "client/js/s3/uploader.js", ], "fuSrcS3Jquery": [ "@fuSrcJquery", "client/js/s3/jquery-plugin.js" ], "fuImagePreviewModule": [ "client/js/third-party/megapix-image.js", "client/js/image.js", "client/js/exif.js", "client/js/identify.js" ], "fuPasteModule": [ "client/js/paste.js" ], "fuDndModule" : [ "client/js/dnd.js" ], "fuSrcJqueryDnd": [ "client/js/jquery-dnd.js" ], "fuDeleteFileModule": [ "client/js/deletefile.ajax.requester.js" ], "fuUiEvents": [ "client/js/ui.handler.events.js", ], "fuDeleteFileUiModule": [ "client/js/ui.handler.click.drc.js" ], "fuEditFilenameModule": [ "client/js/ui.handler.click.filename.js", "client/js/ui.handler.focusin.filenameinput.js", "client/js/ui.handler.focus.filenameinput.js", "client/js/ui.handler.edit.filename.js" ], "fuIframeXssResponse": [ "client/js/iframe.xss.response.js" ], "fuExtra": [ "@fuImages", "@fuCss", "@fuDocs", "@fuTemplates" ], "fuTemplates": [ "client/html/templates/default.html", "client/html/templates/simple-thumbnails.html" ], "fuImages": [ "client/loading.gif", "client/processing.gif", "client/edit.gif", ], "fuPlaceholders": [ "client/placeholders/not_available-generic.png", "client/placeholders/waiting-generic.png" ], "fuCss": [ "client/fineuploader.css", ], "fuDocs": [ "README.md", "LICENSE" ], "versioned": [ "package.json", "fineuploader.jquery.json", "client/js/version.js", "bower.json", "README.md" ], "fuUnit": [ "test/static/helpme.js", "test/unit/*.js", "test/unit/s3/*.js" ], "fuFunctional": [ "test/functional/**/*.coffee" ], "karmaModules": [ "test/static/karma-runner.js", "test/_vendor/assert/assert.js", "test/_vendor/jquery/jquery.js", "test/_vendor/jquery.simulate/jquery.simulate.js", "test/_vendor/json2/json2.js", "test/_vendor/purl/purl.js" ], "fuSrcBuild": [ "_build/all!(@(*.min.js|*.gif|*.css))" ] }; if (exports) { var mergeModules = function() { var files = []; Array.prototype.slice.call(arguments, 0).forEach(function(filegroup) { fineUploaderModules[filegroup].forEach(function(file) { // replace @ref var match = file.match(/^\@(.*)/); if (match) { files = files.concat(mergeModules(match[1])); //files = files.concat(fineUploaderModules[match[1]]); } else { files.push(file); } }); }); return files; }; exports.modules = fineUploaderModules; exports.mergeModules = mergeModules; }
JavaScript
0
@@ -354,32 +354,50 @@ %22@fuSrcS3%22,%0A + %22@fuSrcS3Ui%22,%0A %22@fuSrcModul @@ -650,32 +650,50 @@ %22@fuSrcS3%22,%0A + %22@fuSrcS3Ui%22,%0A %22@fuSrcS3Jqu
c06abbd31c890708b5fdb55aabdf175cc07e7b60
更新用例,在IE6下更新css的操作需要时间等待
test/baidu/event/un.js
test/baidu/event/un.js
module("baidu.event.unload"); test("取消注册unload事件", function() { stop(); ua.importsrc('baidu.event.on', function() { expect(1); var handle_a = function() { ok(true, "check unload"); }; var div = document.body.appendChild(document.createElement('div')); baidu.on(div, "onclick", handle_a); /* 直接调用UserAction提供的接口跨浏览器接口,屏蔽浏览器之间的差异 */ ua.click(div); baidu.un(div, "click", handle_a); ua.click(div); document.body.removeChild(div); start(); }, 'baidu.event.on', 'baidu.event.un'); }); /** * 跨frame on然后un */ test("window resize", function() { expect(1); ua.frameExt({ onafterstart : function(f) { $(f).css('width', 200); }, ontest : function(w, f) { var op = this; var fn = function() { ok(true); }; baidu.on(w, 'resize', fn); $(f).css('width', 220); /* 貌似通过jquery触发窗体变化会存在延时 */ setTimeout(function() { baidu.un(w, 'resize', fn); $(f).css('width', 240); op.finish(); }, 500); } }); }); //测试大小写在on中一并做了 //test("test case sensitive", function() { // // ok(false, 'TODO: 添加大小写敏感事件的on绑定和un取消用例,比如DOMMouseScroll'); // expect(1); // var div = document.createElement('div'); // document.body.appendChild(div); // var listener = function() { // ok(true, '用DOMNodeInserted测试大小写敏感事件的un取消'); // }; // baidu.on(div, 'DOMNodeInserted', listener); // var div1 = document.createElement('div'); // div.appendChild(div1); // baidu.un(div, 'DOMNodeInserted', listener); // var div2 = document.createElement('div'); // div.appendChild(div2); // $(div).remove(); //});
JavaScript
0
@@ -960,16 +960,27 @@ );%0D%0A%09%09%09%09 +setTimeout( op.finis @@ -980,17 +980,21 @@ p.finish -( +, 100 );%0D%0A%09%09%09%7D
3424f1a08aa19ff75a7a9db421f1d594ad1d2c03
fix duplicate file bug with watcher
lib/watcher.js
lib/watcher.js
var Gaze = require('gaze').Gaze; var fse = require('fs-extra'); var minimatch = require('minimatch'); var path = require('path'); var _ = require('lodash'); function AcetateWatcher (acetate) { this.acetate = acetate; _.bindAll(this); } AcetateWatcher.prototype.start = function(){ this.watcher = new Gaze(this.acetate._sources); this.watcher.on('renamed', this.renamed); this.watcher.on('changed', this.changed); this.watcher.on('added', this.added); this.watcher.on('deleted', this.deleted); }; AcetateWatcher.prototype.renamed = function(filepath, oldpath){ oldpath = oldpath.replace(process.cwd() + path.sep, ''); filepath = filepath.replace(process.cwd() + path.sep, ''); this.acetate.log.info('watcher', "%s renamed to %s", oldpath, filepath); var insideSource = _.some(this.acetate._sources, function(source){ return minimatch(filepath, source); }); this._invalidateNunjucksCache(oldpath); this._removeOldPage(oldpath); if(insideSource) { // file was actually renamed and is still in the source folder this._loadNewPage(filepath); } }; AcetateWatcher.prototype.changed = function(filepath){ filepath = filepath.replace(process.cwd() + path.sep, ''); this.acetate.log.info('watcher', "%s changed", filepath); this._removeOldPage(filepath); this._loadNewPage(filepath); }; AcetateWatcher.prototype.deleted = function(filepath){ filepath = filepath.replace(process.cwd() + path.sep, ''); this.acetate.log.info('watcher', "%s deleted", filepath); this._removeOldPage(filepath); }; AcetateWatcher.prototype.added = function(filepath){ filepath = filepath.replace(process.cwd() + path.sep, ''); this.acetate.log.info('watcher', "%s added", filepath); this._loadNewPage(filepath); }; AcetateWatcher.prototype._removeOldPage = function(filepath){ var page = _.remove(this.acetate.pages, {template: filepath})[0]; if(page){ this.acetate.log.verbose('watcher', "removing %s", page.dest); page._clean(); } }; AcetateWatcher.prototype._loadNewPage = function(filepath){ if(path.basename(filepath)[0] === '_'){ this.acetate.log.info('watcher', "layout or partial changed rebuilding all pages"); _.each(this.acetate.pages, function(page){ page.__dirty = true; }); this.acetate.build(); } else { this.acetate.loadPage(filepath, _.bind(function(error, page){ this.acetate.log.info('watcher', "rebuilding %s", filepath); this.acetate.pages.push(page); this.acetate.build(); }, this)); } }; AcetateWatcher.prototype._invalidateNunjucksCache = function(filepath){ var name = filepath.replace(this.acetate.src + path.sep, '').replace(path.extname(filepath), ''); this.acetate.nunjucks.loaders[0].emit('update', name); }; AcetateWatcher.prototype.stop = function(){ this.watcher.close(); }; module.exports = AcetateWatcher;
JavaScript
0
@@ -1812,24 +1812,89 @@ (filepath)%7B%0A + filepath = filepath.replace(this.acetate.src + path.sep, '');%0A%0A var page = @@ -1928,16 +1928,11 @@ s, %7B -template +src : fi
577736442b563af42595833e75f10cc1790c02ef
Add allowPaymentRequest to iframes
src/tapp/custom-tapp.js
src/tapp/custom-tapp.js
import logger from 'chayns-logger'; import htmlToElement from 'html-to-element'; import { chaynsInfo, setSelectedTapp } from '../chayns-info'; import { resetCallback } from '../json-chayns-call/calls/access-token-status-change'; import FloatingButton from '../ui/floating-button'; import WaitCursor from '../ui/wait-cursor'; import { getUrlParameters } from '../utils/url-parameter'; import { parameterStringToObject } from '../utils/convert'; import ConsoleLogger from '../utils/console-logger'; const loggerLoadTappById = new ConsoleLogger('loadTappById(custom-tapp.js)'); const loggerLoadTapp = new ConsoleLogger('loadTapp(custom-tapp.js)'); const $bodyContent = document.querySelector('.body-content'); /** * Loads Tapp by TappId. * @param {Number} tappId */ export default function loadTappById(tappId) { FloatingButton.hide(); WaitCursor.hide(); const tapp = getTappById(tappId); if (tapp) { setSelectedTapp(tapp); resetCallback(); loadTapp(tapp.id, setUrlParams(tapp.url), tapp.postTobitAccessToken); } else { logger.warning({ message: 'no tapp found', customNumber: tappId, fileName: 'custom-tapp.js', section: 'loadTapp' }); loggerLoadTappById.warn('No Tapp found!'); } } /** * Returns the tapp to tappId * @param tappId * @returns {*} */ export function getTappById(tappId) { return chaynsInfo.Tapps.find(tapp => tapp.id === tappId) || null; } /** * replaces url parameters with chayns env, removes double params, removes empty params, adds non system urlParameter from cnrt * @param {string} url * @returns {string} url */ function setUrlParams(url) { url = url.replace(/##apname##/ig, chaynsInfo.LocationName); url = url.replace(/##siteid##/ig, chaynsInfo.SiteID); url = url.replace(/##os##/ig, 'chaynsnet-runtime'); url = url.replace(/##version##/ig, chaynsInfo.getGlobalData().AppInfo.Version); url = url.replace(/##colormode##/ig, chaynsInfo.ColorMode.toString()); url = url.replace(/##color##/ig, chaynsInfo.Color.replace('#', '')); url = url.replace(/##adminmode##/ig, (chaynsInfo.AdminMode ? 1 : 0).toString()); url = url.replace(/##tobituserid##/ig, chaynsInfo.User.ID.toString()); if (chaynsInfo.User !== undefined && chaynsInfo.User.ID !== '' && chaynsInfo.User.ID > 0) { url = url.replace(/##firstname##/ig, chaynsInfo.User.FirstName); url = url.replace(/##lastname##/ig, chaynsInfo.User.LastName); } url = url.replace(/##.*?##/g, ''); // removes unused parameters const urlParam = Object.assign(getUrlParameters(false), parameterStringToObject(url)); const paramString = Object.keys(urlParam).map(key => (urlParam[key] !== undefined ? `${key}=${urlParam[key]}` : key)); const timeStamp = url.match(/(?:_=)\b(\d*)/i); return `${url.split('?')[0]}?${paramString.join('&')}${(!timeStamp) ? `&_=${Date.now()}` : ''}`; } /** * loads an url by tapp id and creates the iframe * @param {number} tappId * @param {string} tappUrl * @param {boolean} postTobitAccessToken */ function loadTapp(tappId, tappUrl, postTobitAccessToken) { if (typeof tappId !== 'number') { tappId = parseInt(tappId, 10); if (Number.isNaN(tappId)) { loggerLoadTapp.error('TappId is not a number'); return; } } if (!tappUrl || typeof tappUrl !== 'string') { loggerLoadTapp.error('TappUrl is not a string'); return; } const $input = htmlToElement(`<input id="ActiveTappID" name="ActiveTappID" type="hidden" value="${tappId}">`); const $form = htmlToElement(`<form action="${tappUrl}" target="TappIframe" method="get" id="TobitAccessTokenForm"></form>`); if (postTobitAccessToken && chaynsInfo.User.TobitAccessToken) { $form.setAttribute('method', 'post'); const $hiddenField = document.createElement('input'); $hiddenField.setAttribute('type', 'hidden'); $hiddenField.setAttribute('name', 'TobitAccessToken'); $hiddenField.setAttribute('value', chaynsInfo.User.TobitAccessToken); $form.appendChild($hiddenField); } const parameter = parameterStringToObject(tappUrl); for (const key of Object.keys(parameter)) { $form.appendChild(htmlToElement(`<input name="${key}" value="${parameter[key]}" type="hidden">`)); } const $iframe = htmlToElement('<iframe frameborder="0" marginheight="0" marginwidth="0" id="TappIframe" name="TappIframe"></iframe>'); $iframe.style.height = `${(window.innerHeight - document.body.getBoundingClientRect().top) + document.body.scrollTop}px`; if (chaynsInfo.IsMobile) { $iframe.setAttribute('style', 'margin-top: -10px !important;'); } if (chaynsInfo.ExclusiveMode || chaynsInfo.fullSizeMode) { $bodyContent.classList.add('body-content--exclusive-view'); } else { $bodyContent.classList.remove('body-content--exclusive-view'); } $form.action = `${$form.action}&contentWidth=${$bodyContent.offsetWidth}`; $bodyContent.innerHTML = ''; $bodyContent.appendChild($input); $bodyContent.appendChild($form); $bodyContent.appendChild($iframe); if ($form.length > 0) { $form.submit(); } }
JavaScript
0
@@ -4512,16 +4512,39 @@ pIframe%22 + allowpaymentrequest=%22%22 %3E%3C/ifram
c49e66e3510be076923739bf07d65c9e174e2a23
Add unit tests for wait parameter
test/check-url.spec.js
test/check-url.spec.js
import 'babel-polyfill'; import { describe, it, before, after } from 'mocha'; import { expect } from 'chai'; import checkURL from '../lib/check-url'; import createTestServer from './server'; describe('Check URL', function testChechkURL() { let server; this.timeout(5000); before('set up test server', () => { server = createTestServer(4001); }); after('tear down test server', () => { server.close(); }); it('should export a function', () => { expect(checkURL).to.be.a('function'); }); it('should report correctly when there is no JS error', (done) => { checkURL('http://localhost:4001/no-error', 1000, (err, result) => { expect(err).to.equal(null); expect(result[1]).to.equal(false); done(); }); }); it('should report correctly when there is a JS error', (done) => { checkURL('http://localhost:4001/error', 1000, (err, result) => { expect(err).to.equal(null); expect(result[1]).to.equal(true); done(); }); }); it('should get an error when the url does not load', (done) => { checkURL('http://localhost:9999/notfound', 1000, (err, result) => { expect(err).to.not.equal(null); expect(typeof result).to.equal('undefined'); done(); }); }); });
JavaScript
0
@@ -1378,13 +1378,548 @@ %0A %7D); +%0A%0A it('should take more time before returning for non-default wait parameters', (done) =%3E %7B%0A let ran = false;%0A%0A checkURL('http://localhost:9999/notfound', 2000, (err, result) =%3E %7B%0A expect(err).to.not.equal(null);%0A expect(typeof result).to.equal('undefined');%0A%0A ran = true;%0A %7D);%0A%0A setTimeout(() =%3E %7B%0A expect(ran).to.equal(false);%0A %7D, 1000);%0A%0A setTimeout(() =%3E %7B%0A expect(ran).to.equal(true);%0A done();%0A %7D, 4500);%0A %7D); %0A%7D);%0A
dfaf562d2214292fe35ddde8bd873e1399c2dc7f
Remove xattr if there is no tag (nv-tags)
lib/nv-tags.js
lib/nv-tags.js
// For a *nix compatible platform (targeted MacOSX) this should register custom logic // to support tags compatible with Notational Velocity (see https://notational.net). // // This also services as a canonical example of how to consume the service API, // to enhance the package with additional file readers, search fields, and columns. // See http://flight-manual.atom.io/behind-atom/sections/interacting-with-other-packages-via-services/ // E.g. in your package.json: // { // "consumedServices": { // "textual-velocity": { // "versions": { // "^0.1.0": "consumeTextualVelocityServiceV0" // } // } // } // } module.exports = { consumeTextualVelocityServiceV0: function (service) { var bplist, xattr // Due to being optionalDependencies they might not exist, if that's the case do nothing and just return try { bplist = require('bplist') xattr = require('fs-xattr') } catch (err) { return } var XATTR_KEY = 'com.apple.metadata:kMDItemOMUserTags' var FILE_PROP_NAME = 'nvtags' var FIELD_NAME = 'nvtagstr' service.registerFileReaders({ filePropName: FILE_PROP_NAME, read: function (path, callback) { if (!xattr) return callback(new Error('xattr no longer available, probably due to package being deactivated while in transit')) xattr.get(path, XATTR_KEY, function (err, plistBuf) { if (err) { if (err.code === 'ENOATTR') { callback(null, null) // no xattrs set; return empty list } else { callback(err) // e.g. file path does not exist or such } } else { bplist.parseBuffer(plistBuf, function (err, list) { if (err) { callback(err) } else { callback(null, list[0]) } }) } }) } }) var fieldAndColumnEditValue = function (file) { var tags = file[FILE_PROP_NAME] if (!Array.isArray(tags)) return return tags.join(' ') } service.registerFields({ filePropName: FIELD_NAME, value: fieldAndColumnEditValue }) service.registerColumns({ title: 'NV tags', description: 'NV Tags', position: 2, // after Summary sortField: FIELD_NAME, editCellName: FILE_PROP_NAME, width: 20, editCellStr: fieldAndColumnEditValue, cellContent: function (file, searchMatch) { var tags = file[FILE_PROP_NAME] if (!Array.isArray(tags)) return return tags.map(function (tag) { return { attrs: {className: 'inline-block-tight highlight'}, content: searchMatch && searchMatch.content(tag) || tag } }) } }) service.registerFileWriters({ editCellName: FILE_PROP_NAME, write (path, str, callback) { // https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback var tags = str.split(' ') var plistBuf = bplist.create([tags]) xattr.set(path, XATTR_KEY, plistBuf, callback) } }) var editNVTags = function () { service.editCell(FILE_PROP_NAME) } var DisposableValues = require('./disposable-values') return new DisposableValues( atom.commands.add('.platform-darwin', 'textual-velocity:edit-nv-tags', editNVTags), atom.commands.add('.platform-linux', 'textual-velocity:edit-nv-tags', editNVTags), atom.keymaps.add(__filename, { '.platform-darwin': { 'cmd-shift-t': 'textual-velocity:edit-nv-tags' }, '.platform-linux': { 'ctrl-shift-t': 'textual-velocity:edit-nv-tags' } }) ) } }
JavaScript
0
@@ -2923,118 +2923,85 @@ -// https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback%0A var tags = str.split(' ') +var tags = str.trim().split(' ')%0A if (tags.length && tags%5B0%5D !== '') %7B %0A @@ -3001,24 +3001,26 @@ ) %7B%0A + var plistBuf @@ -3044,16 +3044,18 @@ %5Btags%5D)%0A + @@ -3101,16 +3101,93 @@ llback)%0A + %7D else %7B%0A xattr.remove(path, XATTR_KEY, callback)%0A %7D%0A %7D%0A
a0f1e7fad91d7086e082fe8c11f8e2bd3259b0e1
Add header to the offline command output
lib/offline.js
lib/offline.js
/** * Copyright 2015 Mozilla * * 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'; // Import this first so we can use it to wrap other modules we import. var promisify = require('promisify-node'); var fs = require('fs'); var path = require('path'); var swPrecache = promisify(require('sw-precache')); var chalk = require('chalk'); var ghslug = promisify(require('github-slug')); var glob = require('glob'); module.exports = function(config) { return new Promise(function(resolve, reject) { var rootDir = config.rootDir || './'; // Ensure root directory ends with slash so we strip leading slash from paths // of files to cache, so they're relative paths, and the offline worker // will match them regardless of whether the app is deployed to a top-level // directory for a custom domain (f.e. https://example.com/) or a subdirectory // of a GitHub Pages domain (f.e. https://mykmelez.github.io/example/). if (rootDir.lastIndexOf('/') !== rootDir.length -1) { rootDir = rootDir + '/'; } var fileGlobs = config.fileGlobs || ['**/*']; // Remove the existing service worker, if any, so sw-precache doesn't include // it in the list of files to cache. try { fs.unlinkSync(path.join(rootDir, 'offline-worker.js')); } catch (ex) { // Only ignore the error if it's a 'file not found' error. if (!ex.code || ex.code !== 'ENOENT') { reject(ex); return; } } resolve(ghslug('./').catch(function() { // Use the name from package.json if there's an error while fetching the GitHub slug. try { return JSON.parse(fs.readFileSync('package.json')).name; } catch (ex) { return ''; } }).then(function(cacheId) { var staticFileGlobs = fileGlobs.map(function(v) { return path.join(rootDir, v); }); staticFileGlobs.forEach(function(globPattern) { glob.sync(globPattern.replace(path.sep, '/')).forEach(function(file) { var stat = fs.statSync(file); if (stat.isFile() && stat.size > 2 * 1024 * 1024 && staticFileGlobs.indexOf(file) === -1) { console.log(chalk.yellow.bold(file + ' is bigger than 2 MiB. Are you sure you want to cache it? To suppress this warning, explicitly include the file in the fileGlobs list.')); } }); }); var importScripts = config.importScripts || []; importScripts.forEach(function(script) { var stat; try { stat = fs.statSync(path.join(rootDir, script)); } catch (ex) { console.log(chalk.red.bold(script + ' doesn\'t exist.')); throw ex; } if (!stat.isFile()) { console.log(chalk.red.bold(script + ' is not a file.')); throw new Error(script + ' is not a file.'); } }); return swPrecache.write(path.join(rootDir, 'offline-worker.js'), { staticFileGlobs: staticFileGlobs, stripPrefix: rootDir, verbose: true, logger: function(message) { if (message.indexOf('Caching') === 0) { message = chalk.bold.green('✓ ') + message.replace('static resource ', '') } console.log(message); }, importScripts: importScripts, cacheId: cacheId, ignoreUrlParametersMatching: config.ignoreUrlParametersMatching || [/./], maximumFileSizeToCacheInBytes: Infinity, }); })); }); };
JavaScript
0.000001
@@ -1055,16 +1055,141 @@ './';%0A%0A + console.log('Offlining ' + chalk.bold(rootDir) + ' to ' + chalk.bold(path.join(rootDir, 'offline-worker.js')) + '%E2%80%A6%5Cn');%0A%0A // E
53102b9b7735172dfc9ec9cead911656b72265f5
Remove 'static resource' from sw-precache logs
lib/offline.js
lib/offline.js
/** * Copyright 2015 Mozilla * * 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'; // Import this first so we can use it to wrap other modules we import. var promisify = require('promisify-node'); var fs = require('fs'); var path = require('path'); var swPrecache = promisify(require('sw-precache')); var chalk = require('chalk'); var ghslug = promisify(require('github-slug')); var glob = require('glob'); module.exports = function(config) { return new Promise(function(resolve, reject) { var rootDir = config.rootDir || './'; // Ensure root directory ends with slash so we strip leading slash from paths // of files to cache, so they're relative paths, and the offline worker // will match them regardless of whether the app is deployed to a top-level // directory for a custom domain (f.e. https://example.com/) or a subdirectory // of a GitHub Pages domain (f.e. https://mykmelez.github.io/example/). if (rootDir.lastIndexOf('/') !== rootDir.length -1) { rootDir = rootDir + '/'; } var fileGlobs = config.fileGlobs || ['**/*']; // Remove the existing service worker, if any, so sw-precache doesn't include // it in the list of files to cache. try { fs.unlinkSync(path.join(rootDir, 'offline-worker.js')); } catch (ex) { // Only ignore the error if it's a 'file not found' error. if (!ex.code || ex.code !== 'ENOENT') { reject(ex); return; } } resolve(ghslug('./').catch(function() { // Use the name from package.json if there's an error while fetching the GitHub slug. try { return JSON.parse(fs.readFileSync('package.json')).name; } catch (ex) { return ''; } }).then(function(cacheId) { var staticFileGlobs = fileGlobs.map(function(v) { return path.join(rootDir, v); }); staticFileGlobs.forEach(function(globPattern) { glob.sync(globPattern.replace(path.sep, '/')).forEach(function(file) { var stat = fs.statSync(file); if (stat.isFile() && stat.size > 2 * 1024 * 1024 && staticFileGlobs.indexOf(file) === -1) { console.log(chalk.yellow.bold(file + ' is bigger than 2 MiB. Are you sure you want to cache it? To suppress this warning, explicitly include the file in the fileGlobs list.')); } }); }); var importScripts = config.importScripts || []; importScripts.forEach(function(script) { var stat; try { stat = fs.statSync(path.join(rootDir, script)); } catch (ex) { console.log(chalk.red.bold(script + ' doesn\'t exist.')); throw ex; } if (!stat.isFile()) { console.log(chalk.red.bold(script + ' is not a file.')); throw new Error(script + ' is not a file.'); } }); return swPrecache.write(path.join(rootDir, 'offline-worker.js'), { staticFileGlobs: staticFileGlobs, stripPrefix: rootDir, verbose: true, logger: console.log, importScripts: importScripts, cacheId: cacheId, ignoreUrlParametersMatching: config.ignoreUrlParametersMatching || [/./], maximumFileSizeToCacheInBytes: Infinity, }); })); }); };
JavaScript
0.000001
@@ -3543,27 +3543,109 @@ logger: -console.log +function(message) %7B%0A console.log(message.replace('static resource ', ''));%0A %7D ,%0A
5cb568a59038d56629f1306da9ef45c8fe2a1a76
test setChildIndex
test/core/Container.js
test/core/Container.js
'use strict'; describe('PIXI.Container', () => { describe('parent', () => { it('should be present when adding children to Container', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); expect(container.children.length).to.be.equals(0); container.addChild(child); expect(container.children.length).to.be.equals(1); expect(child.parent).to.be.equals(container); }); }); describe('events', () => { it('should trigger "added" and "removed" events on its children', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); let triggeredAdded = false; let triggeredRemoved = false; child.on('added', (to) => { triggeredAdded = true; expect(container.children.length).to.be.equals(1); expect(child.parent).to.be.equals(to); }); child.on('removed', (from) => { triggeredRemoved = true; expect(container.children.length).to.be.equals(0); expect(child.parent).to.be.null; expect(container).to.be.equals(from); }); container.addChild(child); expect(triggeredAdded).to.be.true; expect(triggeredRemoved).to.be.false; container.removeChild(child); expect(triggeredRemoved).to.be.true; }); }); describe('addChild', () => { it('should remove from current parent', () => { const parent = new PIXI.Container(); const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, container, child, () => { container.addChild(child); }); }); }); describe('removeChildAt', () => { it('should remove from current parent', () => { const parent = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, null, child, () => { parent.removeChildAt(0); }); }); }); describe('addChildAt', () => { it('should allow placements at start', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); container.addChildAt(child, 0); expect(container.children.length).to.be.equals(2); expect(container.children[0]).to.be.equals(child); }); it('should allow placements at end', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); container.addChildAt(child, 1); expect(container.children.length).to.be.equals(2); expect(container.children[1]).to.be.equals(child); }); it('should throw on out-of-bounds', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); expect(() => container.addChildAt(child, -1)).to.throw('The index -1 supplied is out of bounds 1'); expect(() => container.addChildAt(child, 2)).to.throw('The index 2 supplied is out of bounds 1'); }); it('should remove from current parent', () => { const parent = new PIXI.Container(); const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, container, child, () => { container.addChildAt(child, 0); }); }); }); describe('removeChild', () => { it('should ignore non-children', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); container.removeChild(new PIXI.DisplayObject()); expect(container.children.length).to.be.equals(1); }); it('should remove all children supplied', () => { const container = new PIXI.Container(); const child1 = new PIXI.DisplayObject(); const child2 = new PIXI.DisplayObject(); container.addChild(child1, child2); expect(container.children.length).to.be.equals(2); container.removeChild(child1, child2); expect(container.children.length).to.be.equals(0); }); }); describe('getChildIndex', () => { it('should return the correct index', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject(), child, new PIXI.DisplayObject()); expect(container.getChildIndex(child)).to.be.equals(1); }); it('should throw when child does not exist', () => { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); expect(() => container.getChildIndex(child)) .to.throw('The supplied DisplayObject must be a child of the caller'); }); }); describe('getChildAt', () => { it('should throw when out-of-bounds', () => { const container = new PIXI.Container(); expect(() => container.getChildAt(-1)).to.throw('getChildAt: Index (-1) does not exist.'); expect(() => container.getChildAt(1)).to.throw('getChildAt: Index (1) does not exist.'); }); }); }); }); function assertRemovedFromParent(parent, container, child, functionToAssert) { parent.addChild(child); expect(parent.children.length).to.be.equals(1); expect(child.parent).to.be.equals(parent); functionToAssert(); expect(parent.children.length).to.be.equals(0); expect(child.parent).to.be.equals(container); } });
JavaScript
0.000001
@@ -5892,24 +5892,822 @@ %7D);%0A %7D); +%0A%0A describe('setChildIndex', () =%3E%0A %7B%0A it('should throw on out-of-bounds', () =%3E%0A %7B%0A const container = new PIXI.Container();%0A const child = new PIXI.DisplayObject();%0A%0A container.addChild(child);%0A%0A expect(() =%3E container.setChildIndex(child, -1)).to.throw('The supplied index is out of bounds');%0A expect(() =%3E container.setChildIndex(child, 1)).to.throw('The supplied index is out of bounds');%0A %7D);%0A%0A it ('should throw when child does not belong', () =%3E%0A %7B%0A const container = new PIXI.Container();%0A const child = new PIXI.DisplayObject();%0A %0A expect(() =%3E container.setChildIndex(child, 0)).to.throw('The supplied DisplayObject must be a child of the caller'); %0A %7D);
d3fee2bfd8465b2265e907bcdd313d28dc759279
fix plugin loading
lib/plugins.js
lib/plugins.js
var symbols = require('symbolsjs'); var async = require('async'); var printit = require('printit'); var logger = printit({prefix: 'Cozy Light'}); var nodeHelpers = require('./helpers/node'); var npmHelpers = require('./helpers/npm'); var configHelpers = require('./config'); var routes = require('./routes'); module.exports = pluginHelpers = { loadedPlugins: {}, startedPlugins: {}, loadPlugin: function (pluginName, program) { var cozyLight = require('./cozy-light'); var config = configHelpers.getConfig(); var pluginConfig = config.plugins[pluginName]; if (pluginConfig.disabled !== true) { var pluginPath = configHelpers.modulePath(pluginConfig.name); try { var pluginModule = require(pluginPath); var options = { name: pluginModule.name, displayName: pluginConfig.displayName, version: pluginConfig.version, description: pluginConfig.description, configPath: configHelpers.getConfigPath(), home: configHelpers.getHomePath(), npmHelpers: npmHelpers, cozyLight: cozyLight, proxy: cozyLight.mainAppHelper.getProxy(), /* eslint-disable */ // for backward compatibility config_path: configHelpers.getConfigPath() /* eslint-enable */ }; if (pluginModule.configure) { pluginModule.configure(options, config, program, cozyLight); } pluginHelpers.loadedPlugins[pluginName] = pluginModule; return pluginModule; } catch (err) { logger.error('Can\'t load ' + pluginName); logger.raw(err.stack); } } return null; }, unloadPlugin: function (pluginName) { if (pluginHelpers.startedPlugins[pluginName]) { throw 'Can not unload started plugins, stop it first !'; } delete pluginHelpers.loadedPlugins[pluginName]; }, /** * Loads all plugins. * * @param program Program or Plain object. * @param callback Termination. */ loadAll: function (program, callback) { var config = configHelpers.getConfig(); var loadPlugin = function (pluginName, cb) { pluginHelpers.loadPlugin(pluginName, program, cb); }; async.eachSeries(Object.keys(config.plugins || {}), loadPlugin, callback); }, /** * Start given plugin (require it, run configuration and apply change to * cozy light server). * NB: Do not load given plugin if it is disabled. * * @param pluginName The plugin name to start. * @param program The commander program to bind. * @param applicationServer The application server to connect the plugin on. * @param callback Termination. */ start: function (pluginName, program, applicationServer, callback) { var config = configHelpers.getConfig(); if (config.plugins[pluginName] === undefined) { logger.error('Plugin ' + pluginName + ' not installed!'); } else { try { if (pluginHelpers.loadedPlugins[pluginName] === undefined) { pluginHelpers.loadPlugin(pluginName, program); } var plugin = pluginHelpers.loadedPlugins[pluginName]; if (plugin !== null) { pluginHelpers.startedPlugins[plugin] = true; if (plugin.configureAppServer !== undefined) { logger.info('Configuring plugin ' + pluginName + '...'); var logResult = function () { logger.info('Plugin ' + pluginName + ' configured.'); nodeHelpers.invoke(callback); }; return plugin.configureAppServer(applicationServer, config, routes, logResult); } } } catch(err) { logger.raw(err); logger.error('Plugin ' + pluginName + ' loading failed.'); return nodeHelpers.invoke(callback, err); } } return nodeHelpers.invoke(callback); }, /** * Stop given plugin (unload it form cache and run its exit handleR). * * @param pluginName The plugin name to start. * @param callback Termination. */ stop: function (pluginName, callback) { var config = configHelpers.getConfig(); if (config.plugins[pluginName] === undefined) { logger.error('Plugin ' + pluginName + ' not installed!'); } else if (pluginHelpers.loadedPlugins[pluginName] === undefined) { logger.error('Plugin ' + pluginName + ' not loaded!'); } else { var options = config.plugins[pluginName]; try { var plugin = pluginHelpers.loadedPlugins[pluginName]; delete pluginHelpers.loadedPlugins[pluginName]; nodeHelpers.clearRequireCache(configHelpers.modulePath(options.name)); if (plugin.onExit !== undefined) { return plugin.onExit(options, config, function (err) { if (err) { logger.raw(err); logger.info('\t' + symbols.err + '\t' + options.displayName + ''); } else { logger.info('\t' + symbols.ok + '\t' + options.displayName + ''); } delete pluginHelpers.startedPlugins[pluginName]; nodeHelpers.invoke(callback, err); }); } else { delete pluginHelpers.startedPlugins[pluginName]; logger.info('\t' + symbols.ok + '\t' + options.displayName + ''); } } catch(err) { logger.raw(err); logger.error('Plugin ' + options.displayName + ' failed for termination.'); return nodeHelpers.invoke(callback, err); } } return nodeHelpers.invoke(callback); }, /** * Start all plugins. * * @param program Program or Plain object. * @param app Express app. * @param callback Termination. */ startAll: function (program, app, callback) { var attachPlugin = function (pluginName, cb) { pluginHelpers.start(pluginName, program, app, cb); }; async.eachSeries( Object.keys(pluginHelpers.loadedPlugins), attachPlugin, callback ); }, /** * Stop all plugins. * * @param callback Termination. */ stopAll: function (callback) { var plugins = Object.keys(pluginHelpers.loadedPlugins || {}); async.eachSeries(plugins, pluginHelpers.stop, callback); } };
JavaScript
0.000001
@@ -790,22 +790,22 @@ : plugin -Module +Config .name,%0A @@ -2224,33 +2224,16 @@ %7D;%0A%0A -async.eachSeries( Object.k @@ -2257,18 +2257,25 @@ s %7C%7C %7B%7D) -, +.forEach( loadPlug @@ -2276,18 +2276,42 @@ adPlugin -, +);%0A nodeHelpers.invoke( callback
db247eb53cfaf7b4861e6dfdd1541bb2d88e31a1
update test targets for latest Primo [PT #172970658]
test/e2e/e2e.primo2.js
test/e2e/e2e.primo2.js
var minimalUql = require("./e2e.minimal.js"); // test for something basic that should always return results var searchText = 'book'; var urlTest = 'https://search.library.uq.edu.au/primo-explore/search?query=any,contains,' + searchText + '&tab=61uq_all&search_scope=61UQ_All&sortby=rank&vid=61UQ&offset=0'; module.exports = { '@tags': ['e2etest', 'primo'], 'Test reusable components are applied to New Primo UI': function (client) { // common uql checks // new primo UI doesn't have footer, only header minimalUql.commonChecks(client, urlTest, false); client // primo specific checks .assert.elementPresent('prm-brief-result-container', 'at least one primo result is present') .end(); }, 'Test user area modifications have been applied': function (client) { client .url(urlTest) .pause(10000) .waitForElementPresent('prm-topbar', 20000) .assert.elementPresent('prm-topbar prm-user-area', 'user area component is present') .assert.elementPresent('prm-topbar prm-user-area prm-authentication', 'login component is present') .assert.elementPresent('prm-topbar prm-user-area prm-authentication span', 'login text is present') .assert.elementPresent('prm-topbar prm-user-area prm-library-card-menu', 'user account component is present') .assert.elementPresent('prm-topbar .top-nav-bar prm-search-bookmark-filter', 'bookmark component is present') .assert.elementPresent('prm-topbar prm-user-area span', 'Not logged in') .end(); client.end(); } };
JavaScript
0
@@ -102,16 +102,124 @@ results%0A +// (this url should match the primo landing url when you search for 'book' from the homepage search wudget)%0A var sear @@ -381,20 +381,8 @@ All& -sortby=rank& vid= @@ -536,17 +536,17 @@ %0A // -c +C ommon uq @@ -565,13 +565,9 @@ // -new p +P rimo @@ -674,16 +674,18 @@ t%0A + // primo @@ -703,24 +703,26 @@ hecks%0A + + .assert.elem @@ -798,24 +798,26 @@ s present')%0A + .end() @@ -913,16 +913,18 @@ t%0A + .url(url @@ -929,16 +929,18 @@ rlTest)%0A + .p @@ -947,24 +947,26 @@ ause(10000)%0A + .waitF @@ -1001,32 +1001,34 @@ ', 20000)%0A + .assert.elementP @@ -1059,16 +1059,27 @@ ser-area +-expandable ', 'user @@ -1099,32 +1099,34 @@ nt is present')%0A + .assert.el @@ -1163,33 +1163,32 @@ ser-area - prm-authenticati +-expandable butt on', 'lo @@ -1206,32 +1206,34 @@ nt is present')%0A + .assert.el @@ -1274,161 +1274,60 @@ area - prm-authentication span', 'login text is present')%0A .assert.elementPresent('prm-topbar prm-user-area prm-library-card-menu', 'user account componen +-expandable button.sign-in-btn-ctm span', 'login tex t is @@ -1329,32 +1329,34 @@ xt is present')%0A + .assert.el @@ -1461,85 +1461,8 @@ )%0A - .assert.elementPresent('prm-topbar prm-user-area span', 'Not logged in')%0A
e2e876d3728d790d7060ecd45760e37b29fc9d7f
Change the Mongo index to also use the actual field (thanks Jason!)
lib/profile.js
lib/profile.js
'use strict'; function storage (collection, ctx) { var ObjectID = require('mongodb').ObjectID; function create (obj, fn) { obj.created_at = (new Date( )).toISOString( ); api().insert(obj, function (err, doc) { fn(null, doc); }); } function save (obj, fn) { obj._id = new ObjectID(obj._id); if (!obj.created_at) { obj.created_at = (new Date( )).toISOString( ); } api().save(obj, function (err) { //id should be added for new docs fn(err, obj); }); } function list (fn) { return api( ).find({ }).sort({startDate: -1}).toArray(fn); } function last (fn) { return api().find().sort({startDate: -1}).limit(1).toArray(fn); } function api () { return ctx.store.db.collection(collection); } api.list = list; api.create = create; api.save = save; api.last = last; api.indexedFields = ['validfrom']; return api; } module.exports = storage;
JavaScript
0
@@ -883,17 +883,17 @@ = %5B' -validfrom +startDate '%5D;%0A
00acac55888ba827d55853eef100cb7c208b2941
Update test
test/invariant.spec.js
test/invariant.spec.js
import {expect} from 'chai' import invariant from '../src/invariant' describe('invariant', () => { it('should throw when `message` argument is undefined', () => { expect(() => {invariant(false)}).to.throw(Error) expect(() => {invariant(true)}).to.throw(Error) }) it('should throw when `condition` argument is false', () => { expect(() => {invariant(false, 'something wrong')}).to.throw(Error) }) it('should not throw when `condition` argument is true', () => { expect(() => {invariant(true, 'something wrong')}).to.not.throw(Error) }) })
JavaScript
0.000001
@@ -169,32 +169,39 @@ expect(() =%3E %7B +%0A invariant(false) @@ -200,16 +200,21 @@ t(false) +%0A %7D).to.th @@ -234,32 +234,39 @@ expect(() =%3E %7B +%0A invariant(true)%7D @@ -264,16 +264,21 @@ nt(true) +%0A %7D).to.th @@ -367,32 +367,39 @@ expect(() =%3E %7B +%0A invariant(false, @@ -413,24 +413,29 @@ hing wrong') +%0A %7D).to.throw( @@ -531,16 +531,23 @@ (() =%3E %7B +%0A invarian @@ -572,16 +572,21 @@ wrong') +%0A %7D).to.no
cfa079fcba8dbfca02012f12a9d37b20b11d9e9c
use process env variable for port if available
app/server.js
app/server.js
/* AIDA Source Code */ /* Contributors located at: github.com/2nd47/CSC309-A4 */ // main app // server modules var bcrypt = require('bcryptjs'); var express = require('express'); var mongoose = require('mongoose'); var session = require('express-session'); var validator = require('validator'); var qs = require('querystring'); // testing modules var testCase = require('mocha').describe; var pre = require('mocha').before; var assertions = require('mocha').it; var assert = require('chai').assert; // module init var app = express(); // router import keeps main file clean var router = require('./router'); var db = require('../db/db.js'); // app init const APP_PORT = 3000; const saltRounds = 10; function init() { return; } function main() { init(); app.use('/', router); app.listen(APP_PORT); console.log('Server listening on port ' + APP_PORT); } main();
JavaScript
0
@@ -667,16 +667,36 @@ P_PORT = + process.env.port %7C%7C 3000;%0Ac
15387f0e96b50f76a2b345157fd61a96ac21a4bc
Reword repo name in rollback test for extra clarity
test/rollbacks.test.js
test/rollbacks.test.js
import Microcosm from '../src/microcosm' test('does not rollforward the same actions twice', function () { const repo = new Microcosm({ maxHistory: Infinity }) const send = n => n const a = repo.append(send) const b = repo.append(send) const c = repo.append(send) repo.addDomain('messages', { getInitialState() { return [] }, add(state, items) { return state.concat(items) }, addLoading(state, params) { return this.add(state, { ...params, pending: true }) }, register() { return { [send.open] : this.addLoading, [send.done] : this.add } } }) a.open({ id: 1 }) b.open({ id: 2 }) c.open({ id: 3 }) a.resolve({ id: 2 }) b.resolve({ id: 2 }) c.resolve({ id: 3 }) expect(repo.state.messages[0].pending).not.toBeDefined() expect(repo.state.messages[1].pending).not.toBeDefined() expect(repo.state.messages[2].pending).not.toBeDefined() expect(repo.state.messages.length).toEqual(3) }) test('remembers the archive point', function () { const repo = new Microcosm({ maxHistory: Infinity }) const send = n => n repo.addDomain('messages', { getInitialState() { return [] }, add(state, items) { return state.concat(items) }, register() { return { [send.done] : this.add } } }) const a = repo.push(send, { id: 1 }) const b = repo.push(send, { id: 2 }) const c = repo.push(send, { id: 3 }) repo.checkout(a) expect(repo.state.messages.map(m => m.id)).toEqual([1]) repo.checkout(c) expect(repo.state.messages.map(m => m.id)).toEqual([1, 2, 3]) repo.checkout(b) expect(repo.state.messages.map(m => m.id)).toEqual([1, 2]) }) test('properly rolls forward the cache', () => { const top = new Microcosm({ maxHistory: 0 }) const all = n => n const single = n => n top.addDomain('items', { getInitialState() { return [] }, reset(_, items) { return items }, update (items, data) { return items.map(function (item) { if (item.id === data.id) { return { ...item, ...data } } return item }) }, setLoading (items, id) { return items.map(function (item) { if (item.id === id) { return { ...item, loading: true } } return item }) }, register () { return { [all.done] : this.reset, [single.open] : this.setLoading, [single.done] : this.update } } }) const getAll = top.append(all) const getOne = top.append(single) const getTwo = top.append(single) getAll.resolve([{ id: '1' }, { id: '2' }]) getOne.open('1') getTwo.open('2') getOne.resolve({ id: '1', done: true }) getTwo.resolve({ id: '2', done: true }) expect(top.state.items.map(i => i.done)).toEqual([true, true]) })
JavaScript
0
@@ -1769,19 +1769,20 @@ const -top +repo = new M @@ -1858,19 +1858,20 @@ =%3E n%0A%0A -top +repo .addDoma @@ -2540,19 +2540,20 @@ etAll = -top +repo .append( @@ -2574,19 +2574,20 @@ etOne = -top +repo .append( @@ -2611,19 +2611,20 @@ etTwo = -top +repo .append( @@ -2815,11 +2815,12 @@ ect( -top +repo .sta
a7a1963d93fc7b3a8043ece5b4328571414fdcb9
use callParent instead of Ext.Ajax singleton
src/util/AbstractAPI.js
src/util/AbstractAPI.js
/*jslint browser: true, undef: true*//*global Ext*/ /** * @abstract * An abstract class for singletons that facilitates communication with backend services * * TODO: * - add events for all lifecycle events: beforerequest, request, beforexception, exception, unauthorized * - does the touch version use Ext.Ajax or parent.request? * - pass through request options like touch version does */ Ext.define('Jarvus.util.AbstractAPI', { extend: 'Ext.data.Connection', requires: ['Ext.util.Cookies', 'Ext.Ajax', 'Ext.Array' ], uses: [ 'Jarvus.util.APIDomain' ], config: { /** * @cfg {String/null} * A host to prefix URLs with, or null to leave paths domain-relative */ host: null, /** * @cfg {Boolean} * True to use HTTPS when prefixing host. Only used if {@link #cfg-host} is set */ useSSL: false, // @inheritdoc withCredentials: true }, //@private buildUrl: function(path) { var host = this.getHost(); return host ? (this.getUseSSL() ? 'https://' : 'http://')+host+path : path; }, //@private buildHeaders: function(headers) { return headers; }, //@private buildParams: function(params) { return params || null; }, /** * Override {@link Ext.data.Connection#method-request} to implement auto-decoding and retry handler * @inheritdoc */ request: function(options) { var me = this; return Ext.Ajax.request(Ext.applyIf({ url: me.buildUrl(options.url), withCredentials: true, params: me.buildParams(options.params), headers: me.buildHeaders(options.headers), timeout: options.timeout || 30000, success: function(response) { if (options.autoDecode !== false && response.getResponseHeader('Content-Type') == 'application/json') { response.data = Ext.decode(response.responseText, true); } //Calling the callback function sending the decoded data Ext.callback(options.success, options.scope, [response]); }, failure: function(response) { if (options.autoDecode !== false && response.getResponseHeader('Content-Type') == 'application/json') { response.data = Ext.decode(response.responseText, true); } if (options.failure && options.failureStatusCodes && Ext.Array.contains(options.failureStatusCodes, response.status)) { Ext.callback(options.failure, options.scope, [response]); } else if (options.exception) { Ext.callback(options.exception, options.scope, [response]); } else if (response.aborted === true) { Ext.callback(options.abort, options.scope, [response]); } else if (response.status == 401 || response.statusText.indexOf('Unauthorized') !== -1) { /* We seem to always get the same session id, so we can't automatically try again once the user logs in var oldSessionID = Ext.util.Cookies.get('s'); */ Ext.override(Ext.Msg, { hide: function () { var me = this, hideManually = me.cfg ? me.cfg.hideManually : false; if (!hideManually) { me.callParent(arguments); } } }); var msg = Ext.Msg.show({ hideManually: true, title: 'Login Required', msg: "You've either logged out or your has session expired. Please login and try again.", buttonText: { 'yes': 'Login', 'no': 'Try Again', 'cancel': 'Cancel' }, scope: msg, fn: function (btn) { if (btn === 'yes') { // login var loginWindow = window.open(me.buildUrl('/login'), 'emergence-login'); loginWindow.focus(); return; } else if (btn === 'no') { // try again me.request(options); } msg.cfg.hideManually = false; msg.hide(); } }); /* if (oldSessionID !== null) { var cookieCheckInterval = window.setInterval(function() { console.log(oldSessionID); console.warn(Ext.util.Cookies.get('s')); if (Ext.util.Cookies.get('s') != oldSessionID) { alert('new login'); debugger; window.clearInterval(cookieCheckInterval); } }, 100); } */ } else { Ext.Msg.confirm('An error occurred', 'There was an error trying to reach the server. Do you want to try again?', function (btn) { if (btn === 'yes') { me.request(options); } }); } }, scope: options.scope }, options)); }, // @deprecated setHostname: function(hostname) { //<debug> Ext.Logger.deprecate('hostname config is deprecated, use host instead'); //</debug> this.setHost(hostname); }, // @deprecated getHostname: function() { //<debug> Ext.Logger.deprecate('hostname config is deprecated, use host instead'); //</debug> return this.getHost(); } });
JavaScript
0.000001
@@ -1562,25 +1562,23 @@ urn -Ext.Ajax.reques +me.callParen t( +%5B Ext. @@ -5916,16 +5916,17 @@ options) +%5D );%0A %7D
c7b2619db93c9a356f5b592820eb9d47a457fe48
add getters for callingNumber and calledNumber
lib/request.js
lib/request.js
var Emitter = require('events').EventEmitter ; var sip = require('drachtio-sip') ; var delegate = require('delegates') ; var only = require('only') ; var assert = require('assert') ; var util = require('util') ; var merge = require('merge') ; var debug = require('debug')('drachtio-client') ; module.exports = exports = Request ; function Request( msg, meta ){ if (!(this instanceof Request)) return new Request(msg); Emitter.call(this); Object.defineProperty( this, 'res', { get: function() { return this._res; }, set: function(res) { this._res = res; return this ; } }) ; Object.defineProperty( this, 'isNewInvite', { get: function() { var to = this.getParsed('to') ; return this.method === 'INVITE' && !('tag' in to.params) ; } }) ; Object.defineProperty( this, 'meta', { set: function(meta) { this.source = meta.source ; this.source_address = meta.address ; this.source_port = meta.port ? parseInt(meta.port): 5060 ; this.protocol = meta.protocol ; this.stackTime = meta.time ; this.stackTxnId = meta.transactionId ; this.stackDialogId = meta.dialogId ; } }) ; if( msg ) { assert(msg instanceof sip.SipMessage) ; this.msg = msg ; this.meta = meta ; } } util.inherits(Request, Emitter) ; Request.prototype.cancel = function(callback) { if( !this.agent || this.source != 'application') throw new Error('Request#cancel can only be used for uac Request') ; this.agent.request({ uri: this.uri, method: 'CANCEL', stackTxnId: this.stackTxnId, }, callback ) ; } ; Request.prototype.proxy = function( opts, callback ) { if( this.source !== 'network' ) throw new Error('Request#proxy can only be used for incoming requests') ; if( typeof opts !== 'object' || !opts.destination ) throw new Error('Request#proxy: opts.destination is required') ; //TODO: throw error if req.res.send has already been called (i.e. can't start off as UAS and then become a proxy) var destination = opts.destination; if( typeof destination === 'string') opts.destination = [destination] ; merge( opts, { stackTxnId: this.stackTxnId, remainInDialog: opts.remainInDialog || false, provisionalTimeout: opts.provisionalTimeout || '', finalTimeout: opts.finalTimeout || '', followRedirects: opts.followRedirects || false, simultaneous: opts.forking === 'simultaneous', fullResponse: callback.length === 2 }) ; //normalize sip uris opts.destination.forEach( function(value, index, array){ var token = value.split(':') ; if( token[0] !== 'sip' && token[0] != 'tel') { array[index] = 'sip:' + value ; } }) ; var result = { connected: false, responses: [] } ; this.agent.proxy( this, opts, function( token, rawMsg, meta){ if( 'NOK' === token[0] ) { return callback( token[1] ) ; } if( 'done' === token[1] ) { result.connected = (200 === result.finalStatus) ; return callback( null, result) ; } else { //add a new response to the array var address = meta.address ; var port = ~~meta.port ; var msg = new sip.SipMessage( rawMsg ) ; var obj = { time: meta.time, status: msg.status, msg: msg } ; var len = result.responses.length ; if( len === 0 || address !== result.responses[len-1].address || port === result.responses[len-1].port ) { result.responses.push({ address: address, port: port, msgs:[] }) ; len++ ; } result.responses[len-1].msgs.push( obj ) ; result.finalStatus = msg.status ; result.finalResponse = obj ; } }) ; } ; Request.prototype.toJSON = function() { return( only( this, 'msg source source_address source_port protocol stackTime stackDialogId stackTxnId')) ; } ; delegate(Request.prototype, 'msg') .method('get') .method('getParsedHeader') .method('set') .access('method') .access('uri') .access('headers') .access('body') .getter('type') .getter('raw') .getter('canFormDialog') ;
JavaScript
0
@@ -4127,16 +4127,69 @@ 'raw') %0A + .getter('callingNumber')%0A .getter('calledNumber')%0A .gette
f642bfa0e53c44c668f040ddbf9a9603fdbd117e
add transform to request
lib/request.js
lib/request.js
const request = require('request') const cheerio = require('cheerio') const urls = require('./urls') const config = require('./config') exports = module.exports = sendRequest exports.xsrf = get_xsrf /** * Send a request. * * If `data` is specified, a POST request will be sent, * else a GET request. * * @param {String} url * @param {Object} data * @return {Promise} * @public */ function sendRequest(url, data) { if (!config.cookie) { throw new Error('A cookie is needed. You should use ' + '`api.cookie(_cookie)` to set cookie.') } var opts = { headers: config.headers, url } if (data) { opts.method = 'POST' opts.form = data } else { opts.method = 'GET' } return new Promise((resolve, reject) => { request(opts, (err, res, body) => { if (err) { return reject(err) } resolve(body) }) }) } /** * Get `_xsrf`. * * @return {Promise} * @public */ function get_xsrf() { if (config.xsrf) { return Promise.resolve(config.xsrf) } return sendRequest(urls.index()) .then(body => { var $ = cheerio.load(body) config.xsrf = $('input[name="_xsrf"]').val() return config.xsrf }) }
JavaScript
0
@@ -130,16 +130,109 @@ nfig')%0A%0A +const transforms = %7B%0A html: data =%3E cheerio.load(data),%0A json: data =%3E JSON.parse(data)%0A%7D%0A%0A exports @@ -444,16 +444,55 @@ t%7D data%0A + * @param %7BString%7CFunction%7D transform%0A * @retu @@ -545,24 +545,35 @@ st(url, data +, transform ) %7B%0A if (!c @@ -714,16 +714,44 @@ pts = %7B%0A + url,%0A method: 'GET',%0A head @@ -773,17 +773,8 @@ ders -,%0A url %0A %7D @@ -842,43 +842,8 @@ %0A %7D - else %7B%0A opts.method = 'GET'%0A %7D %0A%0A @@ -976,16 +976,220 @@ %7D%0A +%0A if (typeof transform === 'string') %7B%0A transform = transforms%5Btransform.toLowerCase()%5D%0A %7D%0A%0A if (typeof transform === 'function') %7B%0A resolve(transform(body))%0A %7D else %7B%0A re @@ -1196,24 +1196,32 @@ solve(body)%0A + %7D%0A %7D)%0A %7D)%0A @@ -1403,16 +1403,30 @@ .index() +, null, 'html' )%0A .t @@ -1433,51 +1433,15 @@ hen( -body +$ =%3E %7B%0A - var $ = cheerio.load(body)%0A
8a77f071005253e58156232d48615587b2a5536f
Fix tests for Firefox
test/webworker-pool.js
test/webworker-pool.js
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Tests for WebWorkerPool * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ module("WebWorkerPool"); asyncTest("creates webworker out of simple source file", function () { expect(2); var wwp = new WebWorkerPool("resources/counting-webworker.js"), worker = wwp.getWorker(), count = 0; worker.onmessage = function (a) { equal(a.data.numMessages, 1); worker.onmessage = function (b) { equal(b.data.numMessages, 2); worker.terminate(); start(); } worker.postMessage(); }; worker.postMessage(); }); asyncTest("creates webworker from Blob, if browser supports Blobs", function () { var url; try { var response = "this.onmessage=function (e) { postMessage({ square: e.data * e.data }) }", blob = new Blob([ response ], { type: "application/javascript" }); url = URL.createObjectURL(blob); } catch (ignore) { } if (url) { expect(2); var wwp = new WebWorkerPool(url), worker = wwp.getWorker(); URL.revokeObjectURL(url); worker.onmessage = function (a) { equal(a.data.square, 49); worker.onmessage = function (b) { equal(b.data.square, 1); worker.terminate(); start(); } worker.postMessage(1); }; worker.postMessage(7); } else { expect(0); start(); } }); asyncTest("new webworker is created unless one has been reclaimed", function () { expect(5); var wwp = new WebWorkerPool("resources/counting-webworker.js"), worker1, worker2, worker3; function step1() { var count = 0; worker1 = wwp.getWorker(); worker2 = wwp.getWorker(); worker1.onmessage = worker2.onmessage = function (e) { equal(e.data.numMessages, 1); if (++count === 2) { wwp.reclaim(worker2); worker2 = null; step2(); } } worker1.postMessage(); worker2.postMessage(); } function step2() { var count = 0; worker2 = wwp.getWorker(); worker3 = wwp.getWorker(); worker1.onmessage = worker2.onmessage = function (e) { equal(e.data.numMessages, 2); if (++count === 3) finishAll(); } worker3.onmessage = function (e) { equal(e.data.numMessages, 1); if (++count === 3) finishAll(); } worker1.postMessage(); worker2.postMessage(); worker3.postMessage(); } function finishAll() { worker1.terminate(); worker2.terminate(); worker3.terminate(); start(); } step1(); }); asyncTest("reuses webworker from Blob, if browser supports Blobs", function () { var url; try { var response = "var count = 0; this.onmessage=function (e) { postMessage(++count) }", blob = new Blob([ response ], { type: "application/javascript" }); url = URL.createObjectURL(blob); } catch (ignore) { } if (url) { expect(4); var wwp = new WebWorkerPool(url), worker1 = wwp.getWorker(), worker2; function finishAll() { worker1.terminate(); worker2.terminate(); URL.revokeObjectURL(url); start(); } worker1.onmessage = function (a) { equal(a.data, 1); wwp.reclaim(worker1); worker2 = wwp.getWorker(); worker2.onmessage = function (b) { equal(b.data, 2); var count = 0; wwp.reclaim(worker2); worker1 = wwp.getWorker(); worker2 = wwp.getWorker(); worker1.onmessage = function (c) { equal(c.data, 3); if (count++) finishAll(); }; worker2.onmessage = function (c) { equal(c.data, 1); if (count++) finishAll(); }; worker1.postMessage(); worker2.postMessage(); }; worker2.postMessage(); }; worker1.postMessage(); } else { expect(0); start(); } });
JavaScript
0.000001
@@ -872,32 +872,34 @@ ker.postMessage( +%7B%7D );%0A %7D;%0A%0A w @@ -916,16 +916,18 @@ Message( +%7B%7D );%0A%7D);%0A%0A @@ -2414,32 +2414,34 @@ er1.postMessage( +%7B%7D );%0A worke @@ -2447,32 +2447,34 @@ er2.postMessage( +%7B%7D );%0A %7D%0A%0A fu @@ -2907,32 +2907,34 @@ er1.postMessage( +%7B%7D );%0A worke @@ -2940,32 +2940,34 @@ er2.postMessage( +%7B%7D );%0A worke @@ -2973,32 +2973,34 @@ er3.postMessage( +%7B%7D );%0A %7D%0A%0A fu @@ -4536,32 +4536,34 @@ er1.postMessage( +%7B%7D );%0A @@ -4577,32 +4577,34 @@ er2.postMessage( +%7B%7D );%0A %7D @@ -4634,24 +4634,26 @@ postMessage( +%7B%7D );%0A %7D @@ -4683,16 +4683,18 @@ Message( +%7B%7D );%0A %7D
d3be6a1ac653d34eb49752f155c7bb0c06b77fbf
fix exec async for older nodejs versions
testUtils/execAsync.js
testUtils/execAsync.js
'use strict'; const util = require('util'); const {exec} = require('child_process'); module.exports = util.promisify(exec);
JavaScript
0
@@ -14,20 +14,20 @@ %0A%0Aconst -util +exec = requi @@ -34,22 +34,36 @@ re(' -util') +child_process').exec ;%0Aconst %7Bexe @@ -62,14 +62,12 @@ nst -%7Bexec%7D +pify = r @@ -78,61 +78,231 @@ re(' -child_process');%0A%0Amodule.exports = util.promisify(exec) +pify');%0A%0Aconst execAsync = pify(exec, %7BmultiArgs: true%7D);%0A%0Amodule.exports = (cmd) =%3E %7B%0A%09return Promise.resolve()%0A%09%09.then(() =%3E execAsync(cmd))%0A%09%09.then((results) =%3E %7B%0A%09%09%09return %7Bstdout: results%5B0%5D, stderr: results%5B1%5D%7D;%0A%09%09%7D);%0A%7D ;%0A
6585074f11539f4f105edda6c689c49923b11cb6
fix assert for name in route.create method
lib/routing.js
lib/routing.js
import reduce from 'lodash/reduce'; import { throwHiddenError } from './util/log'; import URIjs from 'urijs'; import { assertTrimmedNonEmptyString, assertRegExp } from './util/assert'; const routesByName = {}; let routesNamesInSearchingOrder = []; export const INITIAL_STATE_NAME = ''; export const getRoutesByName = () => routesByName; export const getRoutesNamesInSearchingOrder = () => routesNamesInSearchingOrder; const registerTreeOfRoutes = (name, { url = '', params = {}, slots = {} }, parent = null) => { if (process.env.NODE_ENV !== 'production') { assertTrimmedNonEmptyString('name', name); assertRegExp(/^([a-zA-Z0-9.]+)$/, 'name', name); const sections = name.split('.'); if (parent) { if (!name.startsWith(parent.name)) { throw new Error(`child state name (${name}) must starts from parent name "${parent.name}"`); } if (`${parent.name}.${sections[sections.length - 1]}` !== name) { throw new Error(`state "${name}" has invalid count of real parents in name`); } } else { if (sections.length !== 1) { throw new Error(`state "${name}" has invalid format`); } } } const route = { url, name, path: url.replace(/\?.*$/, ''), slots, params, parent, pathMask: '', pathMaskExp: /.+/, searchParams: url.replace(/^[?]*\?/, '').split('&'), pathMaskParams: [] }; if (parent) { route.params = { ...parent.params, ...route.params }; route.slots = { ...parent.slots, ...route.slots }; route.searchParams = [ ...parent.searchParams, ...route.searchParams ]; route.path = `${parent.path.replace(/\/$/, '')}/${route.path.replace(/^\//, '')}`; route.url = `${route.path}?${route.searchParams.join('&')}`; } route.pathMaskParams = []; route.pathMask = route.path.replace(/:([^/]+)/g, ($0, paramName) => { route.pathMaskParams.push(paramName); return `{{${paramName}}}`; }); route.pathMaskExpSrc = route.path.replace(/:([^/]+)/g, () => '([^/]+)'); route.pathMaskExp = new RegExp(`^${route.pathMaskExpSrc}$`); routesByName[name] = route; routesNamesInSearchingOrder.push(name); routesNamesInSearchingOrder = routesNamesInSearchingOrder.sort((name1, name2) => { const name1segmentsLength = name1.split('.').length; const name2segmentsLength = name2.split('.').length; if (name1segmentsLength > name2segmentsLength) { return -1; } if (name1segmentsLength < name2segmentsLength) { return 1; } return 0; }); return { create: (...args) => registerTreeOfRoutes(...args, route) }; }; export const createRoute = (name, definition) => registerTreeOfRoutes(name, definition, null); export const parseSearchString = (string) => URIjs.parseQuery(string); export const calcSearchString = (params) => URIjs.buildQuery(params, true); export const compileStateHash = (name, params) => `${name}?${calcSearchString(params)}`; export const searchStateByLocation = (location) => { const name = routesNamesInSearchingOrder.find((routeName) => { const route = routesByName[routeName]; return route.pathMaskExp.test(location.pathname); }); if (!name) { return null; } const route = routesByName[name]; let params = { ...route.params }; const pathname = String(location.pathname || ''); pathname.replace(route.pathMaskExp, ($0, ...args) => { params = route.pathMaskParams.reduce((params, paramName, index) => { params[paramName] = args[index]; return params; }, params); return $0; }); const search = String(location.search || '').replace(/^\?/, ''); const searchParams = search ? parseSearchString(search) : {}; params = reduce(searchParams, (params, paramName, paramValue) => { if (route.searchParams.includes(paramName)) { params[paramName] = paramValue; } return params; }, params); return { name, params }; }; export const calcLocation = (route, params) => { const pathname = route.pathMask.replace(/{{([^}]+)}}/g, ($0, $1) => { if (params.hasOwnProperty($1)) { return params[$1]; } throwHiddenError(`Route param "${$1}" is not defined for route "${route.name}"`); return '-ERROR-'; }); const searchParams = route.searchParams.reduce((search, searchParam) => { if (params.hasOwnProperty(searchParam)) { search[searchParam] = params[searchParam]; } return search; }, {}); const location = { pathname, hash: '', search: '' }; if (searchParams) { location.search = calcSearchString(searchParams); } return location; };
JavaScript
0.000002
@@ -644,16 +644,17 @@ -zA-Z0-9 +- .%5D+)$/,
74fe0ec2fb2f8a83ebc4afc9dee4d8685c134f7c
Make velocity a bit more random
src/world/projectile.js
src/world/projectile.js
window.DEBUG_PROJECTILES = true; var Projectile = function(firedBy) { this.position = { x: 0, y: 0 }; this.velocity = { x: 0, y: 0 }; this.size = { w: 11, h: 7 }; this.renderSize = { w: 6, h: 4 }; this.firedBy = firedBy; this.lifetime = 30; this.txBody = new Image(); this.txBody.src = 'assets/textures/bullet.png'; this.draw = function(ctx) { ctx.save(); if (this.velocity.x < 0) { ctx.translate(this.position.x + this.renderSize.w, this.position.y); ctx.scale(-1, 1); } else { ctx.translate(this.position.x, this.position.y); } ctx.drawImage(this.txBody, 0, 0, this.size.w, this.size.h, 0, 0, this.renderSize.w, this.renderSize.h); ctx.restore(); if (window.DEBUG_PROJECTILES) { var sq = this.getRect(); ctx.beginPath(); ctx.rect(sq.left, sq.top, sq.width, sq.height); ctx.lineWidth = 1; ctx.strokeStyle = 'yellow'; ctx.stroke(); } }; this.update = function() { this.position.x += this.velocity.x; this.position.y += this.velocity.y; /*** Check collisions with entities ***/ var ourBox = this.getRect(); for (var i = 0; i < Map.entities.length; i++) { var entity = Map.entities[i]; if (!entity.isVulnerable) { // Probably a wall. Or a projectile. Or something. continue; } if (entity === this.firedBy) { // The entity that fired a projectile can never be harmed by itself. // For now at least. continue; } var boundingBox = entity.getRect(); if (Utils.rectIntersects(ourBox, boundingBox)) { entity.hurt(); Map.remove(this); return; } } /*** Lifetime management ***/ if (this.lifetime > 0) { this.lifetime--; } else { Map.remove(this); return; } }; this.getRect = function() { return { top: this.position.y, left: this.position.x, height: this.renderSize.h, width: this.renderSize.w, bottom: this.position.y + this.renderSize.h, right: this.position.x + this.renderSize.w }; }; };
JavaScript
0.000042
@@ -24,11 +24,12 @@ S = -tru +fals e;%0A%0A @@ -345,16 +345,46 @@ .png';%0A%0A + this.configured = false;%0A%0A this @@ -1104,32 +1104,215 @@ = function() %7B%0A + if (!this.configured) %7B%0A this.velocity.x += Math.random() - 0.5;%0A this.velocity.y += Math.random() - 0.5;%0A this.configured = true;%0A %7D%0A%0A this.pos
bc28b754dcb442841341f6b20ca6004854315c64
Add a bit code
lib/saphana.js
lib/saphana.js
/*! * Module dependencies */ var saphana = require('hdb'); var SqlConnector = require('loopback-connector').SqlConnector; var async = require('async'); var debug = require('debug')('loopback:connector:saphana');
JavaScript
0.000122
@@ -208,8 +208,131 @@ phana'); +%0A%0A%0Aexports.initialize = function initializeDataSource(dataSource, callback) %7B%0A if (!saphana) %7B%0A return;%0A %7D%0A%0A%7D;
e515367ab2d59334acf3ae48071084353a26cf8e
fix body-parser bug
lib/service.js
lib/service.js
'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const debug = require('debug')('moo:service'); const app = express(); app.use(bodyParser); app.post('/hook/github/push', function (req, res) { console.log(req.body); res.end(); }); const port = process.env.PORT || 8001; app.listen(port); debug('service is up on ' + port);
JavaScript
0.000002
@@ -177,16 +177,23 @@ dyParser +.json() );%0Aapp.p
982e9a58664c7d6879ddd9545f7c8d3c5658d8b6
Use correct property to set browser state representation.
static/global/js/app.js
static/global/js/app.js
App = Em.Application.create({ rootElement : '#content', // Define the main application controller. This is automatically picked up by // the application and initialized. ApplicationController : Em.Controller.extend({ // TODO: Is there a better way of dointg this? currentMenu: function(){ var currentState = this.get('target.location.lastSetURL'); var menu = currentState.split("/"); currentState = menu[1]||'home'; return currentState; }.property('target.location.lastSetURL') }), ApplicationView : Em.View.extend({ templateName : 'application', }), // Use this to clear an outlet EmptyView : Em.View.extend({ template : '' }), /* Home */ HomeView : Em.View.extend({ templateName : 'home' }) }); /* Routing */ // Set basic Project route App.ProjectRoute = Em.Route.extend({ route: '/projects', showProjectDetail: Em.Route.transitionTo('projects.detail'), connectOutlets : function(router, context) { require(['app/projects'], function(){ router.get('applicationController').connectOutlet('topPanel', 'projectStart'); router.get('applicationController').connectOutlet('midPanel', 'projectSearchForm'); router.get('applicationController').connectOutlet('bottomPanel', 'projectSearchResultsSection'); }); }, // The project start state. start: Em.Route.extend({ route: "/" }), // The project detail state. detail: Em.Route.extend({ route: '/:project_slug', deserialize: function(router, params) { return {slug: params.project_slug} }, serialize: function(router, context) { return {project_slug: context.slug}; }, connectOutlets: function(router, context) { require(['app/projects'], function(){ App.projectDetailController.populate(context.slug); router.get('applicationController').connectOutlet('topPanel', 'projectDetail'); }); } }) }); App.RootRoute = Em.Route.extend({ // Used for navigation showHome: Em.Route.transitionTo('home'), showProjectStart: Em.Route.transitionTo('projects.start'), // Language switching switchLanguage : function(router, event) { //TODO: implement language switch //TODO: Do class switch in a proper Ember way... $('a', '.languages').removeClass('active'); $(event.srcElement).addClass('active'); }, // The actual routing home: Em.Route.extend({ route : '/', connectOutlets: function(router, context) { router.get('applicationController').connectOutlet('topPanel', 'home'); router.get('applicationController').connectOutlet('midPanel', 'empty'); router.get('applicationController').connectOutlet('bottomPanel', 'empty'); } }), projects: App.ProjectRoute }); App.Router = Em.Router.extend({ history: 'hash', root: App.RootRoute }); $(function() { App.initialize(); });
JavaScript
0
@@ -3076,15 +3076,16 @@ -history +location : 'h
8b8d637752c4eeb8d04c2b0cbf9678254470624c
Fix lint issue
lib/targets.js
lib/targets.js
/** * @module gulp-mux/targets */ 'use strict'; var _ = require('lodash'); var path = require('path'); var fs = require('fs'); var chalk = require('chalk'); var gutil = require('gulp-util'); var DEFAULT_TARGET = 'app'; var clientFolder = 'client'; /** * Set the client folder where the available targets live * @method setClientFolder * @param {String} folder - The path to the client folder */ var setClientFolder = exports.setClientFolder = function(folder) { clientFolder = folder; }; var basenameToTarget = function(basename) { return basename === 'index' ? DEFAULT_TARGET : _(basename.split('-')).last(); }; /** * Inspect the client folder set with setClientFolder for files with a name * that matches index-<target>.html. An array of <target> names is returned * @method getAllTargets * * @returns {String[]} - The array of target names */ var getAllTargets = exports.getAllTargets = function() { var re = /index(|-[^\.]+)\.html/; return _(fs.readdirSync(clientFolder)) .filter(function(name) { return re.test(name); }) .map(function(name) { var filename = path.basename(name, '.html'); return basenameToTarget(filename); }) .sortBy() .value(); }; var checkTargets = exports.checkTargets = function(args, opts) { var message; if(!args.target) { return; } var badTargets = _.difference([].concat(args.target), getAllTargets()); if(badTargets.length !== 0) { message = 'The following targets were not found in the folder "' + clientFolder + '": ' + badTargets.join(','); gutil.log(chalk.red('(ERR) ' + message)); throw new Error(message); } if(!args.mode) { return; } if(!_.isString(args.mode)) { message = 'mode should be a string instead of: ' + args.mode.toString(); gutil.log(chalk.red('(ERR) ' + message)); throw new Error(message); } if(args.mode !== 'prod' && args.mode !== 'dev') { message = 'valid values for mode are "prod" or "dev", instead got: ' + args.mode.toString(); gutil.log(chalk.red('(ERR) ' + message)); throw new Error(message); } }; var checkSingleTarget = exports.checkSingleTarget = function(args, opts) { var message; checkTargets(args, opts); if(_.isArray(args.target) && args.target.length > 1) { message = 'Only a single target can be used with this task, instead got: ' + args.target.toString(); gutil.log(chalk.red('(ERR) ' + message)); throw new Error(message); } }; var askForTargets = function(taskname, defaultTargets, defaultMode, checkFn) { taskname = taskname || ''; delete require.cache[require.resolve('yargs')]; var yargs = require('yargs'); return yargs.usage(chalk.cyan('Usage: $0 ' + taskname)) .alias('t', 'target') .default('t', defaultTargets) .alias('m', 'mode') .string('m') .default('m', defaultMode) .example(chalk.white('$0 ' + taskname), chalk.cyan('Run the gulp task for all available targets.')) .example(chalk.white('$0 ' + taskname + ' -t a'), chalk.cyan('Run the gulp task, only for target a.')) .example(chalk.white('$0 ' + taskname + ' -t a -t b --target c'), chalk.cyan('Run the gulp task, for targets a, b, and c.')) .example(chalk.white('$0 ' + taskname + ' -t a -t b -m prod'), chalk.cyan('Run the gulp task, for targets a, b in prod mode.')) .describe('t', chalk.cyan('Run the gulp task for each of the specified distribution target[s]')) .describe('m', chalk.cyan('Run the gulp task in the specified mode (prod or dev)')) .check(checkFn) .argv; }; /** * Create and return the yargs object containing the multiple targets provided * on the command line with -t and the mode if provided with -m. * @method askForMultipleTargets * @param {String} taskname - The name of the task that will accept multiple targets. * * @returns {Object} - The yargs object */ exports.askForMultipleTargets = function(taskname) { return askForTargets(taskname, getAllTargets(), 'dev', checkTargets); }; /** * Create and return the yargs object containing the single target provided on * the command line with -t and the mode if provided with -m. * @method askForSingleTarget * @param {String} taskname - The name of the task that will accept multiple targets. * * @returns {Object} - The yargs object */ exports.askForSingleTarget = function(taskname) { return askForTargets(taskname, getAllTargets()[0], 'dev', checkSingleTarget); };
JavaScript
0.000006
@@ -4184,17 +4184,16 @@ s);%0A%7D;%0A%0A -%0A /**%0A * C
5631e7e62434de7cabf1b6fd22cce60c6e699be6
Remove transitional defensive code in hashchange.js
static/js/hashchange.js
static/js/hashchange.js
var hashchange = (function () { var exports = {}; var expected_hash; var changing_hash = false; // Some browsers zealously URI-decode the contents of // window.location.hash. So we hide our URI-encoding // by replacing % with . (like MediaWiki). exports.encodeHashComponent = function (str) { return encodeURIComponent(str) .replace(/\./g, '%2E') .replace(/%/g, '.'); }; function decodeHashComponent(str) { return decodeURIComponent(str.replace(/\./g, '%')); } function set_hash(hash) { var location = window.location; if (history.pushState) { if (hash === '' || hash.charAt(0) !== '#') { hash = '#' + hash; } // IE returns pathname as undefined and missing the leading / var pathname = location.pathname; if (pathname === undefined) { pathname = '/'; } else if (pathname === '' || pathname.charAt(0) !== '/') { pathname = '/' + pathname; } // Build a full URL to not have same origin problems var url = location.protocol + '//' + location.host + pathname + hash; history.pushState(null, null, url); } else { location.hash = hash; } } exports.changehash = function (newhash) { if (changing_hash) { return; } $(document).trigger($.Event('hashchange.zulip')); set_hash(newhash); util.reset_favicon(); }; // Encodes an operator list into the // corresponding hash: the # component // of the narrow URL exports.operators_to_hash = function (operators) { var hash = '#'; if (operators !== undefined) { hash = '#narrow'; _.each(operators, function (elem) { // Support legacy tuples. var operator = elem.operator; var operand = elem.operand; if (operator === undefined) { blueslip.error("Legacy tuple syntax passed into operators_to_hash."); operator = elem[0]; operand = elem[1]; } var sign = elem.negated ? '-' : ''; hash += '/' + sign + hashchange.encodeHashComponent(operator) + '/' + hashchange.encodeHashComponent(operand); }); } return hash; }; exports.save_narrow = function (operators) { if (changing_hash) { return; } var new_hash = exports.operators_to_hash(operators); exports.changehash(new_hash); }; function parse_narrow(hash) { var i, operators = []; for (i=1; i<hash.length; i+=2) { // We don't construct URLs with an odd number of components, // but the user might write one. try { var operator = decodeHashComponent(hash[i]); var operand = decodeHashComponent(hash[i+1] || ''); var negated = false; if (operator[0] === '-') { negated = true; operator = operator.slice(1); } operators.push({negated: negated, operator: operator, operand: operand}); } catch (err) { return undefined; } } return operators; } function activate_home_tab() { ui.change_tab_to("#home"); narrow.deactivate(); ui.update_floating_recipient_bar(); } // Returns true if this function performed a narrow function do_hashchange(from_reload) { // If window.location.hash changed because our app explicitly // changed it, then we don't need to do anything. // (This function only neds to jump into action if it changed // because e.g. the back button was pressed by the user) // // The second case is for handling the fact that some browsers // automatically convert '#' to '' when you change the hash to '#'. if (window.location.hash === expected_hash || (expected_hash !== undefined && window.location.hash.replace(/^#/, '') === '' && expected_hash.replace(/^#/, '') === '')) { return false; } $(document).trigger($.Event('hashchange.zulip')); // NB: In Firefox, window.location.hash is URI-decoded. // Even if the URL bar says #%41%42%43%44, the value here will // be #ABCD. var hash = window.location.hash.split("/"); switch (hash[0]) { case "#narrow": ui.change_tab_to("#home"); var operators = parse_narrow(hash); if (operators === undefined) { // If the narrow URL didn't parse, clear // window.location.hash and send them to the home tab set_hash(''); activate_home_tab(); return false; } var narrow_opts = { select_first_unread: true, change_hash: false, // already set trigger: 'hash change' }; if (from_reload !== undefined && page_params.initial_narrow_pointer !== undefined) { narrow_opts.from_reload = true; } narrow.activate(operators, narrow_opts); ui.update_floating_recipient_bar(); return true; case "": case "#": activate_home_tab(); break; case "#subscriptions": ui.change_tab_to("#subscriptions"); break; case "#administration": ui.change_tab_to("#administration"); break; case "#settings": ui.change_tab_to("#settings"); break; } return false; } function hashchanged(from_reload) { changing_hash = true; var ret = do_hashchange(from_reload); changing_hash = false; return ret; } exports.initialize = function () { // jQuery doesn't have a hashchange event, so we manually wrap // our event handler window.onhashchange = blueslip.wrap_function(hashchanged); hashchanged(true); }; return exports; }()); if (typeof module !== 'undefined') { module.exports = hashchange; }
JavaScript
0
@@ -1800,222 +1800,8 @@ d;%0A%0A - if (operator === undefined) %7B%0A blueslip.error(%22Legacy tuple syntax passed into operators_to_hash.%22);%0A operator = elem%5B0%5D;%0A operand = elem%5B1%5D;%0A %7D%0A%0A
283c333a331a5f55377edbb16290c95f2adcdd78
Fix typo
static/js/place_list.js
static/js/place_list.js
// js for place listing // popup DOM for a particular place. HTML with name, description, etc. function popupForPlace(place) { return "<span id='place-name'>" + place['name'] + "</span><br/>" } // adds a given place to the leaflet map as a marker // TODO: give it an alphabetical or numerical ID function addPlaceToMap(place) { console.log("adding marker: " + popupForPlace(place)) L.marker([place['lat'], place['lon']]).addTo(map).bindPopup(popupForPlace(place)) } // updates the place list for the given parseid function updatePlaceList(parseid) { placeList = $('ul#place-list') $.get('/itinerary/' + parseid, function(data) { console.log("received list of places:"); console.log(data); var places = data['itinerary']; for(i in places) { console.log(places[i].name); placeList.append("<li data-json='"+JSON.stringify(places[i])+"' class='place-item'>" + places[i].name + '</li>'); addPlaceToMap(places[i]); } }); } $(document).ready(function() { // TODO: change this hardcoded ID to be dynamic var testId = 'Mw3O68vpF8'; updatePlaceList('Mw3O68vpF8'); $("ul#place-list").sortable({ opacity: 0.6, cursor: 'move', // save itinerary when user reorders list update: function( event, ui ) { var itin = {"itinerary" : []}; $("ul#place-list").each(function( index ) { $(this).find("li").each(function(){ console.log($(this).data("json")); itin.itinerary.push($(this).data("json")); }); }); console.log(itin); $.post("/itinerary/" + testId, JSON.stringify(itin, function(data) { console.log("Saved new itinerary order") console.log(data); }, "json"); } }); });
JavaScript
0.999999
@@ -1794,16 +1794,17 @@ ify(itin +) , functi @@ -1870,16 +1870,17 @@ order%22) +; %0A
84aacb89c176ce2631c864c93bb32bcbb774a473
Add google analytics setup code
static/js/thirdparty.js
static/js/thirdparty.js
const LogFit = require('logfit'); const Rollbar = require('rollbar'); const varsnap = require('varsnap'); function setupRollbar() { const rollbarConfig = { accessToken: process.env.ROLLBAR_CLIENT_TOKEN, captureUncaught: true, payload: { environment: process.env.ENV, } }; return Rollbar.init(rollbarConfig); } function setupLogfit() { const logfit = new LogFit({ source: process.env.LOGFIT_CLIENT_TOKEN, }); logfit.report(); } function setupVarsnap() { varsnap.updateConfig({ varsnap: 'true', env: process.env.ENV, branch: process.env.GIT_BRANCH, producerToken: process.env.VARSNAP_PRODUCER_TOKEN, consumerToken: process.env.VARSNAP_CONSUMER_TOKEN, }); } function setupSegment() { // eslint-disable-next-line !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t,e){var n=document.createElement("script");n.type="text/javascript";n.async=!0;n.src="https://cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(n,a);analytics._loadOptions=e};analytics.SNIPPET_VERSION="4.1.0"; analytics.load(process.env.SEGMENT_TOKEN); analytics.page(); }}(); } module.exports = { setupRollbar: setupRollbar, setupLogfit: setupLogfit, setupSegment: setupSegment, setupVarsnap: setupVarsnap, };
JavaScript
0
@@ -710,24 +710,470 @@ N,%0A %7D);%0A%7D%0A%0A +function setupGoogleAnalytics() %7B%0A var script = document.createElement('script');%0A script.onload = function () %7B%0A window.dataLayer = window.dataLayer %7C%7C %5B%5D;%0A function gtag()%7Bwindow.dataLayer.push(arguments);%7D%0A gtag('js', new Date());%0A gtag('config', process.env.GOOGLE_ANALYTICS_TOKEN);%0A %7D;%0A script.src = 'https://www.googletagmanager.com/gtag/js?id=' + process.env.GOOGLE_ANALYTICS_TOKEN;%0A document.head.appendChild(script);%0A%7D%0A%0A function set @@ -2380,11 +2380,57 @@ arsnap,%0A + setupGoogleAnalytics: setupGoogleAnalytics,%0A %7D;%0A
055b13a7a830cd6576002bb7b2bb63c8383d8f06
Update code comments in topic_data.
static/js/topic_data.js
static/js/topic_data.js
const Dict = require('./dict').Dict; const FoldDict = require('./fold_dict').FoldDict; let stream_dict = new Dict(); // stream_id -> array of objects exports.stream_has_topics = function (stream_id) { if (!stream_dict.has(stream_id)) { return false; } const history = stream_dict.get(stream_id); return history.has_topics(); }; exports.topic_history = function (stream_id) { const topics = new FoldDict(); const self = {}; self.has_topics = function () { return !topics.is_empty(); }; self.add_or_update = function (opts) { const name = opts.name; let message_id = opts.message_id || 0; message_id = parseInt(message_id, 10); const existing = topics.get(name); if (!existing) { topics.set(opts.name, { message_id: message_id, pretty_name: name, historical: false, count: 1, }); return; } if (!existing.historical) { existing.count += 1; } if (message_id > existing.message_id) { existing.message_id = message_id; existing.pretty_name = name; } }; self.maybe_remove = function (topic_name) { const existing = topics.get(topic_name); if (!existing) { return; } if (existing.historical) { // We can't trust that a topic rename applied to // the entire history of historical topic, so we // will always leave it in the sidebar. return; } if (existing.count <= 1) { topics.del(topic_name); return; } existing.count -= 1; }; self.add_history = function (server_history) { // This method populates historical topics from the // server. We have less data about these than the // client can maintain for newer topics. _.each(server_history, function (obj) { const name = obj.name; const message_id = obj.max_id; const existing = topics.get(name); if (existing) { if (!existing.historical) { // Trust out local data more, since it // maintains counts. return; } } // If we get here, we are either finding out about // the topic for the first time, or we are getting // more current data for it. topics.set(name, { message_id: message_id, pretty_name: name, historical: true, }); }); }; self.get_recent_names = function () { const my_recents = topics.values(); const missing_topics = unread.get_missing_topics({ stream_id: stream_id, topic_dict: topics, }); const recents = my_recents.concat(missing_topics); recents.sort(function (a, b) { return b.message_id - a.message_id; }); const names = _.map(recents, function (obj) { return obj.pretty_name; }); return names; }; return self; }; exports.remove_message = function (opts) { const stream_id = opts.stream_id; const name = opts.topic_name; const history = stream_dict.get(stream_id); // This is the special case of "removing" a message from // a topic, which happens when we edit topics. if (!history) { return; } // This is the normal case of an incoming message. history.maybe_remove(name); }; exports.find_or_create = function (stream_id) { let history = stream_dict.get(stream_id); if (!history) { history = exports.topic_history(stream_id); stream_dict.set(stream_id, history); } return history; }; exports.add_message = function (opts) { const stream_id = opts.stream_id; const message_id = opts.message_id; const name = opts.topic_name; const history = exports.find_or_create(stream_id); history.add_or_update({ name: name, message_id: message_id, }); }; exports.add_history = function (stream_id, server_history) { const history = exports.find_or_create(stream_id); history.add_history(server_history); }; exports.get_server_history = function (stream_id, on_success) { const url = '/json/users/me/' + stream_id + '/topics'; channel.get({ url: url, data: {}, success: function (data) { const server_history = data.topics; exports.add_history(stream_id, server_history); on_success(); }, }); }; exports.get_recent_names = function (stream_id) { const history = exports.find_or_create(stream_id); return history.get_recent_names(); }; exports.reset = function () { // This is only used by tests. stream_dict = new Dict(); }; window.topic_data = exports;
JavaScript
0
@@ -131,24 +131,28 @@ -%3E -array of +topic_history object -s %0A%0Aex @@ -393,32 +393,225 @@ n (stream_id) %7B%0A + /*%0A Each stream has a dictionary of topics.%0A The main getter of this object is%0A get_recent_names, and we just sort on%0A the fly every time we are called.%0A */%0A%0A const topics
590839b4b009cf5d8ac4921e932ae47120fcb869
Fix errors in lib/updates
lib/updates.js
lib/updates.js
'use strict'; module.exports = {}; const error = require('http-errors'); const friends = require('./store/friends'); const blockList = require('./store/block-list'); const subscriptions = require('./store/subscriptions'); const pushAll = (arr, otherArr) => { Array.prototype.push.apply(arr, otherArr); } const recipients = (senderEmail, text) => { const result = []; let senderId = null; let filter = null; // get connected friends return friends.findByEmail(senderEmail) .then(sender => { // find sender id if (!sender) throw error.NotFound('Unknown user '+senderEmail); senderId = sender.id; }) .then(() => { // get block list return blockList.blocking(senderEmail).then(blocking => { filter = blocking.map(b => b.requestor); }) }) .then(() => { // find friends of sender return friends.list(senderEmail).then(list => { const subscribers = list .filter(f => blockingUsers.indexOf(f.id) < 0) .map(item => item.email); pushAll(result, subscribers); }); }) .then(() => { // find other mentioned users, filter through blocklist const mentioned = parseMentions(text); return friends.findMultiple(mentioned).then(list => { const subscribers = list .filter(f => blockingUsers.indexOf(f.id) < 0) .map(item => item.email); pushAll(result, subscribers); }); }) .then(() => { // find subscribers return subscriptions.findByTarget(senderId).then(subscribers => { pushAll(result, subscribers.map(s => s.subscriber)); }); }) .then(() => result); } const parseMentions = (text) => { // extremely simplified, any '@' surrounded by non-whitespace is considered a mention const re = /([^\s]+@[^\s]+)/ig return text.match(re); } Object.assign(module.exports, {recipients});
JavaScript
0.000004
@@ -406,22 +406,29 @@ let -filt +blockingUs er +s = null; @@ -821,17 +821,23 @@ -filt +blockingUs er +s = - blo
f2e72f33a948b34f1036c7a13a10555b03e3c086
Fix issue with walking paths instead of watching them. (Thanks to @mbibee and @betaveros.)
lib/watcher.js
lib/watcher.js
var fs = require('fs'); var path = require('path'); var logger = require('./logger'); module.exports = watcher; var dirsToIgnore = /^(?:(?:node_modules|AppData)$|\.)/; function watcher(paths, extensions, callback) { paths.forEach(function(path) { walk(path, true); }); function watch(path_, isParentDir) { fs.stat(path_, function(err, stats) { if (!err) { if (stats.isDirectory()) { if (!dirsToIgnore.test(path.basename(path_))) { walk(path_); } else if (isParentDir) { walk(path_); } } else if (extensions.test(path.extname(path_))) { try { fs.watchFile(path_, { persistent: true, interval: 100 }, function(curr, prev) { if (curr.nlink && (curr.mtime.getTime() != prev.mtime.getTime())) { callback(path_); } }); logger.info('Watching ' + path_); } catch (e) { logger.error(e.message); } } } }); } function walk(path_) { fs.readdir(path_, function(err, files) { if (!err) { files.forEach(function(filename) { watch(path_ + path.sep + filename, false); }); } }); } }
JavaScript
0
@@ -248,26 +248,27 @@ th) %7B%0A wa -lk +tch (path, true)
20123af50c751120df75454629b47a057a18167e
Use `Symbol.for` to ensure global uniqueness
symbol-is-observable.js
symbol-is-observable.js
'use strict'; module.exports = require('es6-symbol')('isObservable');
JavaScript
0.000002
@@ -46,16 +46,20 @@ symbol') +.for ('isObse
ca96600b11118f530c9e04a2f4304d061ff820c5
fix comments
lib/wolfram.js
lib/wolfram.js
import Promise from 'bluebird'; import nconf from 'nconf'; import R from 'ramda'; import wolframalpha from 'wolfram-alpha'; import sentry from './config/sentry'; function queryWolf(wolf, query) { return new Promise((resolve, reject) => { wolf.query(query, (err, results) => { if (err) return reject(err); return resolve(results); }); }); } function wolfram(bot, msg, query) { // if (!nconf.get('WOLFRAM_KEY')) { // return bot.sendMessage(msg.channel, 'Please setup Wolfram in config.js to use the **`!wolfram`** command.'); // } if (!query) { bot.sendMessage(msg.channel, 'Usage: !wolfram query'); } let wolf = wolframalpha.createClient(nconf.get('WOLFRAM_KEY')); queryWolf(wolf, query) .then(R.nth(1)) .tap(data => { if (!data) throw new Error('No results found'); }) .then(R.prop('subpods')) .then(R.nth(0)) .then(R.prop('image')) .then(text => bot.sendMessage(msg.channel, text)) .catch(err => { sentry.captureError(err); bot.sendMessage(msg.channel, `Error: ${err.message}`); }); } export default { wolfram: wolfram, wfa: wolfram };
JavaScript
0.000001
@@ -397,19 +397,16 @@ ery) %7B%0A - // if (!nc @@ -432,19 +432,16 @@ Y')) %7B%0A - // retur @@ -549,11 +549,8 @@ );%0A - // %7D%0A%0A
71118a0ac9be9964eaa7c758bb3452861e77c219
Tidy `t/coverage/replace.t.js`.
t/coverage/replace.t.js
t/coverage/replace.t.js
#!/usr/bin/env node require('./proof')(1, function (step, Strata, tmp, insert, serialize, deepEqual, equal) { function forward (name) { return function () { return fs[name].apply(fs, arguments) } } var fs = require('fs'), path = require('path'), proxy = {} for (var x in fs) { if (x[0] != '_') proxy[x] = forward(x) } proxy.unlink = function (file, callback) { var error = new Error() error.code = 'EACCES' callback(error) } var strata = new Strata({ directory: tmp, fs: proxy, leafSize: 3 }) step(function () { serialize(__dirname + '/../basics/fixtures/split.before.json', tmp, step()) }, function () { strata.open(step()) }, function () { insert(step, strata, [ 'b' ]) }, [function () { strata.balance(step()) }, function (_, error) { equal(error.code, 'EACCES', 'unlink error') }]) })
JavaScript
0
@@ -87,19 +87,8 @@ ize, - deepEqual, equ
56e321c891bd56bd79deea81e7be1794b4c2b308
Remove tests for `_reshape`.
t/paxos/legislator.t.js
t/paxos/legislator.t.js
require('proof')(17, prove) function prove (assert) { var Legislator = require('../../legislator') var signal = require('signal') var Legislator = require('../../legislator'), signal = require('signal') signal.subscribe('.bigeasy.paxos.invoke'.split('.'), function (id, method, vargs) { if (id == '0') { // console.log(JSON.stringify({ method: method, vargs: vargs })) } }) var time = 0, gremlin var options = { Date: { now: function () { return time } }, parliamentSize: 5, ping: 1, timeout: 2, retry: 5 } signal.subscribe('.bigeasy.paxos.invoke'.split('.'), function (id, method, vargs) { if (id == '0') { // console.log(JSON.stringify({ method: method, vargs: vargs })) } }) ! function () { var legislator = new Legislator(0, '1') legislator._schedule(0, { id: 'scheduled', type: 'scheduled', delay: 0 }) legislator._schedule(0, { id: 'removed', delay: 0 }) legislator._unschedule('removed') var wasScheduled = false legislator._whenScheduled = function () { wasScheduled = true } legislator._whenRemoved = function () { throw new Error } assert(legislator.checkSchedule(0), 'check schedule') assert(wasScheduled, 'scheduled') } () ! function () { var legislator = new Legislator(0, '1') assert(legislator._expand.call({ collapsed: true }), null, 'expand already electing') assert(legislator._expand.call({ parliamentSize: 3, government: { majority: [ 0, 1 ], minority: [ 2 ] } }), null, 'expand already right size') assert(legislator._expand.call({ parliamentSize: 5, id: 0, government: { majority: [ 0, 1 ], minority: [ 2 ] }, _peers: { 0: { timeout: 0 }, 1: { timeout: 0 }, 2: { timeout: 0 }, 3: { timeout: 0 } } }), null, 'expand not enough present') assert(legislator._expand.call({ parliamentSize: 5, id: '0', government: { majority: [ '0', '1' ], minority: [ '2' ], constituents: [ '3', '4' ] }, _peers: { 0: { timeout: 0 }, 1: { timeout: 0 }, 2: { timeout: 0 }, 3: { timeout: 0 }, 4: { timeout: 0 } } }), { quorum: [ '0', '1', '2' ], government: { majority: [ '0', '1', '2' ], minority: [ '3', '4' ] } }, 'expand') } () ! function () { var legislator = new Legislator(0, '1') assert(legislator._impeach.call({ collapsed: true }), null, 'impeach already electing') assert(legislator._impeach.call({ id: '0', timeout: 2, government: { majority: [ '0', '1', '2' ], minority: [ '3', '4' ] }, _peers: { 3: { timeout: 0 }, 4: { timeout: 1 } } }), null, 'impeach all good') assert(legislator._impeach.call({ id: '0', timeout: 2, government: { majority: [ '0', '1', '2' ], minority: [ '3', '4' ] }, _peers: { 4: { timeout: 0 } } }), null, 'impeach missing') assert(legislator._impeach.call({ id: '0', timeout: 2, government: { majority: [ '0', '1', '2' ], minority: [ '3', '4' ], constituents: [ '5' ] }, _peers: { 3: { timeout: 2 }, 4: { timeout: 0 }, 5: { timeout: 0 } } }), { majority: [ '0', '1', '2' ], minority: [ '4', '5' ] }, 'impeach replace') assert(legislator._impeach.call({ id: '0', timeout: 2, government: { majority: [ '0', '1', '2' ], minority: [ '3', '4' ] }, _peers: { 0: { timeout: 0 }, 1: { timeout: 0 }, 2: { timeout: 0 }, 3: { timeout: 2 }, 4: { timeout: 0 } } }), { quorum: [ '0', '1', '2' ], government: { majority: [ '0', '1' ], minority: [ '2' ] } }, 'impeach shrink to three member parliament') assert(legislator._impeach.call({ id: '0', timeout: 2, government: { majority: [ '0', '1' ], minority: [ '2' ] }, _peers: { 0: { timeout: 0 }, 1: { timeout: 0 }, 2: { timeout: 2 } } }), { quorum: [ '0', '1' ], government: { majority: [ '0' ], minority: [] } }, 'impeach shrink to dictator') } () ! function () { var legislator = new Legislator(0, '1') assert(legislator._exile.call({ collapsed: true }), null, 'exile collapsed') assert(legislator._exile.call({ timeout: 2, government: { constituents: [ '3', '4' ] }, _peers: { 3: { timeout: 0 }, 4: { timeout: 1 } } }), null, 'exile all good') assert(legislator._exile.call({ timeout: 2, government: { majority: [ '0', '1' ], minority: [ '2' ], constituents: [ '3', '4' ] }, _peers: { 3: { timeout: 0 }, 4: { timeout: 2 } } }), { quorum: [ '0', '1' ], government: { majority: [ '0', '1' ], minority: [ '2' ], exiles: [ '4' ] } }, 'exile') } () ! function () { var legislator = new Legislator(0, '1') assert(legislator.reshape.call({ collapsed: false, id: '0', government: { majority: [ '0' ] }, _impeach: function () { return null }, _exile: function () { return null }, _expand: function () { return 0xaaaaaaaa } }), 0xaaaaaaaa, 'ponged not collapsed') assert(legislator.reshape.call({ collapsed: false, id: '0', government: { majority: [ '1' ] }, }) == null, 'ponged do nothing') } () }
JavaScript
0
@@ -15,9 +15,9 @@ ')(1 -7 +5 , pr @@ -6485,665 +6485,7 @@ %7D () -%0A%0A ! function () %7B%0A var legislator = new Legislator(0, '1')%0A%0A assert(legislator.reshape.call(%7B%0A collapsed: false,%0A id: '0',%0A government: %7B%0A majority: %5B '0' %5D%0A %7D,%0A _impeach: function () %7B return null %7D,%0A _exile: function () %7B return null %7D,%0A _expand: function () %7B return 0xaaaaaaaa %7D%0A %7D), 0xaaaaaaaa, 'ponged not collapsed')%0A%0A assert(legislator.reshape.call(%7B%0A collapsed: false,%0A id: '0',%0A government: %7B%0A majority: %5B '1' %5D%0A %7D,%0A %7D) == null, 'ponged do nothing')%0A %7D () %0A%7D%0A
cb8a4dd5fd582a69ced37ee2ee16fa25e5d6754c
handle notes_type
tasks/hockeyapp_puck.js
tasks/hockeyapp_puck.js
/* * grunt-hockeyapp-puck * https://github.com/dresources/grunt-hockeyapp-puck.git * * Copyright (c) 2015 rtregaskis * Licensed under the MIT license. */ var request = require('request'), fs = require('fs'), path = require('path'); module.exports = function(grunt) { 'use strict'; // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('hockeyapp_create', 'Create new app on HockeyApp via grunt', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ token: null, title: null, bundle_identifier: null, platform: 'iOS', //Android, Mac OS, Windows Phone, Custom release_type: '0', custom_release_type: null, icon:null, private: 'true' }); // warn and exit on missing options if (!options['token'] || options['token'] === undefined || options['token'] === '') { return grunt.fatal( 'token option is required!' ); } if (!options['title'] || options['title'] === undefined || options['title'] === '') { return grunt.fatal( 'title option is required!' ); } if (!options['bundle_identifier'] || options['bundle_identifier'] === undefined || options['bundle_identifier'] === '') { return grunt.fatal( 'bundle_identifier option is required!' ); } // construct form data // NB: use read stream to access IPA file var formData = { title:options.title, bundle_identifier:options.bundle_identifier, platform:options.platform, release_type:options.release_type, private:options.private }; // tidy up url var url = 'https://rink.hockeyapp.net/api/2/apps/new'; // run this asynchronously var done = this.async(); grunt.log.subhead('Creating a new app instance for '+options.title); console.log(options); console.log(formData); // fire request to server. request.post({ url: url, formData: formData, headers: { 'X-HockeyAppToken': options['token'] } }, function(error, response, body) { if (error !== null) { grunt.log.error(error); grunt.log.error('Error creating "' + options['title'] + '"'); done(false); } else { grunt.config('ha_app_id', JSON.parse(body)['public_identifier']); grunt.log.ok('Created new app "' + options['title'] + '" successfully'); done(); } }); }); grunt.registerMultiTask('hockeyapp_listteams', 'Lists teams of app', function(){ var options = this.options({ app_id:null }); // warn and exit on missing options if (!options['app_id'] || options['app_id'] === undefined || options['app_id'] === '') { return grunt.fatal( 'app_id option is required!' ); } // tidy up url var url = 'https://rink.hockeyapp.net/api/2/apps/'+options.app_id+'/app_teams'; // run this asynchronously var done = this.async(); grunt.log.subhead('List teams of app'); // fire request to server. request.get({ url: url, headers: { 'X-HockeyAppToken': options['token'] } }, function(error, response, body) { if (error !== null) { grunt.log.error(error); grunt.log.error('Error listing team to app!'); done(false); } else { body = JSON.parse(body); grunt.log.ok('Added team to app successfully'); for (var i = 0; i < body.teams.length; i++){ console.log(body.teams[i]['id'], body.teams[i]['name']); } done(); } }); }); grunt.registerMultiTask('hockeyapp_addteam', 'Add team to app', function(){ var options = this.options({ app_id:null, team_id:null }); // warn and exit on missing options if (!options['app_id'] || options['app_id'] === undefined || options['app_id'] === '') { return grunt.fatal( 'app_id option is required!' ); } if (!options['team_id'] || options['team_id'] === undefined || options['team_id'] === '') { return grunt.fatal( 'team_id option is required!' ); } // tidy up url var url = 'https://rink.hockeyapp.net/api/2/apps/'+options.app_id+'/app_teams/'+options.team_id; // run this asynchronously var done = this.async(); grunt.log.subhead('Add app to team'); // fire request to server. request.put({ url: url, headers: { 'X-HockeyAppToken': options['token'] } }, function(error, response, body) { if (error !== null) { grunt.log.error(error); grunt.log.error('Error adding team to app!'); done(false); } else { grunt.log.ok('Added team to app successfully'); done(); } }); }); grunt.registerMultiTask('hockeyapp_upload', 'Upload builds to HockeyApp via grunt', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ token: null, app_id: null, file: null, notes: 'Changelog', notify: 2, status: 2, tags: '', teams:null }); // warn and exit on missing options if (!options['token'] || options['token'] === undefined || options['token'] === '') { return grunt.fatal( 'Token option is required!' ); } else if (!options['app_id'] || options['app_id'] === undefined || options['app_id'] === '') { return grunt.fatal( 'Application id option is required!' ); } else if (!options['file'] || options['file'] === undefined || options['file'] === '') { return grunt.fatal( 'File option is required!' ); } // construct form data // NB: use read stream to access IPA file var formData = { ipa: fs.createReadStream(options['file']), status: options.status, notify: options.notify, notes: options.notes, notes_type: 1, teams: options.teams }; // tidy up url var url = 'https://rink.hockeyapp.net/api/2/apps/' + options.app_id + '/app_versions/upload'; // run this asynchronously var done = this.async(); grunt.log.subhead('Uploading "' + options['file'] + '"'); // fire request to server. request.post({ url: url, formData: formData, headers: { 'X-HockeyAppToken': options['token'] } }, function(error, response, body) { if (error !== null) { grunt.log.error(error); grunt.log.error('Error uploading "' + options['file'] + '"'); done(false); } else { grunt.log.ok('Uploaded "' + options['file'] + '" successfully'); done(); } }); }); };
JavaScript
0.000001
@@ -5738,16 +5738,33 @@ gelog',%0A +%09%09%09notes_type:1,%0A @@ -6768,17 +6768,34 @@ s_type: -1 +options.notes_type ,%0A%09%09%09tea
5aa22345577bf4403f11868bef022b0e71c2142d
drop sourcemap and unminified options
tasks/partial_bundle.js
tasks/partial_bundle.js
var path = require('path'); var minimist = require('minimist'); var runSeries = require('run-series'); var prependFile = require('prepend-file'); var constants = require('./util/constants'); var common = require('./util/common'); var _bundle = require('./util/browserify_wrapper'); var header = constants.licenseDist + '\n'; var allTransforms = constants.allTransforms; var allTraces = constants.allTraces; var mainIndex = constants.mainIndex; function isFalse(a) { return ( a === 'none' || a === 'false' ); } function inputBoolean(a, dflt) { return !a ? dflt : !isFalse(a); } function inputArray(a, dflt) { dflt = dflt.slice(); return ( isFalse(a) ? [] : !a || a === 'all' ? dflt : a.split(',') ); } if(process.argv.length > 2) { // command line var args = minimist(process.argv.slice(2), {}); // parse arguments var out = args.out ? args.out : 'custom'; var traces = inputArray(args.traces, allTraces); var transforms = inputArray(args.transforms, allTransforms); var calendars = inputBoolean(args.calendars, true); var keepindex = inputBoolean(args.keepindex, false); var sourcemaps = inputBoolean(args.sourcemaps, false); var unminified = inputBoolean(args.unminified, false); var i, t; var traceList = ['scatter']; // added by default for(i = 0; i < traces.length; i++) { t = traces[i]; if( traceList.indexOf(t) === -1 // not added before ) { if(allTraces.indexOf(t) === -1) { console.error(t, 'is not a valid trace!', 'Valid traces are:', allTraces); } else { traceList.push(t); } } } traceList = traceList.sort(); var transformList = []; for(i = 0; i < transforms.length; i++) { t = transforms[i]; if( transformList.indexOf(t) === -1 // not added before ) { if(allTransforms.indexOf(t) === -1) { console.error(t, 'is not a valid transform!', 'Valid transforms are:', allTransforms); } else { transformList.push(t); } } } transformList = transformList.sort(); var opts = { traceList: traceList, transformList: transformList, calendars: calendars, sourcemaps: sourcemaps, name: out, index: path.join(constants.pathToLib, 'index-' + out + '.js') }; if(unminified) { opts.dist = path.join(constants.pathToDist, 'plotly-' + out + '.js'); } else { opts.distMin = path.join(constants.pathToDist, 'plotly-' + out + '.min.js'); } if(!keepindex) { opts.deleteIndex = true; } console.log(opts); var tasks = []; partialBundle(tasks, opts); runSeries(tasks, function(err) { if(err) throw err; }); } // Browserify the plotly.js partial bundles function partialBundle(tasks, opts) { var name = opts.name; var index = opts.index; var dist = opts.dist; var distMin = opts.distMin; var traceList = opts.traceList; var transformList = opts.transformList; var calendars = opts.calendars; var sourcemaps = opts.sourcemaps; var deleteIndex = opts.deleteIndex; tasks.push(function(done) { var partialIndex = mainIndex; var all = ['calendars'].concat(allTransforms).concat(allTraces); var includes = (calendars ? ['calendars'] : []).concat(transformList).concat(traceList); var excludes = all.filter(function(e) { return includes.indexOf(e) === -1; }); excludes.forEach(function(t) { var WHITESPACE_BEFORE = '\\s*'; // remove require var newCode = partialIndex.replace( new RegExp( WHITESPACE_BEFORE + 'require\\(\'\\./' + t + '\'\\)' + (t === 'calendars' ? '' : ','), // there is no comma after calendars require 'g'), '' ); // test removal if(newCode === partialIndex) { console.error('Unable to find and drop require for ' + t); throw 'Error generating index for partial bundle!'; } partialIndex = newCode; }); common.writeFile(index, partialIndex, done); }); tasks.push(function(done) { var bundleOpts = { debug: sourcemaps, deleteIndex: deleteIndex, standalone: 'Plotly', pathToMinBundle: distMin }; _bundle(index, dist, bundleOpts, function() { var headerDist = header.replace('plotly.js', 'plotly.js (' + name + ')'); var headerDistMin = header.replace('plotly.js', 'plotly.js (' + name + ' - minified)'); if(dist) prependFile(dist, headerDist, common.throwOnError); if(distMin) prependFile(distMin, headerDistMin, common.throwOnError); done(); }); }); } module.exports = partialBundle;
JavaScript
0
@@ -1184,126 +1184,8 @@ se); -%0A var sourcemaps = inputBoolean(args.sourcemaps, false);%0A var unminified = inputBoolean(args.unminified, false); %0A%0A @@ -2248,40 +2248,8 @@ ars, -%0A sourcemaps: sourcemaps, %0A%0A @@ -2338,57 +2338,23 @@ js') +, %0A -%7D;%0A%0A if(unminified) %7B%0A opts. + dist - = +: pat @@ -2410,45 +2410,26 @@ js') -; +, %0A -%7D else %7B%0A opts. + distMin - = +: pat @@ -2485,23 +2485,23 @@ min.js') -; %0A %7D +; %0A%0A if @@ -2575,24 +2575,52 @@ log(opts);%0A%0A + opts.sourcemap = true;%0A%0A var task @@ -3063,17 +3063,16 @@ ourcemap -s = opts. @@ -3080,17 +3080,16 @@ ourcemap -s ;%0A va @@ -4301,17 +4301,16 @@ ourcemap -s ,%0A
ec76bd6028e8e81f713563794852a0850d90e996
Remove legacy minification webpack plugin
tasks/webpack.config.js
tasks/webpack.config.js
const webpack = require('webpack'); const path = require('path'); const config = require('./config'); const mode = require('./lib/mode'); const JS_DEV = path.resolve(config.root.dev, config.js.dev); const JS_DIST = path.resolve(config.root.dist, config.js.dist); const publicPath = config.browserSync.proxy.target ? config.browserSync.proxy.publicPath : path.join('/', config.js.dist); const webpackConfig = { mode: mode.production ? 'production' : 'development', context: JS_DEV, entry: { app: [ './main.js', ], }, output: { path: JS_DIST, filename: 'bundle.js', publicPath, }, module: { rules: [ { test: /\.js$/, exclude: path.resolve(__dirname, 'node_modules/'), loader: 'babel-loader', options: { presets: [ [ 'env', { modules: false }, ], ], }, }, ], }, resolve: { modules: [ JS_DEV, 'node_modules', 'bower_components', ], extensions: config.js.extensions, }, plugins: [], }; /** * Modify webpackConfig depends on mode */ if (mode.production) { webpackConfig.plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new webpack.NoEmitOnErrorsPlugin(), ); } else { webpackConfig.devtool = 'inline-source-map'; webpackConfig.entry.app.unshift('webpack-hot-middleware/client?reload=true'); webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); } module.exports = webpackConfig;
JavaScript
0
@@ -466,16 +466,69 @@ pment',%0A + optimization: %7B%0A minimize: mode.production%0A %7D,%0A contex @@ -1152,18 +1152,17 @@ %0A/** -%0A * Modif -y +ies web @@ -1187,17 +1187,17 @@ on mode -%0A +. */%0Aif ( @@ -1249,110 +1249,8 @@ sh(%0A - new webpack.optimize.UglifyJsPlugin(%7B%0A compress: %7B%0A warnings: false,%0A %7D,%0A %7D),%0A
ec27f2d3388815fb2ed5b347c0c2ce122b4f8348
add dummy items
demos/crud/app.js
demos/crud/app.js
window.addEventListener('WebComponentsReady', function () { document.body.style.opacity = 1; window.store = document.querySelector('#store'); window.list = document.querySelector('#list'); var flip = document.querySelector('x-flipbox'); var form = document.querySelector('form'); list.addEventListener('click', function (e) { if (e.target.__item__) { form.name = e.target.__item__.created; flip.flipped = true; } }); function closeEdit() { flip.flipped = false; list.render(); } form.addEventListener('submit', closeEdit); document.querySelector('#cancel').addEventListener('click', closeEdit); document.querySelector('#new').addEventListener('click', function (e) { form.name = Date.now(); flip.flipped = true; }); });
JavaScript
0.000001
@@ -775,12 +775,321 @@ e;%0A %7D); +%0A%0A store.size().then(function (size) %7B%0A if (size %3C 5);%0A for (var i=0; i %3C 100; i++) %7B%0A store.insert(%7B%0A created: (Date.now()+i).toString(),%0A done: false,%0A label: (Math.random() * 1e9%7C0).toString(16)%0A %7D).then(function () %7B%0A console.log('done');%0A %7D);%0A %7D%0A %7D); %0A%7D);
17f71d827f5e1167a2c4a18b5f09bcdf9f87c08d
Replace [].includes() call for node.js v4 support
test/bad-dns-warning.js
test/bad-dns-warning.js
/* * Copyright (c) 2014, 2015, 2016, 2017, Verisign, Inc. * 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 names of the copyright holders 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 Verisign, Inc. 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. */ /* global describe:false, it:false, */ "use strict"; const expect = require("expect.js"); const getdns = require("../"); const shared = require("./shared"); shared.initialize(); describe("BADDNS", () => { it("Should throw for bad add_warning_for_bad_dns", () => { expect(() => { getdns.createContext({ add_warning_for_bad_dns: "some string value", }); }).to.throwException((err) => { expect(err).to.be.an("object"); expect(err).to.be.an(TypeError); expect(err.code).to.be.an("number"); expect(err.code).to.be(getdns.RETURN_INVALID_PARAMETER); expect(err.message).to.be.an("string"); expect(err.message).to.be("add_warning_for_bad_dns"); }); }); it("Should return bad_dns", function(done) { const ctx = getdns.createContext(); const recordType = getdns.RRTYPE_TXT; const extensions = { add_warning_for_bad_dns: true, }; ctx.general("_443._tcp.www.nlnetlabs.nl", recordType, extensions, (err, result) => { expect(err).to.be(null); expect(result.replies_tree).to.be.an(Array); expect(result.replies_tree).to.not.be.empty(); result.replies_tree.forEach((reply) => { expect(reply).to.be.an("object"); expect(reply).to.not.be(null); expect(reply.bad_dns).to.be.an(Array); expect(reply.bad_dns).to.not.be.empty(); const badDnsReplies = reply.bad_dns.filter((badDns) => { const badDnsValus = [ getdns.BAD_DNS_CNAME_IN_TARGET, getdns.BAD_DNS_ALL_NUMERIC_LABEL, getdns.BAD_DNS_CNAME_RETURNED_FOR_OTHER_TYPE, ]; return badDnsValus.includes(badDns); }); expect(badDnsReplies.length).to.be(reply.bad_dns.length); }); shared.destroyContext(ctx, done); }); }); it("Should not return bad_dns if disabled", function(done) { const ctx = getdns.createContext(); const recordType = getdns.RRTYPE_TXT; const extensions = { add_warning_for_bad_dns: false, }; ctx.general("_443._tcp.www.nlnetlabs.nl", recordType, extensions, (err, result) => { expect(err).to.be(null); expect(result.replies_tree).to.be.an(Array); expect(result.replies_tree).to.not.be.empty(); result.replies_tree.forEach((reply) => { expect(reply).to.be.an("object"); expect(reply).to.not.be(null); expect(reply.bad_dns).to.not.be.ok(); }); shared.destroyContext(ctx, done); }); }); });
JavaScript
0.000002
@@ -3452,22 +3452,21 @@ s.in -cludes +dexOf (badDns) ;%0A @@ -3461,16 +3461,23 @@ (badDns) + !== -1 ;%0A
ed004aa81887f5d4c1e4228d04730d3aa9eef82b
Add "remove variable" test
test/components.spec.js
test/components.spec.js
'use strict'; var chai = require('chai'); chai.use(require('chai-dom')); var expect = chai.expect; var m = require('mithril'); var AppComponent = require('../app/scripts/components/app'); describe('app UI', function () { beforeEach(function () { m.mount(document.body, AppComponent); }); afterEach(function () { m.mount(document.body, null); }); it('should render default variables', function () { var variables = document.querySelectorAll('div.variable input'); expect(variables).to.have.length(2); expect(variables[0]).to.have.value('p'); expect(variables[1]).to.have.value('q'); }); it('should render default expressions', function () { var expressions = document.querySelectorAll('th.expression input'); expect(expressions).to.have.length(3); expect(expressions[0]).to.have.value('not p'); expect(expressions[1]).to.have.value('p and q'); expect(expressions[2]).to.have.value('p or q'); }); it('should add new variable', function () { var variables = document.querySelectorAll('div.variable'); expect(variables).to.have.length(2); variables[1].querySelector('.control-add').click(); m.redraw.sync(); expect(document.querySelectorAll('div.variable')).to.have.length(3); }); });
JavaScript
0.000032
@@ -1262,12 +1262,407 @@ %0A %7D);%0A%0A + it('should remove existing variable', function () %7B%0A var variables = document.querySelectorAll('div.variable');%0A expect(variables).to.have.length(2);%0A variables%5B0%5D.querySelector('.control-remove').click();%0A m.redraw.sync();%0A expect(document.querySelectorAll('div.variable')).to.have.length(1);%0A expect(document.querySelector('div.variable input')).to.have.value('q');%0A %7D);%0A%0A %7D);%0A
62cabf23b574415088f4e41b72d6d7f1442be7b9
Fix connection-test
test/connection-test.js
test/connection-test.js
var mongoose = require('mongoose'), async = require('async'), elasticsearch = require('elasticsearch'), config = require('./config'), Schema = mongoose.Schema, mongoosastic = require('../lib/mongoosastic'); var DummySchema = new Schema({ text: String }); var Dummy = mongoose.model('Dummy1', DummySchema, 'dummys'); describe('Elasticsearch Connection', function() { before(function(done) { mongoose.connect(config.mongoUrl, function() { Dummy.remove(function() { config.deleteIndexIfExists(['dummys'], function() { var dummies = [ new Dummy({ text: 'Text1' }), new Dummy({ text: 'Text2' }) ]; async.forEach(dummies, function(item, cb) { item.save(cb); }, function() { setTimeout(done, config.indexingTimeout); }); }); }); }); }); after(function(done) { Dummy.remove(); mongoose.disconnect(); done(); }); it('should be able to connect with default options', function(done) { DummySchema.plugin(mongoosastic); var Dummy = mongoose.model('Dummy2', DummySchema, 'dummys'); tryDummySearch(Dummy, done); }); it('should be able to connect with explicit options', function(done) { DummySchema.plugin(mongoosastic, { host: 'localhost', port: 9200 }); var Dummy = mongoose.model('Dummy3', DummySchema, 'dummys'); tryDummySearch(Dummy, done); }); it('should be able to connect with an array of hosts', function(done) { DummySchema.plugin(mongoosastic, { hosts: [ 'localhost:9200', 'localhost:9200' ] }); var Dummy = mongoose.model('Dummy4', DummySchema, 'dummys'); tryDummySearch(Dummy, done); }); it('should be able to connect with an existing elasticsearch client', function(done) { var esClient = new elasticsearch.Client({host: 'localhost:9200'}); esClient.ping({ requestTimeout: 1000 }, function(err) { if (err) { return done(err); } DummySchema.plugin(mongoosastic, { esClient: esClient }); var Dummy = mongoose.model('Dummy5', DummySchema, 'dummys'); tryDummySearch(Dummy, done); }); }); }); function tryDummySearch(model, cb) { setTimeout(function() { model.search({ query_string: { query: 'Text1' } }, function(err, results) { if (err) { return cb(err); } results.hits.total.should.eql(0); model.esClient.close(); cb(err); }); }, config.indexingTimeout); }
JavaScript
0
@@ -2383,24 +2383,33 @@ rch(%7B%0A + simple_ query_string @@ -2420,16 +2420,18 @@ + + query: ' @@ -2447,16 +2447,65 @@ -%7D%0A %7D, + %7D%0A %7D,%0A %7B%0A index: '_all'%0A %7D,%0A fun @@ -2524,32 +2524,34 @@ esults) %7B%0A + + if (err) %7B%0A @@ -2537,32 +2537,34 @@ if (err) %7B%0A + return c @@ -2573,27 +2573,31 @@ err);%0A + + %7D%0A%0A + result @@ -2624,16 +2624,18 @@ eql(0);%0A + mo @@ -2662,16 +2662,18 @@ ;%0A + cb(err); @@ -2669,24 +2669,26 @@ cb(err);%0A + %7D);%0A %7D,
2cd811d8acef001dddc8bd94704eebe2e9488ee3
test year for date object
test/core/utils/file.js
test/core/utils/file.js
import chai from 'chai' import path from 'path' import sinonChai from'sinon-chai' chai.use(sinonChai) import sinon from 'sinon' import mkdirp from 'mkdirp' import fse from 'fs-extra' import { coreUtils, abeExtend, cmsData, config } from '../../../src/cli' config.set({root: path.join(process.cwd(), 'test', 'fixtures')}) describe('coreUtils.file', function() { /** * coreUtils.file.addFolder * */ it('coreUtils.file.addFolder()', function() { this.sinon = sinon.sandbox.create(); var stub = sinon.stub(mkdirp, 'mkdirP') stub.returns({'test':'test'}); var result = coreUtils.file.addFolder('path/to/folder') chai.expect(result).to.be.a('string') chai.expect(result).to.equal('path/to/folder') mkdirp.mkdirP.restore() }); /** * coreUtils.file.removeFolder * */ it('coreUtils.file.removeFolder()', function() { this.sinon = sinon.sandbox.create(); var stub = sinon.stub(fse, 'remove') stub.returns({}); var result = coreUtils.file.removeFolder('path/to/folder') chai.expect(result).to.be.a('string') chai.expect(result).to.equal('path/to/folder') fse.remove.restore() }); /** * coreUtils.file.getDate * */ it('coreUtils.file.getDate()', function() { this.sinon = sinon.sandbox.create(); var stub = sinon.stub(cmsData.fileAttr, 'get') stub.returns({d: '2016-12-07T13:04:18.810Z'}); var result = coreUtils.file.getDate(path.join(config.root, config.data.url, 'article-abe-d20161207T130418810Z.json')) chai.expect(result.toString()).to.equal('Wed Dec 07 2016 14:04:18 GMT+0100 (CET)') cmsData.fileAttr.get.restore() }); /** * coreUtils.file.addDateIsoToRevisionPath * */ it('coreUtils.file.addDateIsoToRevisionPath()', function() { var date = '20161207T132049118Z' var urlRevision = path.join(config.root, config.data.url, 'article-abe-d' + date + '.json') this.sinon = sinon.sandbox.create(); var stub = sinon.stub(cmsData.revision, 'removeStatusAndDateFromFileName') stub.returns(date); var stub2 = sinon.stub(cmsData.fileAttr, 'add') stub2.returns(urlRevision); var result = coreUtils.file.addDateIsoToRevisionPath(path.join(config.root, config.data.url, 'article.json'), 'draft') chai.expect(result).to.be.a('string') chai.expect(result).to.equal(urlRevision) cmsData.revision.removeStatusAndDateFromFileName.restore() cmsData.fileAttr.add.restore() }); /** * coreUtils.file.exist * */ it('coreUtils.file.exist()', function() { this.sinon = sinon.sandbox.create(); var stub = sinon.stub(fse, 'statSync') stub.returns(''); var result = coreUtils.file.exist('path/to/file') chai.expect(result).to.be.true fse.statSync.restore() }); });
JavaScript
0.000439
@@ -1547,16 +1547,15 @@ ult. -toString +getYear ()). @@ -1567,49 +1567,11 @@ ual( -'Wed Dec 07 2016 14:04:18 GMT+0100 (CET)' +116 )%0A
be83a740aadb72914b0b7b202434755592ad23f4
Modify test to allow for multiple change listeners
test/crud_store_test.js
test/crud_store_test.js
'use strict'; var CrudStore = require('../lib/index').Store; var CrudStoreActions = require('../lib/index').Actions; var Record = require('immutable').Record; var Iterable = require('immutable').Iterable; var chai = require('chai'); chai.use(require('dirty-chai')); var expect = chai.expect; var sinon = require('sinon'); chai.use(require('sinon-chai')); describe('crud_store', function () { var store; var actions; var ViewModel; beforeEach(function () { ViewModel = Record({ id: null }); store = CrudStore.extend({ viewModel: ViewModel }).instance(); actions = CrudStoreActions.boundTo(store); }); describe('#initialize', function () { it('throws an error if viewModel is not set', function () { expect(function () { store = CrudStore.instance(); }).to.throw('viewModel must be set'); }); it('throws an error if collection is not set', function () { expect(function () { store = CrudStore.extend({ viewModel: ViewModel, collection: null }).instance(); }).to.throw('collection must be set'); }); }); describe('#addChangeListener', function () { it('binds a callback to when the store changes', function () { var spy = sinon.spy(); store.addChangeListener(spy); actions.create(); expect(spy).to.have.been.called(); }); it('throws an error if the param is not a function', function () { expect(function () { store.addChangeListener(); }).to.throw('is not a function'); }); }); describe('#removeChangeListener', function () { it('removes an already bound callback', function () { var spy = sinon.spy(); store.addChangeListener(spy); store.removeChangeListener(spy); actions.create(); expect(spy).not.to.have.been.called(); }); it('throws an error if the param is not a function', function () { expect(function () { store.removeChangeListener(); }).to.throw('is not a function'); }); it('throws an error if the callback is not already bound'); }); describe('#get', function () { it('returns null if requested id is not in storage', function () { expect(store.get(77)).to.be.null(); }); it('returns an instance of the specified view model', function () { actions.create({ id: 77 }); expect(store.get(77)).to.be.instanceOf(ViewModel); }); it('returns the same view model instance if nothing changed', function () { actions.create({ id: 77 }); expect(store.get(77)).to.equal(store.get(77)); }); }); describe('#getAll', function () { it('returns an empty Iterable if nothing is in storage', function () { expect(store.getAll().size).to.equal(0); }); it('returns an Iterable of the specified view model', function () { actions.create({ id: 77 }); var viewModels = store.getAll(); expect(viewModels).to.be.instanceOf(Iterable); expect(viewModels.size).to.equal(1); store.getAll().forEach(function (viewModel) { expect(viewModel).to.be.instanceOf(ViewModel); }); }); it('returns the same Iterable instance if nothing changed', function () { actions.create({ id: 77 }); expect(store.getAll()).to.equal(store.getAll()); }); it('works even when models are destroyed', function () { actions.create({ id: 77 }); expect(store.getAll().size).to.equal(1); actions.destroy({ id: 77 }); expect(store.getAll().size).to.equal(0); }); }); });
JavaScript
0
@@ -1170,15 +1170,25 @@ it(' -binds a +can bind multiple cal @@ -1192,16 +1192,17 @@ callback +s to when @@ -1241,32 +1241,63 @@ %7B%0A var spy +1 = sinon.spy();%0A var spy2 = sinon.spy();%0A @@ -1321,32 +1321,70 @@ angeListener(spy +1);%0A store.addChangeListener(spy2 );%0A actions @@ -1410,16 +1410,59 @@ pect(spy +1).to.have.been.called();%0A expect(spy2 ).to.hav
11505897764ac366eb0388c81344cf693f8ce40a
Fix typo
test/dtsCreator.spec.js
test/dtsCreator.spec.js
'use strict'; var path = require('path'); var assert = require('assert'); var DtsCreator = require('../lib/dtsCreator').DtsCreator; describe('DtsCreator', () => { var creator = new DtsCreator(); describe('#create', () => { it('returns DtsContent instance simple css', done => { creator.create('test/testStyle.css').then(content => { assert.equal(content.contents.length, 1); assert.equal(content.contents[0], "export const myClass: string;") done(); }); }); it('returns DtsContent instatnce from composing css', done => { creator.create('test/composer.css').then(content => { assert.equal(content.contents.length, 1); assert.equal(content.contents[0], "export const root: string;") done(); }); }) }); describe('#modify path', () => { it('can be set outDir', done => { new DtsCreator({searchDir: "test", outDir: "dist"}).create('test/testStyle.css').then(content => { assert.equal(path.relative(process.cwd(), content.outputFilePath), "dist/testStyle.css.d.ts"); done(); }); }); }); }); describe('DtsContent', () => { describe('#tokens', () => { it('returns original tokens', done => { new DtsCreator().create('test/testStyle.css').then(content => { assert.equal(content.tokens[0], "myClass"); done(); }); }); }); describe('#inputFilePath', () => { it('returns original CSS file name', done => { new DtsCreator().create('test/testStyle.css').then(content => { assert.equal(path.relative(process.cwd(), content.inputFilePath), "test/testStyle.css"); done(); }); }); }); describe('#formatted', () => { it('returns formatted .d.ts string', done => { new DtsCreator().create('test/testStyle.css').then(content => { assert.equal(content.formatted, "export const myClass: string;"); done(); }); }); it('returns empty object exportion when result list does not any items', done => { new DtsCreator().create('test/empty.css').then(content => { assert.equal(content.formatted, "export default {};"); done(); }); }); }); describe('#writeFile', () => { it('writes a file', done => { new DtsCreator().create('test/testStyle.css').then(content => { return content.writeFile(); }).then(() => { done(); }); }); }); });
JavaScript
0.999999
@@ -534,17 +534,16 @@ nt insta -t nce from @@ -1990,16 +1990,20 @@ on when +the result l @@ -2010,20 +2010,14 @@ ist -doe +ha s no -t any ite
2fbdcec41efbf91dfb6f21d73459463878788b9a
exclude specific browser versions
test/helper/Supports.js
test/helper/Supports.js
import UserAgentParser from "ua-parser-js"; var parsed = new UserAgentParser().getBrowser(); var name = parsed.name; var version = parseInt(parsed.major); console.log(name, version); function is(browser, above){ above = above || 0; return name.includes(browser) && version >= above; } function isnt(browser, below){ below = below || Infinity; return !(name.includes(browser) && version <= below); } export default { //setValueCurveAtTime interpolates INTERPOLATED_VALUE_CURVE : is("Chrome", 46), //waveshaper has correct value at 0 WAVESHAPER_0_POSITION : isnt("Safari"), //has stereo panner node STEREO_PANNER_NODE : isnt("Safari"), //can schedule a mixture of curves correctly ACCURATE_SIGNAL_SCHEDULING : isnt("Safari"), //can disconnect from a specific node NODE_DISCONNECT : is("Chrome", 50), //stereo panner is equal power panning EQUAL_POWER_PANNER : isnt("Firefox"), //doesn't seem to support the pluck synth PLUCK_SYNTH : isnt("Safari"), //offline rendering matches Chrome closely //chrome is the platform the files were rendered on //so it is the default for continuity testing CHROME_AUDIO_RENDERING : is("Chrome"), //has float time domain analyser ANALYZE_FLOAT_TIME_DOMAIN : AnalyserNode && typeof AnalyserNode.prototype.getFloatTimeDomainData === "function", //if the tests run in focus ONLINE_TESTING : is("Chrome", 72), //the close method resolves a promise AUDIO_CONTEXT_CLOSE_RESOLVES : isnt("Firefox") && isnt("Safari", 10), //if it supports gUM testing GET_USER_MEDIA : isnt("Safari"), RUN_EXAMPLES : isnt("Safari", 10) };
JavaScript
0.000003
@@ -156,37 +156,8 @@ );%0A%0A -console.log(name, version);%0A%0A func @@ -378,493 +378,199 @@ %0A%7D%0A%0A -export default %7B%0A%09//setValueCurveAtTime +function i +s nt +V er -polates%0A%09INTERPOLATED_VALUE_CURVE : is(%22Chrome%22, 46),%0A%09//waveshaper has correct value at 0%0A%09WAVESHAPER_0_POSITION : isnt(%22Safari%22),%0A%09//has stereo panner node%0A%09STEREO_PANNER_NODE : isnt(%22Safari%22),%0A%09//can schedule a mixture of curves correctly%0A%09ACCURATE_SIGNAL_SCHEDULING : isnt(%22Safari%22),%0A%09//can disconnect from a specific node%0A%09NODE_DISCONNECT : is(%22Chrome%22, 50),%0A%09//stereo panner is equal power panning%0A%09EQUAL_POWER_PANNER : isnt(%22Firefox%22 +sion(browser, version)%7B%0A%09return !(name.includes(browser) && version === version);%0A%7D%0A%0Aexport default %7B%0A%09//can disconnect from a specific node%0A%09NODE_DISCONNECT : is(%22Chrome%22, 50 ),%0A%09 @@ -1015,32 +1015,41 @@ INE_TESTING : is +ntVersion (%22Chrome%22, 72),%0A @@ -1048,9 +1048,9 @@ %22, 7 -2 +1 ),%0A%09
570b7183a37713f732b9a575eaae926eb7266569
test - ensure dir deletetion before ncp.copy
test/helpers/pretest.js
test/helpers/pretest.js
// todo: rewrite this file. Relying on git is ok, until testing out on a system without // git.. This pretest script should download the latest targz from master repo and untar // at the appropriate location. var child = require('child_process'), path = require('path'), ncp = require('ncp').ncp; // npm pretest script // Prepares the necessary file structure before testing out the build // script. // // This will create the test/fixtures directory by cloning (or pulling // if already there) the main html5-boilerplate repo. // var repo = 'https://github.com/h5bp/html5-boilerplate.git', basedir = path.resolve('test'), cloned = path.existsSync(path.join(basedir, 'fixtures/h5bp')); // Clone or pull first var cmd = cloned ? ['pull'] : ['clone', repo, 'fixtures/h5bp']; console.log((cloned ? 'Pulling' : 'Cloning') + ' ' + repo); spawn('git', cmd, { cwd: cloned ? path.join(basedir, 'fixtures/h5bp') : basedir }, function(code) { if(code) throw new Error('Got errors with git ' + cmd); // Do some editions on h5bp repo's file, mainly to test some advanced optimization like // css improrts inline etc. // Grab the base jQuery UI CSS Theme, does have a good test case for the css import // inline, on several levels // now done by coping local files in the repo ncp('test/fixtures/themes', 'test/fixtures/h5bp/css', function(e) { if(e) throw e; console.log('All ok'); }); }); // little spawn helper, piping out the child standard output / error // to the current process. function spawn(cmd, args, o, cb) { var stderr = [], stdout = []; var ch = child.spawn(cmd, args, o); ch.stdout.pipe(process.stdout, {end: false}); ch.stderr.pipe(process.stderr); ch.stdout.on('data', function (data) { stdout[stdout.length] = data; }); ch.stdout.on('data', function (data) { stderr[stderr.length] = data; }); ch.on('exit', function(code) { stdout = stdout.join('\n'); stderr = stderr.join('\n'); if(cb) cb(code, stdout, stderr); }); return ch; }
JavaScript
0
@@ -268,16 +268,46 @@ path'),%0A + rimraf = require('rimraf'),%0A ncp = @@ -326,16 +326,16 @@ ').ncp;%0A - %0A// npm @@ -580,13 +580,11 @@ = ' -https +git ://g @@ -1030,16 +1030,55 @@ cmd);%0A%0A + console.log('Git clone / pull ok');%0A%0A // Do @@ -1308,16 +1308,16 @@ levels%0A%0A - // now @@ -1356,16 +1356,130 @@ he repo%0A + console.log('Copying over jqueryui base theme into css folder.');%0A rimraf.sync('test/fixtures/h5bp/css/base');%0A ncp('t
b34c1d2eb6cf83a06214c5c3f03b246c3dd41862
Update the fake for Graph resource
test/support/fake-io.js
test/support/fake-io.js
var nock = require('nock'); var fakeIo = exports; exports.createServer = function (options) { return new FakeIo(options); }; var FakeIo = exports.FakeIo = function (options) { this.defaults = options; }; // // Fake server for Key/Value resource // FakeIo.prototype.keyValue = function (options) { var server , uri = '/' + [ this.defaults.api, options.collection, options.key ].join('/'); switch (options.method) { case "GET": server = nock(this.defaults.endpoint) .get(uri) .replyWithFile(200, __dirname + '/fixtures/key-value-sample.json'); break; case "PUT": server = nock(this.defaults.endpoint) .put(uri, options.data).reply(201, {}); break; default: throw new Error('Inappropriate method'); } return server; }; // // Fake server for Search resource // FakeIo.prototype.search = function (options) { var server , uri = '/' + [ this.defaults.api, options.collection ].join('/'); server = nock(this.defaults.endpoint) .get(uri + '?query=' + encodeURIComponent(options.query)) .replyWithFile(200, __dirname + '/fixtures/search-sample.json'); return server; }; // // Fake server for Events resource // FakeIo.prototype.event = function (options) { var server , uri = '/' + [ this.defaults.api, options.collection, options.key, 'events', options.type ].join('/'); switch (options.method) { case "GET": server = nock(this.defaults.endpoint) .get(uri + '?start=' + options.start + '&end=' + options.end) .replyWithFile(200, __dirname + '/fixtures/events-sample.json'); break; case "PUT": server = nock(this.defaults.endpoint) .put(uri + '?timestamp=' + options.timestamp, options.data).reply(204, {}); break; default: throw new Error('Inappropriate method'); } return server; }; FakeIo.prototype.graph = function (options) { // write fake request & response console.log('call FakeIo.graph with ' + options); };
JavaScript
0
@@ -1912,91 +1912,763 @@ %7B%0A -// write fake request & response%0A console.log('call FakeIo.graph with ' + options) +var server%0A , uri;%0A%0A switch (options.method) %7B%0A case %22GET%22:%0A uri = '/' + %5B%0A this.defaults.api,%0A options.collection,%0A options.key,%0A options.relation %0A %5D.join('/');%0A%0A server = nock(this.defaults.endpoint)%0A .get(uri)%0A .replyWithFile(200, __dirname + '/fixtures/graph-sample.json');%0A break;%0A case %22PUT%22:%0A uri = '/' + %5B%0A this.defaults.api,%0A options.collection,%0A options.key,%0A 'relation',%0A options.relation,%0A options.toCollection,%0A options.toKey%0A %E3%80%80 %5D.join('/');%0A%0A server = nock(this.defaults.endpoint)%0A .put(uri).reply(204, %7B%7D);%0A break;%0A default:%0A throw new Error('Inappropriate method');%0A %7D%0A%0A return server ;%0A%7D;
9baee0180eec00f60a9e68c48a3c3caad34f1346
fix recursion checking
macro/index.js
macro/index.js
'use strict'; var fs = require('fs'), lfmt = require('lfmt'); var saveFile = process.cwd() + '/saved.macros'; var macros = {}; var errMsgs = { incorrectUsage: '`macro`: you did something wrong.', noMacro: 'Can\'t find that!', cantBeEmpty: 'Macro can\'t be empty!', cantBeRecursive: 'Macro can\'t be recursive!', badBrackets: 'Macro has mismatched brackets!' }; var loadMacros = function loadMacros() { if (Object.keys(macros).length > 0) return; try { // this scheme does not account for duplicate keys. later records with // the same key will simply overwrite the template. var rawMacros = fs.readFileSync(saveFile).toString() .split('\n') .forEach(function(record) { if (!record) return; // TODO: catch errors for records with no space var spaceIndex = record.indexOf(' '), name = record.slice(0, spaceIndex), template = record.slice(spaceIndex + 1); macros[name] = template; console.log(lfmt.format('loading macro {{name}} `{{template}}`', { name: name, template: template })); }); } catch (err) { // log the error and clean the macros. console.error(err); macros = {}; } }; var addMacro = function addMacro(name, template, cb) { macros[name] = template; fs.appendFile(saveFile, lfmt.format('{{name}} {{template}}\n', { name: name, template: template }), function(err) { if (err) console.error(err); cb && cb(); }); }; var applyMacro = function loadMacros(name, args, cb) { var template = macros[name]; if (!template) { cb && cb(new Error('Macro not found')); return; } var result = template .replace(/\$@/g, args.join(' ')) .replace(/\$(\d+)/g, function(match, p1) { return (args[Number(p1)] || ''); }); cb && resolveNesting(result, cb); }; var resolveNesting = function resolveNesting(template, cb) { var lastNested = template.lastIndexOf('$('); if (lastNested === -1) cb(null, template); else { var brackets = 1; var index = lastNested + 2; while (brackets > 0) { if (template[index+1] && template[index] === '$' && template[index+1] === '(') { brackets += 1; } else if (template[index] === ')') { brackets -= 1; } index += 1; } var nestedMacro = template.substring(lastNested+2, index-1), firstSpace = nestedMacro.indexOf(' '), name = firstSpace === -1 ? nestedMacro : nestedMacro.substring(0, firstSpace), args = firstSpace === -1 ? [] : nestedMacro.substring(firstSpace+1).split(' '); applyMacro(name, args, function(err, result) { resolveNesting(template.slice(0, lastNested) + result + template.slice(index), cb); }); } }; var isRecursive = function isRecursive(name, template) { var nestedMacros = template.match(/\$\(.*?(\)|\ )/g); if (!nestedMacros) return false; nestedMacros = nestedMacros.map(function (str) { return str.substring(2, str.length - 1); }); var recursive = false; nestedMacros.some(function (macro) { return macro === name || (macros[macro] && isRecursive(name, macros[macro])); }); return recursive; }; var badBrackets = function badBrackets(template) { var index = 0, brackets = 0; while (template[index]) { if (template[index+1] && template[index] === '$' && template[index+1] === '(') { brackets += 1; } else if (template[index] === ')') { brackets -= 1; } if (brackets < 0) return true; index += 1; } if (brackets != 0) return true; return false; }; var macro = function macro(argv, response, logger) { loadMacros(); if (argv.length < 2) { logger.error('`macro` called incorrectly: ', argv); response.end(errMsgs.incorrectUsage); return; } var subcmd = argv[1]; if (subcmd === 'set') { var name = argv[2]; var template = argv.slice(3).join(' ').split('\n')[0]; if (template.length <= 0) { response.end(errMsgs.cantBeEmpty); return; } else if (badBrackets(template)) { response.end(errMsgs.badBrackets); return; } else if (isRecursive(name, template)) { response.end(errMsgs.cantBeRecursive); return; } addMacro(name, template, function(err) { if (!err) { response.end(lfmt.format('Successfully macroed {{name}} to `{{template}}`', { name: name, template: template })); } }); } else { var name = subcmd; applyMacro(name, argv.slice(2), function(err, result) { var reply = result || errMsgs.noMacro; logger.log(lfmt.format('Sending reply: {{reply}}', { reply: reply })); response.end(reply); }); } }; macro.metadata = { name: 'macro', command: 'macro', info: { description: 'Set a string template macro', usage: 'macro [set {template}|{name} {variables...}]' } }; module.exports = macro;
JavaScript
0.000004
@@ -2963,46 +2963,120 @@ -return str.substring(2, str.length - 1 +var firstSpace = str.indexOf(' ');%0A return str.substring(2, firstSpace === -1 ? (str.length - 1) : firstSpace );%0A @@ -3084,35 +3084,17 @@ %7D);%0A +%0A -var re -cursive = false;%0A%0A +turn nes @@ -3219,28 +3219,8 @@ %7D);%0A - return recursive;%0A %7D;%0A%0A
d4e616c36fba0a5096a1b48f0fd46fcf63a721ad
Fix test
test/unit/TestSample.js
test/unit/TestSample.js
(function () { 'use strict'; describe('Sample', function () { beforeEach(module('sample-with-tests')); var factory; beforeEach(inject(function ($injector) { factory = $injector.get('Sample'); })); it('is defined', function () { expect(factory).toBeDefined(); }); describe('myMethod', function () { it('returns 1 when p is true', function () { expect(factory.myMethod(true)).toEqual(1); }); it('returns 3 when p is false', function () { // Intentionally broken test expect(factory.myMethod(false)).toEqual(2); }); }); }); })();
JavaScript
0.000004
@@ -680,9 +680,9 @@ ual( -2 +3 );%0A
d1c4a11160a7ca02fc0634478deb41ff43e7d396
fix module name
test/unit/index.spec.js
test/unit/index.spec.js
"use strict"; const request = require("supertest"); const ApiGateway = require("../../src"); const { ServiceBroker } = require("Moleculer"); describe("Test default settings", () => { let broker; let service; let server; beforeEach(() => { broker = new ServiceBroker(); broker.loadService("./test/services/math.service"); service = broker.createService(ApiGateway); server = service.server; }); it("GET /math/add", () => { return request(server) .get("/math/add") .query({a: 5, b: 4 }) .expect("Content-Type", "application/json") .expect(200) .then(res => { expect(res.body).toBe(9); }); }); it("GET /", () => { return request(server) .get("/") .expect(404, "Not found") .then(res => { expect(res.body).toEqual({}); }); }); it("GET /other/action", () => { return request(server) .get("/other/action") .expect("Content-Type", "application/json") .expect(501) .then(res => { expect(res.body).toEqual({ "code": 501, "message": "Action 'other.action' is not available!", "name": "ServiceNotFoundError" }); }); }); it("POST /math/add with query", () => { return request(server) .post("/math/add") .query({a: 5, b: 4 }) .expect("Content-Type", "application/json") .expect(200) .then(res => { expect(res.body).toBe(9); }); }); it("POST /math/add with body", () => { return request(server) .post("/math/add") .send({a: 10, b: 8 }) .expect("Content-Type", "application/json") .expect(200) .then(res => { expect(res.body).toBe(18); }); }); it("POST /math/add with query & body", () => { return request(server) .post("/math/add") .query({a: 5, b: 4 }) .send({a: 10, b: 8 }) .expect("Content-Type", "application/json") .expect(200) .then(res => { expect(res.body).toBe(18); }); }); });
JavaScript
0.000007
@@ -126,9 +126,9 @@ re(%22 -M +m olec
4c33153279cc090526c5a8bba16e5c87eebe7592
test travis
test/unit/index.test.js
test/unit/index.test.js
import { assert, expect } from 'chai'; const globalRef = typeof window !== 'undefined' ? window : global; const indexPath = '../../src/index'; const timeEventPath = '../../src/timeEvent'; describe("TimeEvent prototype", function() { var timeEvent = require(timeEventPath); var event = new timeEvent(); it("should have a getTime function", function() { expect(event.__proto__.getTime).to.not.be.undefined; }); it("should have a getTimeDiff function", function() { expect(event.__proto__.getTimeDiff).to.not.be.undefined; }); }); describe("include lib", function() { var lib = require(indexPath); it("is on global context", function() { expect(typeof globalRef._purrrf).to.equal('object'); }); it("is not overridden on global context", function() { // require it again var lib2 = require(indexPath); expect(lib._id).to.equal(globalRef._purrrf._id); expect(lib2._id).to.equal(lib._id); }); var firstEvent = 'event1'; var firstEventTime; describe("push new event", function() { firstEventTime = lib.push(firstEvent); it("should return a number greater than 0", function() { expect(typeof firstEventTime).to.equal('number'); expect(firstEventTime).to.be.above(0); }); }); describe("get event time", function() { var time = lib.getTime(firstEvent); it("should return a number greater than 0", function() { expect(time).to.be.above(0); }); it("should equal the time returned when we initially pushed it", function() { expect(time).to.equal(firstEventTime); }); }); var secondEvent = 'event2'; var secondEventTime; describe("push a second event", function() { secondEventTime = lib.push(secondEvent); it("should return a number greater than first event time", function() { expect(secondEventTime).to.be.above(firstEventTime); }); describe("get time diff between two events", function() { var diff = lib.getTimeDiff(secondEvent, firstEvent); var diffNegative = lib.getTimeDiff(firstEvent, secondEvent); it("should return a number greater than 0 when reference event is first event", function() { expect(diff).to.be.above(0); }); it("should equal the exact difference between the two event times", function() { expect(diff).to.equal(secondEventTime - firstEventTime); }); it("reversed diff should return a number below 0 (reference event is the second event)", function() { expect(diffNegative).to.be.below(0); }); it("reversed diff should equal the first diff * -1", function() { expect(diffNegative).to.equal(diff * -1); }); }) }); describe("change reference start time to now", function() { var newStartRef = lib.setStart(); it("should return a number greater than 0", function() { expect(newStartRef).to.be.above(0); }); var firstEventTimeToStartRef = lib.getTime(firstEvent); it("first event getTime should now return negative", function() { expect(firstEventTimeToStartRef).to.be.below(0); }); var firstEventTimeToStartRef = lib.getTime(firstEvent); it("first event getTime + new reference start time should equal old first event time", function() { expect(firstEventTimeToStartRef + newStartRef).to.equal(firstEventTime); }); describe("get current reference start time", function() { var currentOffset = lib.getStart(); it("should return the current offset which was just set", function() { expect(currentOffset).to.equal(newStartRef); }); }); }); describe("get event times using array of events", function() { var multipleEvents = [firstEvent, secondEvent]; var multipleEventTimes = lib.getTime(multipleEvents); it("should return an array", function() { expect(multipleEventTimes).to.be.an('array'); }); var multipleEventsWithUndefined = [firstEvent, secondEvent, "undefined"]; var multipleEventsWithUndefinedTimes = lib.getTime(multipleEventsWithUndefined); it("should return array which contains a false, when passed an array with an undefined event", function() { expect(multipleEventsWithUndefinedTimes).to.be.an('array'); expect(multipleEventsWithUndefinedTimes[2]).to.be.false; }); }); describe("get event time of an undefined event", function() { var undefinedEventTime = lib.getTime('undefined'); it("should return false", function() { expect(undefinedEventTime).to.be.false; }); }); describe("get time diff of an undefined event and no passed reference event", function() { var undefinedEventTimeDiff = lib.getTimeDiff('undefined'); it("should return false", function() { expect(undefinedEventTimeDiff).to.be.false; }); }); describe("get time diff of a defined event and a passed undefined reference event", function() { var definedEventUndefinedReferenceTime = lib.getTimeDiff(firstEvent, 'undefined'); var currentOffset = lib.getStart(); it("should return the definded event's time minus any offset if the start reference has been changed", function() { expect(definedEventUndefinedReferenceTime).to.equal(firstEventTime - currentOffset); }); }); describe("push new event with group name", function() { var eventWithGroupTime = lib.push("event", "group"); it("should return a number greater than 0", function() { expect(eventWithGroupTime).to.be.above(0); }); describe("push another event with same group name", function() { var anotherEvent = "anotherEvent"; var anotherEventWithGroupTimeDiff = lib.push(anotherEvent, "group"); it("should return the time difference between the two events of the same group name", function() { expect(anotherEventWithGroupTimeDiff).to.be.above(0); var anotherEventWithGroupTime = lib.getTime(anotherEvent); expect(anotherEventWithGroupTime).to.be.above(0); expect(anotherEventWithGroupTime - eventWithGroupTime).to.equal(anotherEventWithGroupTimeDiff); }); }); }); describe("get event map", function() { var map = lib.getMap(); it("should be an object", function() { expect(typeof map).to.equal('object'); }); it("should contain an event we created", function() { expect(map[firstEvent]).to.not.be.undefined; }); }); describe("get event map passing the ordered option", function() { var orderedEvents = lib.getMap({ ordered: true }); it("should return an array", function() { expect(orderedEvents).to.be.an('array'); }); }); });
JavaScript
0.000002
@@ -7464,20 +7464,21 @@ %7D);%0A %7D);%0A%7D); +%0A
3b074b852a1f8b860fce7ea14934a1b23e0dd2d7
Remove unnecesary dependencies
test/unit/queueState.js
test/unit/queueState.js
var should = require('should'); var async = require('async'); var config = require('./../config.js') var utils = require('./../utils.js'); var agent = require('../../.'); var queueID = 'q1'; var checkState = function(expectedState, cb) { utils.queueState('q1', function(err, response, data) { should.not.exist(err); response.statusCode.should.be.equal(200); data.should.have.property('blocked', expectedState); if (cb) { cb(); } }); } describe('Queue State', function() { before(function(done){ agent.start(done); }); after(function(done) { utils.cleanBBDD(function() { agent.stop(done); }); }); beforeEach(function(done) { utils.cleanBBDD(done); }); it ('Blocked is false when subscription or pop operations have not been called', function(done) { checkState(false, done); }); it('Blocked is true when pop operations is being processed and false when is completed (trans is pushed)', function(done) { this.timeout(5000); utils.pop(queueID, function(err, response, data) { should.not.exist(err); response.statusCode.should.be.equal(200); data.data.length.should.be.equal(1); data.transactions.length.should.be.equal(1); checkState(false, done); }); setTimeout(function() { checkState(true, function() { var trans = utils.createTransaction('MESSAGE', 'L', [ {id: queueID} ]); utils.pushTransaction(trans, function(err, response, data) { should.not.exist(err); response.statusCode.should.be.equal(200); }) }) }, 1000) }); it('Blocked is true when pop operations is being processed and false when is completed (timeout)', function(done) { this.timeout(5000); utils.popTimeout(queueID, 2, function(err, response, data) { should.not.exist(err); response.statusCode.should.be.equal(200); data.data.length.should.be.equal(0); data.transactions.length.should.be.equal(0); checkState(false, done); }); setTimeout(checkState.bind({}, true), 1000); }); it('Blocked on subscription and unblocked when subscription ends', function(done) { this.timeout(5000); utils.subscribe(1, queueID, function(err, messages) { should.not.exist(err); var msg = messages.pop(); msg.data.length.should.be.equal(1); msg.transactions.length.should.be.equal(1); checkState(false, done); }); setTimeout(function() { checkState(true, function() { var trans = utils.createTransaction('MESSAGE', 'L', [ {id: queueID} ]); utils.pushTransaction(trans, function(err, response, data) { should.not.exist(err); response.statusCode.should.be.equal(200); }) }) }, 1000) }); });
JavaScript
0.012464
@@ -29,77 +29,8 @@ ');%0A -var async = require('async');%0Avar config = require('./../config.js')%0A var @@ -2726,12 +2726,8 @@ );%0A%0A -%0A%0A%0A%0A%0A %7D); +%0A
726196392b3395f17c2ae8593336aa88eab29b30
Add additional test case for stripping existing hypens, too
tests/cases/url/Slug.js
tests/cases/url/Slug.js
QUnit.test( "Slug.transform() defaults", function (assert) { const Slug = mojave.url.Slug; // test defaults const instance = new Slug(); [ ["abc def", "abc-def"], ["ä-ö-ü-ß", "ae-oe-ue-ss"], ["ääää", "aeaeaeae"], [" ", ""], ["a?&b", "a-b"], ["abc(test)", "abc(test)"], ] .forEach( ([raw, expected]) => assert.equal(instance.transform(raw), expected) ); } ); QUnit.test( "Slug.transform() custom transforms", function (assert) { const Slug = mojave.url.Slug; // test defaults const instance = new Slug([ [/z/, "a"], ]); [ ["abc def", "abc-def"], ["abczdef", "abcadef"], ] .forEach( ([raw, expected]) => assert.equal(instance.transform(raw), expected) ); } ); QUnit.test( "Slug.transform() custom sanitizer", function (assert) { const Slug = mojave.url.Slug; // test defaults const instance = new Slug([], /z/); [ ["abc def", "abc def"], ["abczdef", "abc-def"], ] .forEach( ([raw, expected]) => assert.equal(instance.transform(raw), expected) ); } );
JavaScript
0
@@ -382,24 +382,84 @@ bc(test)%22%5D,%0A + %5B%22a&-&b%22, %22a-b%22%5D,%0A %5B%22a---b%22, %22a-b%22%5D,%0A %5D%0A
5f307c622f5970f5b028865eebb70b5d76985a41
update cache setting for test model
tests/js/suite/model.js
tests/js/suite/model.js
define(['wq/store', 'wq/model'], function(store, model) { QUnit.module('wq/model'); var ds = store.getStore('model-test'); ds.init({ 'service': '/tests', 'defaults': { 'format': 'json' } }); var items = model({'url': 'items', 'store': ds}); QUnit.test("load data list", function(assert) { var done = assert.async(); items.load().then(function(data) { assert.ok(data); assert.equal(data.list.length, 3, "list should have 3 items"); assert.equal(data.count, 3, "count should reflect list length"); assert.equal(data.pages, 1, "assume one page unless specified"); done(); }); }); QUnit.test("find item", function(assert) { var done = assert.async(); items.find("one").then(function(item) { assert.equal(item.id, "one", "item identifier"); assert.equal(item.label, "ONE", "item label"); assert.equal(item.contacts.length, 2, "nested array"); done(); }); }); QUnit.test("filter by single value", function(assert) { var done = assert.async(); items.filter({'type_id': 1}).then(function(items) { assert.equal(items.length, 2, "filter should return two results"); assert.equal(items[0].id, "one", "first result should be item 'one'"); assert.equal(items[1].id, "two", "second result should be item 'two'"); done(); }); }); QUnit.test("filter by multiple values", function(assert) { var done = assert.async(); items.filter({'color': ['#f00', '#00f']}).then(function(items) { assert.equal(items.length, 2, "filter should return two results"); assert.equal(items[0].id, "one", "first result should be item 'one'"); assert.equal( items[1].id, "three", "second result should be item 'three'" ); done(); }); }); });
JavaScript
0
@@ -225,16 +225,21 @@ model(%7B +%0A 'url': ' @@ -245,16 +245,20 @@ 'items', +%0A 'store' @@ -261,16 +261,38 @@ ore': ds +,%0A 'cache': 'all',%0A %7D);%0A%0AQUn
9c239c0133b3096879a8a2b2c6fa19972f0fdf4c
correct order for app.js
tests/nullEngine/app.js
tests/nullEngine/app.js
//var LOADERS = require("../../dist/preview release/loaders/babylonjs.loaders"); var BABYLON = require("../../dist/preview release/babylon.max"); global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; var engine = new BABYLON.NullEngine(); var scene = new BABYLON.Scene(engine); // //Create a light // var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(-60, 60, 80), scene); // //Create an Arc Rotate Camera - aimed negative z this time // var camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, 1.0, 110, BABYLON.Vector3.Zero(), scene); // //Creation of 6 spheres // var sphere1 = BABYLON.Mesh.CreateSphere("Sphere1", 10.0, 9.0, scene); // var sphere2 = BABYLON.Mesh.CreateSphere("Sphere2", 2.0, 9.0, scene);//Only two segments // var sphere3 = BABYLON.Mesh.CreateSphere("Sphere3", 10.0, 9.0, scene); // var sphere4 = BABYLON.Mesh.CreateSphere("Sphere4", 10.0, 9.0, scene); // var sphere5 = BABYLON.Mesh.CreateSphere("Sphere5", 10.0, 9.0, scene); // var sphere6 = BABYLON.Mesh.CreateSphere("Sphere6", 10.0, 9.0, scene); // //Position the spheres // sphere1.position.x = 40; // sphere2.position.x = 25; // sphere3.position.x = 10; // sphere4.position.x = -5; // sphere5.position.x = -20; // sphere6.position.x = -35; // //Creation of a plane // var plane = BABYLON.Mesh.CreatePlane("plane", 120, scene); // plane.position.y = -5; // plane.rotation.x = Math.PI / 2; // //Creation of a material with wireFrame // var materialSphere1 = new BABYLON.StandardMaterial("texture1", scene); // materialSphere1.wireframe = true; // //Creation of a red material with alpha // var materialSphere2 = new BABYLON.StandardMaterial("texture2", scene); // materialSphere2.diffuseColor = new BABYLON.Color3(1, 0, 0); //Red // materialSphere2.alpha = 0.3; // //Creation of a material with an image texture // var materialSphere3 = new BABYLON.StandardMaterial("texture3", scene); // materialSphere3.diffuseTexture = new BABYLON.Texture("textures/misc.jpg", scene); // //Creation of a material with translated texture // var materialSphere4 = new BABYLON.StandardMaterial("texture4", scene); // materialSphere4.diffuseTexture = new BABYLON.Texture("textures/misc.jpg", scene); // materialSphere4.diffuseTexture.vOffset = 0.1;//Vertical offset of 10% // materialSphere4.diffuseTexture.uOffset = 0.4;//Horizontal offset of 40% // //Creation of a material with an alpha texture // var materialSphere5 = new BABYLON.StandardMaterial("texture5", scene); // materialSphere5.diffuseTexture = new BABYLON.Texture("textures/tree.png", scene); // materialSphere5.diffuseTexture.hasAlpha = true;//Has an alpha // //Creation of a material and show all the faces // var materialSphere6 = new BABYLON.StandardMaterial("texture6", scene); // materialSphere6.diffuseTexture = new BABYLON.Texture("textures/tree.png", scene); // materialSphere6.diffuseTexture.hasAlpha = true;//Have an alpha // materialSphere6.backFaceCulling = false;//Show all the faces of the element // //Creation of a repeated textured material // var materialPlane = new BABYLON.StandardMaterial("texturePlane", scene); // materialPlane.diffuseTexture = new BABYLON.Texture("textures/grass.jpg", scene); // materialPlane.diffuseTexture.uScale = 5.0;//Repeat 5 times on the Vertical Axes // materialPlane.diffuseTexture.vScale = 5.0;//Repeat 5 times on the Horizontal Axes // materialPlane.backFaceCulling = false;//Always show the front and the back of an element // //Apply the materials to meshes // sphere1.material = materialSphere1; // sphere2.material = materialSphere2; // sphere3.material = materialSphere3; // sphere4.material = materialSphere4; // sphere5.material = materialSphere5; // sphere6.material = materialSphere6; // plane.material = materialPlane; //Adding a light var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(20, 20, 100), scene); //Adding an Arc Rotate Camera var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene); // The first parameter can be used to specify which mesh to import. Here we import all meshes BABYLON.SceneLoader.ImportMesh("", "https://playground.babylonjs.com/scenes/", "skull.babylon", scene, function (newMeshes) { // Set the target of the camera to the first imported mesh camera.target = newMeshes[0]; console.log("Meshes loaded from babylon file: " + newMeshes.length); for (var index = 0; index < newMeshes.length; index++) { console.log(newMeshes[index].toString()); } BABYLON.SceneLoader.ImportMesh("", "https://www.babylonjs.com/Assets/DamagedHelmet/glTF/", "DamagedHelmet.gltf", scene, function (meshes) { console.log("Meshes loaded from gltf file: " + meshes.length); for (var index = 0; index < meshes.length; index++) { console.log(meshes[index].toString()); } }); console.log("render started") engine.runRenderLoop(function() { scene.render(); }) });
JavaScript
0.000178
@@ -1,10 +1,74 @@ -// +var BABYLON = require(%22../../dist/preview release/babylon.max%22);%0D%0A var LOAD @@ -143,74 +143,8 @@ );%0D%0A -var BABYLON = require(%22../../dist/preview release/babylon.max%22);%0D%0A glob
c70759e5820df776ad8ff75acfad960f35b432bf
Update webpack rules for test app
tests/webpack.config.js
tests/webpack.config.js
var path = require("path"); var webpack = require("webpack"); var WebpackBuildNotifierPlugin = require("webpack-build-notifier"); var HtmlWebpackPlugin = require("html-webpack-plugin"); const PATHS = { src: path.join(__dirname, './src'), build: path.join(__dirname, './build') }; module.exports = { entry: { "app": PATHS.src + '/index.ts' }, output: { path: PATHS.build, filename: '[name].js', }, devtool: "source-map", module: { loaders: [ { test: /\.ts$/, loader: 'ts-loader' }, { test: /\.p?css$/, loaders: [ 'style-loader', 'css-loader?importLoaders=1,url=false', 'postcss-loader' ] } ] }, resolve: { // you can now require('file') instead of require('file.js') extensions: ['.ts', '.js'] }, plugins: [ new WebpackBuildNotifierPlugin({ title: "My Project Webpack Build" }), new HtmlWebpackPlugin({ title: 'Webpack boilerplate', hash: true, filename: 'index.html', template: 'index.html' }) ] };
JavaScript
0
@@ -455,30 +455,28 @@ dule: %7B%0A -loader +rule s: %5B%0A %7B @@ -511,27 +511,73 @@ -loader: 'ts-loader' +use: %5B%7B%0A loader: 'awesome-typescript-loader'%0A%0A %7D%5D %0A @@ -582,17 +582,16 @@ %7D,%0A -%0A %7B%0A @@ -628,15 +628,11 @@ -loaders +use : %5B%0A @@ -645,46 +645,141 @@ -'style-loader',%0A 'css-loader? +%7B%0A loader: 'style-loader'%0A %7D,%0A %7B%0A loader: 'css-loader',%0A options: %7B%0A impo @@ -791,22 +791,23 @@ ders -= +: 1, + url -= +: false -', %0A @@ -812,16 +812,65 @@ + %7D%0A %7D,%0A %7B%0A loader: 'postcs @@ -871,32 +871,44 @@ postcss-loader'%0A + %7D%0A %5D%0A @@ -914,17 +914,16 @@ %7D%0A %5D -%0A %7D,%0A r
ee152c020c2b3cfe4a2a0cc9cafa0386e4c36544
Use nicer syntax instead of Reflect
addon/index.js
addon/index.js
import MirageServer from '@miragejs/server/lib'; export * from '@miragejs/server/lib'; import Inflector from 'ember-inflector'; import { __inflections } from './utils/inflector'; function patchEmberInflector() { __inflections(newInflector => { // Proxy ember-inflector calls to `inflected` Inflector.inflector = new window.Proxy(Inflector.inflector, { get: function(_, prop) { if (!newInflector[prop]) { return window.Reflect.get(...arguments); } return (...args) => newInflector[prop](...args); } }); }); } patchEmberInflector(); export default MirageServer;
JavaScript
0
@@ -377,17 +377,22 @@ unction( -_ +target , prop) @@ -449,30 +449,33 @@ urn -window.Reflect.get(... +target%5Bprop%5D.apply(this, argu
15159dbaacfe41f2531dc3a1777d4de4327d44f7
Add TruncateHelper to index.js
addon/index.js
addon/index.js
export { default as AppendHelper } from './helpers/append'; export { default as CamelizeHelper } from './helpers/camelize'; export { default as CapitalizeHelper } from './helpers/capitalize'; export { default as ChunkHelper } from './helpers/chunk'; export { default as ClassifyHelper } from './helpers/classify'; export { default as CompactHelper } from './helpers/compact'; export { default as ComputeHelper } from './helpers/compute'; export { default as ContainsHelper } from './helpers/contains'; export { default as DasherizeHelper } from './helpers/dasherize'; export { default as DecHelper } from './helpers/dec'; export { default as DropHelper } from './helpers/drop'; export { default as FilterByHelper } from './helpers/filter-by'; export { default as FindByHelper } from './helpers/find-by'; export { default as GroupByHelper } from './helpers/group-by'; export { default as IncHelper } from './helpers/inc'; export { default as IntersectHelper } from './helpers/intersect'; export { default as InvokeHelper } from './helpers/invoke'; export { default as JoinHelper } from './helpers/join'; export { default as MapByHelper } from './helpers/map-by'; export { default as PipeHelper } from './helpers/pipe'; export { default as PipeActionHelper } from './helpers/pipe-action'; export { default as RangeHelper } from './helpers/range'; export { default as RejectByHelper } from './helpers/reject-by'; export { default as RepeatHelper } from './helpers/repeat'; export { default as SortByHelper } from './helpers/sort-by'; export { default as TakeHelper } from './helpers/take'; export { default as ToggleHelper } from './helpers/toggle'; export { default as ToggleActionHelper } from './helpers/toggle-action'; export { default as UnderscoreHelper } from './helpers/underscore'; export { default as UnionHelper } from './helpers/union'; export { default as WHelper } from './helpers/w'; export { default as WithoutHelper } from './helpers/without';
JavaScript
0
@@ -1705,32 +1705,96 @@ toggle-action';%0A +export %7B default as TruncateHelper %7D from './helpers/truncate';%0A export %7B default
1ee72824e119c3d6ca6be4214d71617fe9992edb
Update embedded script for the new API.
scripts/embed.js
scripts/embed.js
"use strict"; Relive.useSingleton = false; window.addEventListener("load", function () { var error, events, bits, station, list, lists = document.querySelector("#lists"); Object.toArray = function (obj) { return Object.keys(obj) .reduce(function (list, key) { list.push(obj[key]); return list; }, []); }; function perror (response, status) { // This reveals more to code-based API callers than the UI would. Consider changing? error = { type: "initialization", value: status + ": " + response }; App.error.apply(this, arguments); } function initialized () { window.parent.postMessage(Messages.INITIALIZED, "*"); } function pause () { Replayer.pause(); document.body.style.overflow = ""; } // Detect a URL with #station-0 or #stream-0-0 if (/^#(?:station-[\da-zA-z]+|stream-[\da-zA-z]+-[\da-zA-z]+)$/.test(location.hash)) { bits = location.hash.split("-"); station = Relive.fromBase62(bits[1]); // Get the loading indicator sooner. if (bits[0] === "#station") { list = document.createElement("ol"); list.setAttribute("reversed", "reversed"); document.getElementById("lists").appendChild(list); } else { Replayer.autoplay = false; document.getElementById("back").style.display = "none"; lists.style.transition = "none"; lists.style.marginLeft = "-100%"; } Relive.loadStations(function (stations) { station = stations[station]; if (station && bits[0] === "#station") { Relive.loadStationInfo(station.id, function (info) { var streams; streams = Object.toArray(info.streams) .sort(function (a, b) { return b.timestamp - a.timestamp; }); streams.forEach(function (stream) { list.appendChild(App.entry(station, stream, function () { Replayer.loadStream(station, stream, 0); })); }); list.className = "loaded"; document.querySelector("#lists h1").textContent = info.name; document.getElementById("back").addEventListener("click", function (event) { pause(); App.menu(false); lists.style.marginLeft = ""; }); initialized(); }, perror); } else if (station) { Relive.loadStationInfo(station.id, function (info) { var stream = info.streams[Relive.fromBase62(bits[2])]; if (stream) { Replayer.loadStream(station, stream, 0, initialized); } else { error = { type: "initialization", value: "Invalid stream ID." }; App.error(error.value); } }, perror); } else { error = { type: "initialization", value: "Invalid station ID." }; App.error(error.value); } }); } else { App.error("No station or stream specified."); } // To be written as if we're initialized. It's not their job to check. events = {}; events[Messages.PLAY] = function () { // This and pause may not succeed (no player yet). If so, the outside has no idea. Replayer.play(); }; events[Messages.PAUSE] = function () { Replayer.pause(); }; events[Messages.PAUSED] = function () { window.parent.postMessage(Messages.create(Messages.PAUSED, Replayer.paused), "*"); }; window.addEventListener("message", function (event) { var data = Messages.parse(event.data), handler = events[data.message]; if (handler && error) { window.parent.postMessage(Messages.create(data.message, error, true), "*"); } else if (handler && !error) { handler(); } }); });
JavaScript
0
@@ -1835,35 +1835,32 @@ tionInfo(station -.id , function (info @@ -1853,32 +1853,32 @@ function (info)%0A + @@ -1947,61 +1947,20 @@ s = -Object.toArray(info.streams)%0A +info.streams .sor @@ -1993,34 +1993,26 @@ - %7B%0A +%7B%0A @@ -2057,20 +2057,16 @@ estamp;%0A - @@ -2509,17 +2509,24 @@ = info. -n +stationN ame;%0A%0A @@ -2905,32 +2905,32 @@ )%0A %7B%0A + @@ -2963,11 +2963,8 @@ tion -.id , fu
bc2e9fbaf43cc2bfee43bd03fe5181c093f4a3e6
Remove extra `exports`
config/index.js
config/index.js
'use strict'; var path = require('path'); var webpack = require('webpack'); var merge = require('./merge'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var pkg = require('../package.json'); var TARGET = process.env.TARGET; var ROOT_PATH = path.resolve(__dirname, '..'); var DEMO_DIR = 'demo'; var config = { paths: { dist: path.join(ROOT_PATH, 'dist'), lib: path.join(ROOT_PATH, 'lib'), demo: path.join(ROOT_PATH, DEMO_DIR), demoIndex: path.join(ROOT_PATH, DEMO_DIR, '/index'), }, filename: 'boilerplate', library: 'Boilerplate', demoDirectory: DEMO_DIR, }; var mergeDemo = merge.bind(null, { exports: { entry: [ config.paths.demoIndex, ], resolve: { extensions: ['', '.js', '.jsx', '.md', '.css', '.png', '.jpg'], }, }, module: { loaders: [ { test: /\.css$/, loaders: ['style', 'css'], }, { test: /\.md$/, loader: 'html!highlight!markdown', }, { test: /\.png$/, loader: 'url?limit=100000&mimetype=image/png', include: config.paths.demo, }, { test: /\.jpg$/, loader: 'file', include: config.paths.demo, }, { test: /\.json$/, loader: 'json', }, ] } }); if (TARGET === 'dev') { module.exports = mergeDemo({ port: 3000, devtool: 'eval', entry: [ 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', config.paths.demoIndex, ], output: { path: __dirname, filename: 'bundle.js', publicPath: '/' + config.demoDirectory + '/' }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('development'), } }), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), ], module: { preLoaders: [ { test: /\.jsx?$/, loaders: ['eslint', 'jscs'], include: [config.paths.demo, config.paths.lib], } ], loaders: [ { test: /\.jsx?$/, loaders: ['react-hot', 'babel'], include: [config.paths.demo, config.paths.lib], }, ] } }); } if (TARGET === 'gh-pages') { module.exports = mergeDemo({ entry: [ config.paths.demoIndex, ], output: { path: './gh-pages', filename: 'bundle.js', }, plugins: [ new webpack.DefinePlugin({ 'process.env': { // This has effect on the react lib size 'NODE_ENV': JSON.stringify('production'), } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, }), new HtmlWebpackPlugin({ title: pkg.name + ' - ' + pkg.description }), ], module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: [config.paths.demo, config.paths.lib], } ] } }); } var mergeDist = merge.bind(null, { devtool: 'source-map', output: { path: config.paths.dist, libraryTarget: 'umd', library: config.library, }, entry: config.paths.lib, externals: { react: 'react', 'react/addons': 'react/addons' }, module: { loaders: [ { test: /\.jsx?$/, loaders: ['babel'], include: config.paths.lib, } ] } }); if (TARGET === 'dist') { module.exports = mergeDist({ output: { filename: config.filename + '.js', }, }); } if (TARGET === 'dist-min') { module.exports = mergeDist({ output: { filename: config.filename + '.min.js', }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, }), ], }); }
JavaScript
0
@@ -658,27 +658,8 @@ , %7B%0A - exports: %7B%0A @@ -659,36 +659,32 @@ %7B%0A entry: %5B%0A - config.p @@ -699,35 +699,27 @@ oIndex,%0A - %5D,%0A +%5D,%0A resolve: @@ -717,28 +717,24 @@ resolve: %7B%0A - exte @@ -793,27 +793,16 @@ .jpg'%5D,%0A - %7D,%0A %7D,%0A
a67c2e15f4d8fff63071e3bd69d23a70f7e38162
fix projectName type
config/index.js
config/index.js
'use strict'; const basicConfig = { 'localDir': { env: 'LOCAL_DIRECTORY', type: 'string', default: 'dist' }, 'projectName': { env: 'PROJECT_NAME', type: 'boolean', default: false }, 'projectHasCustomName': { env: 'PROJECT_HAS_CUSTOM_NAME', type: 'boolean', default: false }, 'validationWaitTime': { env: 'VALIDATION_WAIT_TIME', type: 'number', default: 1000 } }; const s3Config = { 's3.uploadParameters.Bucket': { env: 'S3_BUCKET', type: 'string', defaults: { staging: 'ems-assets-staging', production: 'ems-assets' } }, 's3.uploadParameters.ACL': { env: 'S3_ACL', type: 'string', default: 'public-read' }, 's3.uploadParameters.CacheControl': { env: 'S3_CACHE_CONTROL', type: 'string', default: 'max-age=315360000, no-transform, public' }, 's3.credentials.region': { env: 'AWS_REGION', type: 'string', default: 'eu-west-1' }, 's3.credentials.accessKeyId': { env: 'AWS_ACCESS_KEY_ID', type: 'string', optional: true }, 's3.credentials.secretAccessKey': { env: 'AWS_SECRET_ACCESS_KEY', type: 'string', optional: true } }; const redirectorConfig = { 'redirector.deploy': { env: 'REDIRECTOR_DEPLOY', type: 'boolean', default: true }, 'redirector.url': { env: 'REDIRECTOR_URL', type: 'string', defaults: { staging: 'https://redirector-staging.gservice.emarsys.com', production: 'https://redirector.gservice.emarsys.net' } }, 'redirector.target': { env: 'REDIRECTOR_TARGET', type: 'string', defaults: { staging: 'assets.emarsys.com', production: 'assets.emarsys.net' } }, 'redirector.name': { env: ['REDIRECTOR_NAME', 'PROJECT_NAME'], type: 'string', optional: true }, 'redirector.apiSecret': { env: 'REDIRECTOR_API_SECRET', type: 'string', optional: true } }; const firebaseConfig = { 'firebase.deploy': { env: 'FIREBASE_DEPLOY', type: 'boolean', default: false }, 'firebase.project': { env: 'FIREBASE_PROJECT', type: 'string', optional: true }, 'firebase.site': { env: 'FIREBASE_SITE', type: 'string', optional: true }, 'firebase.credentials': { env: 'GOOGLE_APPLICAITON_CREDENTIALS_JSON', type: 'string', optional: true } }; module.exports = { ...basicConfig, ...s3Config, ...redirectorConfig, ...firebaseConfig };
JavaScript
0
@@ -178,35 +178,34 @@ e: ' -boolean',%0A default: fals +string',%0A optional: tru e%0A
eeb05235ea3d9f06cddc520354bc12894bdc17fa
Fix injected code snippet
scripts/popup.js
scripts/popup.js
/* global chrome parseDuration */ "use strict"; function lastErrorPromise(cb) { return new Promise((resolve, reject) => { return cb(value => chrome.runtime.lastError ? reject(chrome.runtime.lastError) : resolve(value)); }); } function getActiveTab() { return new lastErrorPromise(resolve => chrome.tabs.query({active: true, currentWindow: true}, resolve) ).then(tabs => tabs[0]); } function messageResponsePromise(message) { return new lastErrorPromise(resolve => chrome.runtime.sendMessage(message, resolve)); } const pActiveTab = getActiveTab(); let passwords = []; let activePassword = null; let countdownInterval = null; const activeStateControls = document.getElementById('active'); const inactiveStateControls = document.getElementById('inactive'); const countdownElement = document.getElementById('countdown'); function passwordExpiryHack() { // This is sort of a hack to shortcut waiting for the status update // to come back from the background page (which doesn't happen yet) // One way this won't work well is if there's another password that // would be fallen back to after this one expires, but that's kind of // an edge case for the time being activePassword = null; updateActivePasswordState(); } function updateCountdown() { const timeleft = activePassword.expiry - Date.now(); if (timeleft <= 0) { passwordExpiryHack(); } else { const minutes = Math.floor(timeleft / 60000); let seconds = Math.floor(timeleft / 1000 % 60); if (seconds < 10) seconds = '0' + seconds; countdownElement.textContent = `${minutes}:${seconds}`; } } function updateActivePasswordState() { inactiveStateControls.hidden = !(activeStateControls.hidden = !activePassword); if (activePassword) { if (!countdownInterval) { updateCountdown(); countdownInterval = setInterval(updateCountdown, 1000); } } else { clearInterval(countdownInterval); countdownInterval = null; } } function updatePasswords() { if (passwords.length > 0) { // TODO: Default to matching name or something activePassword = passwords[0]; } else { activePassword = null; } updateActivePasswordState(); } // TODO: subscribe to live out-of-band updates on this function receiveStatusUpdate(status) { passwords = status.passwords; updatePasswords(); } // Set the initial password state messageResponsePromise({method: 'getPasswordStatus'}) .then(receiveStatusUpdate); chrome.runtime.onMessage.addListener((message, sender, respond) => { switch (message.method) { // NOTE: this will probably not ever be implemented - // status subscriptions will probably use runtime.connect case 'statusUpdate': return receiveStatusUpdate(message.status); } }); function getDomainOfUrl(url) { const a = document.createElement('a'); a.href = url; return a.hostname; } function requestPasswordGeneration() { return pActiveTab.then(activeTab => messageResponsePromise({method: 'generatePassword', name: activeTab.url && getDomainOfUrl(activeTab.url) || 'nowhere'})) .then(receiveStatusUpdate); } document.getElementById('generate') .addEventListener('click', requestPasswordGeneration); function fillPassword() { chrome.tabs.executeScript({code: ` for (let input of document.querySelectorAll('input[type=password]') { input.value = ${JSON.stringify(activePassword.password)}; }`}); } document.getElementById('fill') .addEventListener('click', fillPassword); function forgetPassword() { chrome.runtime.sendMessage({ method: 'forgetPassword', name: activePassword.name}); passwordExpiryHack(); } document.getElementById('forget') .addEventListener('click', forgetPassword); const ttlInput = document.getElementById('ttl'); function updateTTL() { const ttl = parseDuration(ttlInput.value); if (ttl) { const expiry = Date.now() + ttl; // Minor hack: this should be changed by a status update from the // background page, not the caller activePassword.expiry = expiry; chrome.runtime.sendMessage({ method: 'setPasswordExpiry', name: activePassword.name, expiry}); } else { // If they want it to expire now, they should click "Forget password" // TODO: Some kind of error // TODO: teach parseDuration to differentiate between 0 and unparsable // (or just switch to https://github.com/zeit/ms) } } document.getElementById('expiryform') .addEventListener('submit', updateTTL);
JavaScript
0.00001
@@ -3369,16 +3369,17 @@ sword%5D') +) %7B%0A
496c2eccbafc4185eef390f94a70648fe6ddedda
Fix tag lookup autocomplete
sitemedia/js/annotator/tag-lookup.js
sitemedia/js/annotator/tag-lookup.js
/* Integration for binding jQuery autocomplete to tags field from marginalia - For now, leaving it independent of the tags logic in Marginalia since use case may change. - Parses a string of comma separated tags and handles the lookup to an autocomplete - bindTagAutocomplete function takes two arguments: 1. autocomplete_url - an autocomplete lookup 2. id_string - a jQuery compatibile selector - TODO: Figure out how to refactor as marginalia develop continues */ var bindTagAutocomplete = function(autocomplete_url, id_string) { // Function to parse a list of tags and only autocomplete on what's after the // comma. var parseRecentTag = function(str) { var list = str.split(','); var latest = list[list.length - 1] return latest.trim() } // Function that handles passing the query var tagAutocompleteSearch = function(request, response) { term = parseRecentTag(request.term); $.get(autocomplete_url, {q: term}, function(data) { // convert response into format jquery-ui expects response($.map(data.results, function (value, key) { return { label: value.text, value: value.text, id: value.id }; })); }); } // Bind an autocomplete to tags field $(id_string).autocomplete({ source: tagAutocompleteSearch, minLength: 0, focus: function(event, ui) { event.preventDefault(); }, select: function(event, ui) { var val = $('#annotator-field-1').val() if (val.indexOf(',') == -1) { val = ui.item.value + ', '; } else { val = val.replace(/,[^,]+$/, "") + ", " + ui.item.value + ', '; } $(this).val(val); // Stop the default event from firing because we're // handling the setting event.preventDefault(); }, open: function(event, ui) { // annotator purposely sets the editor at a very high z-index; // set autocomplete still higher so it isn't obscured by annotator buttons $('.ui-autocomplete').css('z-index', $('.annotator-editor').css('z-index') + 1); }, }); $(id_string).bind('focus', function () { $(this).autocomplete("search"); }
JavaScript
0.000001
@@ -2385,10 +2385,26 @@ arch%22);%0A -%7D + %7D);%0A%7D %0A
0d6903ec5547c5f519d402ec2a098229632bff11
测试:属性 class 中的 {{#unless}}
demo/attribute.js
demo/attribute.js
(function attribute() { return var tpl = Mock.heredoc(function() { /* <span title="{{title}}"> 属性 <code>title</code> 在变 </span> */ }) var data = Mock.tpl(tpl, { title: '@TITLE' }) doit(data, tpl) tasks.push( function() { data.title = Random.title(3) } ) })(); (function attribute() { return var tpl = Mock.heredoc(function() { /* <span class="before {{title}} after"> 属性 <code>class</code> 的一部分在变 </span>' */ }) var data = Mock.tpl(tpl, { title: '@TITLE' }) doit(data, tpl) tasks.push( function() { data.title = Random.title(3) } ) })(); (function attribute() { return var tpl = Mock.heredoc(function() { /* <span style="width: {{width}}px; height: auto"> 属性 <code>style</code> 的一部分在变 </span> */ }) var data = Mock.tpl(tpl, { width: '@INTEGER(200,500)' }) doit(data, tpl) tasks.push( function() { data.width = Random.integer(60, 100) + '%' } ) })(); (function attribute() { // return var tpl = Mock.heredoc(function() { /* <a href="/mock/{{guid}}"> 属性 href 再变 </a> */ }) var data = Mock.tpl(tpl, { guid: '@GUID' }) doit(data, tpl) tasks.push( function() { data.guid = Random.guid() } ) })();
JavaScript
0
@@ -8,32 +8,38 @@ on attribute +_title () %7B%0A return%0A @@ -18,32 +18,35 @@ te_title() %7B%0A + // return%0A var @@ -368,32 +368,38 @@ on attribute +_class () %7B%0A return%0A @@ -378,32 +378,35 @@ te_class() %7B%0A + // return%0A var @@ -750,24 +750,30 @@ ttribute +_style () %7B%0A return%0A @@ -764,16 +764,19 @@ () %7B%0A + // return%0A @@ -1162,24 +1162,29 @@ ttribute +_part () %7B%0A // retu @@ -1167,35 +1167,32 @@ ute_part() %7B%0A - // return%0A var @@ -1409,32 +1409,32 @@ function() %7B%0A - data @@ -1456,28 +1456,444 @@ guid()%0A %7D%0A )%0A%7D)(); +%0A%0A(function attribute_block() %7B%0A // return%0A var tpl = Mock.heredoc(function() %7B%0A /*%0A%3Cdiv class=%22%7B%7B#unless length%7D%7Dhide%7B%7B/unless%7D%7D%22%3E%0A %E6%88%91%E4%B8%80%E8%B7%AF%E7%A7%8D%E4%B8%8B%E4%BA%86%E8%98%91%E8%8F%87%E3%80%81%E5%8F%AA%E4%B8%BA%E8%AE%A9%E4%BD%A0%E7%9F%A5%E9%81%93%E5%9B%9E%E5%AE%B6%E7%9A%84%E8%B7%AF%E3%80%82 --- %E8%BF%85%E6%8D%B7%E6%96%A5%E5%80%99%0A%3C/div%3E%0A%3Cspan%3E%7B%7Blength%7D%7D%3C/span%3E%0A */%0A %7D)%0A var data = Mock.tpl(tpl, %7B%0A length: '@BOOLEAN'%0A %7D)%0A doit(data, tpl)%0A%0A tasks.push(%0A function() %7B%0A data.length = Random.boolean()%0A %7D%0A )%0A%7D)();
d012ab4dd268c880ac29231a920e1699fe2dbfcb
Set background color to black for very light transparent tilesets
views/MapClient.bones
views/MapClient.bones
// MapPreview // ---------- // A web map client for displaying tile-based maps. view = Backbone.View.extend({ className: 'MapClient', id: 'map', initialize: function(options) { _.bindAll(this, 'ready', 'record', 'mm', 'mmNav'); }, ready: function() { var wax = this.generateWax(); if (!wax.layers || wax.layers.length === 0) return; $.ajax({ dataType: 'jsonp', url: this.waxURL(wax), context: this, callback: 'grid', callbackParameter: 'callback', success: this.record, error: function() {} }); }, waxURL: function(wax) { return this.model.options.uiHost + 'api/wax.json?' + $.param(wax); }, generateWax: function(callback) { var wax = this.model.wax(); wax.el = $(this.el).attr('id'); wax.size && (delete wax.size); return wax; }, record: function(data) { if (data && data.wax) { var api = this.generateWax().api; this.map = wax.Record(data.wax); _(this[api]).isFunction() && this[api](); } }, mm: function() { this.map.addCallback('zoomed', this.mmNav); this.mmNav(); }, mmNav: function() { if (!$('.zoom').size()) return; $('.zoom.active').removeClass('active'); $('.zoom-' + this.map.getZoom()).addClass('active'); } });
JavaScript
0
@@ -1150,298 +1150,2051 @@ %7D%0A - %7D,%0A mm: function() %7B%0A this.map.addCallback('zoomed', this.mmNav);%0A this.mmNav();%0A %7D,%0A mmNav: function() %7B%0A if (!$('.zoom').size()) return;%0A $('.zoom.active').removeClass('active');%0A $('.zoom-' + this.map.getZoom()).addClass('active');%0A %7D%0A%7D);%0A +%0A // Calculate the background luminosity from the first tile.%0A setTimeout(function() %7B%0A var tile = this.$('img:first')%5B0%5D;%0A if (!tile) return;%0A if (tile.complete) setBackground();%0A else $(tile).load(setBackground);%0A%0A function setBackground() %7B%0A if (view.alphaImageLuminosity(tile) %3E 0.9) %7B%0A $(tile).closest('.MapClient').css(%7B backgroundColor: 'black' %7D);%0A %7D%0A %7D%0A %7D.bind(this), 0);%0A %7D,%0A mm: function() %7B%0A this.map.addCallback('zoomed', this.mmNav);%0A this.mmNav();%0A %7D,%0A mmNav: function() %7B%0A if (!$('.zoom').size()) return;%0A $('.zoom.active').removeClass('active');%0A $('.zoom-' + this.map.getZoom()).addClass('active');%0A %7D%0A%7D);%0A%0A// Calculates the luminosity (0-1) of all semi-transparent pixels.%0Aview.alphaImageLuminosity = function(el) %7B%0A if (!HTMLCanvasElement %7C%7C !el.complete) return -1;%0A%0A var canvas = document.createElement('canvas');%0A canvas.setAttribute('width', el.width);%0A canvas.setAttribute('height', el.height);%0A var c = canvas.getContext('2d');%0A c.drawImage(el, 0, 0);%0A%0A var r = 0, g = 0, b = 0, total = 0;%0A var pixels = c.getImageData(0, 0, el.width, el.height).data;%0A%0A // Look at every pixel's alpha value and only proceed if it is semi-transparent.%0A for (var i = 3; i %3C pixels.length; i += 4) %7B%0A if (pixels%5Bi%5D %3C 255 && pixels%5Bi%5D %3E 0) %7B%0A total++;%0A r += pixels%5Bi - 3%5D;%0A g += pixels%5Bi - 2%5D;%0A b += pixels%5Bi - 1%5D;%0A %7D%0A %7D%0A%0A if (!total) return 0;%0A%0A // Calculate average luminosity of all alpha pixels.%0A // Using the median of all per-pixel luminosities would be better but is%0A // computationally much more expensive and since this runs in the UI thread,%0A // is not an option at this point.%0A return Math.pow(r / total / 255, 2.2) * 0.2126 +%0A Math.pow(g / total / 255, 2.2) * 0.7152 +%0A Math.pow(b / total / 255, 2.2) * 0.0722;%0A%7D; %0A
7deab977a2fc0dc2ba6a83d138b8ab2b1f150830
Set up the canvas for the game
connect-four.js
connect-four.js
(function(){ // see http://benalman.com/news/2010/11/immediately-invoked-function-expression/ })();
JavaScript
0
@@ -8,11 +8,15 @@ on() + %7B%0A -%09 + // s @@ -96,16 +96,347 @@ on/%0A -%09%09%0A%09%0A%09 + var Game = function(canvasId) %7B%0A var canvas = document.getElementById(canvasId);%0A var screen = canvas.getContext('2d');%0A var gameSize = %7B%0A x: canvas.width,%0A y: canvas.height%0A %7D;%0A %7D;%0A%0A window.onload = function() %7B%0A new Game(%22screen%22);%0A %7D;%0A %0A%7D)(); +%0A
f2fe604461c5573862551297f83de1058c2f1fda
Fix some jslint issues in app/index.js
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var process = require('child_process'); var NordBackboneGenerator = yeoman.generators.Base.extend({ init: function () { this.pkg = require('../package.json'); this.on('end', function () { if (!this.options['skip-install']) { this.installDependencies(); } }); }, askFor: function () { var done = this.async(); // have Yeoman greet the user this.log(this.yeoman); // replace it with a short and sweet description of your generator this.log(chalk.magenta('You\'re using the fantastic nord-backbone generator.')); var prompts = [ { name: 'appName', message: 'What would you like to call your application?' }, { name: 'appDir', message: 'Where would you like to create your application?' }, { name: 'webRoot', message: 'Where is your web root located?' } ]; this.prompt(prompts, function (props) { this.appName = this._.camelize(props.appName); this.appDir = props.appDir; this.appPath = path.resolve(path.join(this.appDir, this.appName)); this.webRoot = props.webRoot; done(); }.bind(this)); }, app: function () { var dirsToCreate, i, filesToCopy, prop, templatesToWrite; dirsToCreate = [ this.appPath, path.join(this.appPath, 'components'), path.join(this.appPath, 'views'), path.join(this.appPath, 'core') ]; for (i = 0; i < dirsToCreate.length; i++) { this.mkdir(dirsToCreate[i]); } filesToCopy = { '_config.js': path.join(this.appDir, 'config.js'), '_index.js': path.join(this.appDir, 'index.js'), '_package.json': 'package.json', '_bower.json': 'bower.json', '_Gruntfile.js': 'Gruntfile.js' } for (prop in filesToCopy) { this.copy(prop, filesToCopy[prop]); } templatesToWrite = { 'core/entity.js': path.join(this.appPath, 'core', 'entity.js'), 'utils/dependencyLoader.js': path.join(this.appPath, 'utils', 'dependencyLoader.js'), 'core/component.js': path.join(this.appPath, 'core', 'component.js'), 'components/viewManager.js': path.join(this.appPath, 'components', 'viewManager.js'), 'core/app.js': path.join(this.appPath, 'core', 'app.js'), } for (prop in templatesToWrite) { this.template(prop, templatesToWrite[prop], { appName: this.appName }); } this.config.set('appName', this.appName); this.config.set('appPath', this.appPath); this.config.save(); }, projectfiles: function () { this.copy('.editorconfig', '.editorconfig'); } }); module.exports = NordBackboneGenerator;
JavaScript
0.000001
@@ -12,36 +12,8 @@ ';%0A%0A -var util = require('util');%0A var @@ -34,21 +34,21 @@ ('path') -;%0Avar +,%0A yeoman @@ -80,51 +80,19 @@ or') -;%0Avar chalk = require('chalk');%0Avar process +,%0A chalk = r @@ -105,19 +105,11 @@ ('ch -ild_process +alk ');%0A @@ -961,22 +961,16 @@ ocated?' - %0A %7D @@ -1886,27 +1886,26 @@ le.js'%0A %7D +; %0A - %0A for @@ -1925,26 +1925,24 @@ esToCopy) %7B%0A - this.c @@ -1967,24 +1967,24 @@ opy%5Bprop%5D);%0A + %7D%0A @@ -2404,24 +2404,25 @@ .js'),%0A %7D +; %0A %0A fo @@ -2448,26 +2448,24 @@ sToWrite) %7B%0A - this.t
080b7a48e03c44b05922419926454cef555633ab
Update index.
app/index.js
app/index.js
var React = require('react'); var Input = require('./component/input'); var MyComponent = React.createClass({ handleClick: function() { // Explicitly focus the text input using the raw DOM API. this.refs.myTextInput.getDOMNode().focus(); }, render: function() { // The ref attribute adds a reference to the component to // this.refs when the component is mounted. return ( <div> <Input value={this.props.name} /> <input type="text" ref="myTextInput" value={this.props.name} /> <button value={this.props.name} onClick={this.handleClick} /> </div> ); } }); React.render( <MyComponent name="pierre"/>, document.getElementById('example') );
JavaScript
0
@@ -61,24 +61,137 @@ nt/input');%0A +var pierre = %7Bpierre: %22Pierre Besson%22, metadata: %7Bpierre: %22DO_PRENOM%22%7D%7D;%0Avar Form = require('./component/form');%0A var MyCompon @@ -216,16 +216,16 @@ Class(%7B%0A - handle @@ -513,24 +513,66 @@ %3Cdiv%3E%0A + %3CForm data=%7Bthis.props.data%7D /%3E%0A %3CInput @@ -595,24 +595,26 @@ ps.name%7D /%3E%0A + %3Cinput @@ -667,24 +667,26 @@ ps.name%7D /%3E%0A + %3Cbutto @@ -769,17 +769,16 @@ %7D%0A%7D);%0A -%0A React.re @@ -783,16 +783,16 @@ render(%0A - %3CMyCom @@ -811,16 +811,30 @@ %22pierre%22 + data=%7Bpierre%7D /%3E,%0A do
8d499fd024bdbed63fa810cc1f84ef07e69c311f
Update CIF_Setup2.2.js
Javascript/additional/CIF_Setup2.2.js
Javascript/additional/CIF_Setup2.2.js
/* This file gives functions to the CIF setup page. */ var lineupForm = "https://cdn.rawgit.com/ginshmastc/Volleyball-Bookkeeper/master/HTML/Lineups6p1l.html"; function onStart() { Android.test("onstart"); } function lineups() { var saved = '{'; saved += '"teamA":"' + document.getElementById('teamA').value + '"'; saved += ', "teamB":"' + document.getElementById('teamB').value + '"'; saved += ', "sets":' + document.getElementById('sets').value; saved += ', "playTo":' + document.getElementById('playTo').value; if(document.getElementById('cap') == '') saved += ', "pointCap":-1, '; else saved += ', "pointCap":' + document.getElementById('cap').value + ', '; if(Android != null) { Android.addStartingData(saved); Android.loadForm(lineupForm); //window.location.href = lineupForm; } }
JavaScript
0
@@ -788,49 +788,8 @@ oid. -addStartingData(saved);%0D%0A Android. load @@ -793,16 +793,23 @@ oadForm( +saved, lineupFo
6e92112b76d7307f99d49e2d4319cd181d1dd96e
Remove yeoman greeting
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var AppengineGenerator = module.exports = function AppengineGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(AppengineGenerator, yeoman.generators.Base); AppengineGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [{ name: 'appId', message: 'What is the application ID?', default: 'new-application' }]; this.prompt(prompts, function (props) { this.appId = props.appId; cb(); }.bind(this)); }; AppengineGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); }; AppengineGenerator.prototype.AppEngineFiles = function AppEngineFiles() { this.template('app.yaml'); this.copy('index.yaml'); }; AppengineGenerator.prototype.StaticFiles = function StaticFiles() { this.mkdir('assets'); this.copy('assets/favicon.ico'); this.copy('assets/robots.txt'); };
JavaScript
0.99901
@@ -251,16 +251,35 @@ ments);%0A + this.args = args; %0A this. @@ -514,87 +514,127 @@ %0A%0A -// have Yeoman greet the user.%0A console.log(this.yeoman);%0A%0A var prompts = %5B%7B%0A +this.appId = this.args%5B0%5D %7C%7C undefined;%0A%0A var prompts = %5B%5D;%0A%0A if (this.args%5B0%5D === undefined) %7B%0A prompts.push(%7B%0A @@ -648,16 +648,18 @@ appId',%0A + mess @@ -698,16 +698,18 @@ ?',%0A + default: @@ -733,84 +733,169 @@ '%0A + -%7D%5D;%0A%0A this.prompt(prompts, function (props) %7B%0A this.appId = props.appId; + %7D)%0A %7D else %7B%0A this.appId = this.args%5B0%5D;%0A %7D%0A%0A this.prompt(prompts, function (props) %7B%0A for (var prop in props) %7B%0A this%5Bprop%5D = props%5Bprop%5D;%0A %7D %0A%0A @@ -1280,66 +1280,25 @@ his. -copy('assets/favicon.ico');%0A this.copy('assets/robots.txt +directory('assets ');%0A
dcaa79a9b844dcea30eff07d074d4db274a0e100
Fix bevaviour issue for last commit
src/js/script.js
src/js/script.js
$(window).load(function () { $(document).on('change', '.btn-file :file', function () { var input = $(this) var numFiles = input.get(0).files ? input.get(0).files.length : 1 var label = input.val().replace(/\\/g, '/').replace(/.*\//, '') input.trigger('fileselect', [numFiles, label]) }) $(document).ready(function () { $('.btn-file :file').on('fileselect', function (event, numFiles, label) { //console.log(numFiles) //console.log(label) }) }) $('[data-toggle="tooltip"]').tooltip() }) $(function () { $('a').click(function (event) { // Load links in-app event.preventDefault() window.location = $(this).attr('href') }) $('.toggle-dropdown').on('click', function () { $('ul.active').removeClass('active') // Reset active class var parent = $(this).parent() // Select parent of clicked element parent.children('ul').addClass('active') // Set class 'active' to parent's child }) $('.searchForm').keyup(function () { if ($('.searchForm').val() === '') { $('#searchForm-btn-default').html('<i class="glyphicon glyphicon-search"></i>') $('#textReceiver').slideUp(600) $('#results').hide() if ($('#searchEngine-noResults').css('display') === 'block') { $('#searchEngine-noResults').slideUp('fast') } if ($('#heroSearch').hasClass('contracted')) { $('#heroSearch').removeClass('contracted') } } else { $('#heroSearch').addClass('contracted') $('html, body').animate({ scrollTop: 0 }, 'fast') $('#searchForm-btn-default').html('<img src="/assets/images/loading.svg" class="loading">') } }) var typingTimer $('.searchForm').on('keyup', function () { clearTimeout(typingTimer) typingTimer = setTimeout(doTrigger, 150) }) $('.searchForm').on('keydown', function () { clearTimeout(typingTimer) }) function doTrigger() { if ($('.searchForm').val().length > 2) { $('#searchResultsContainer').html('') $.getJSON('/ajax/search/?s=' + $('.searchForm').val(), function (data) { if (data[0] !== undefined) { if ($('#searchEngine-noResults').css('display') === 'block') { $('#searchEngine-noResults').show() } $('#searchFor').html('<h2 id="searchFor">Sökresultat för <strong>' + $('.searchForm').val() + '</strong></h2>') $('#results').show() $('#searchResult').append('<div id="searchResultsContainer"></div>') $('#searchResultsContainer').show('fast') for (var i = 0, result = data; i < result.length; i++) { var id = result[i]._id var content = '<div class="col-sm-6 col-md-4 col-lg-3" id="searchResult-' + id + '">' content += '<div class="result">' content += '<a href="/' + result[i].url + '"><div class="image" style="background-image: url(http://holdr.me/image/?w=263&h=148&random=' + id + ')"></div></a>' content += '<div class="content">' content += '<a href="/' + result[i].url + '"><h3>' + result[i].title + '</h3></a>' content += '<p>' + result[i].post.content + '</p></div>' content += '<div class="more">' content += '<span class="info">Status</span>' content += '<a href="/' + result[i].url + '" class="btn btn-primary">Läs mer</a></div></div></div>' $('#searchResultsContainer').append(content) $('#searchResult-' + id).show() $('#searchForm-btn-default').html('<i class="glyphicon glyphicon-search"></i>') } } else { // No results $('#searchForm-btn-default').html('<i class="glyphicon glyphicon-search"></i>') $('#searchEngine-noResults').show() $('#results').show() $('#searchFor').html('') $('#searchResultsContainer').show() } }) } } })
JavaScript
0
@@ -628,16 +628,65 @@ fault()%0A + if (!$(this).attr('href') === undefined) %7B%0A wind @@ -720,16 +720,22 @@ 'href')%0A + %7D%0A %7D)%0A%0A
516085bea2953b1e479fa6889d4eafe59f22f6a2
Remove apostate calls to empty handler
app/index.js
app/index.js
'use strict'; import React, { Component } from 'react'; import { AppRegistry, NavigatorIOS, BackAndroid, StatusBar, AppState, View } from 'react-native'; // SETUP / UTIL / NAV var AppSettings = require('./AppSettings'), general = require('./util/general'), logger = require('./util/logger'), // VIEWS Home = require('./views/Home'), ShuttleStop = require('./views/ShuttleStop'), SurfReport = require('./views/weather/SurfReport'), DiningList = require('./views/dining/DiningList'), DiningDetail = require('./views/dining/DiningDetail'), DiningNutrition = require('./views/dining/DiningNutrition'), NewsDetail = require('./views/news/NewsDetail'), EventDetail = require('./views/events/EventDetail'), WebWrapper = require('./views/WebWrapper'); import GeoLocationContainer from './containers/geoLocationContainer'; import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView'; import EventListView from './views/events/EventListView'; import NewsListView from './views/news/NewsListView'; import DiningListView from './views/dining/DiningListView'; import FeedbackView from './views/FeedbackView'; // NAV import NavigationBarWithRouteMapper from './views/NavigationBarWithRouteMapper'; // REDUX import { Provider } from 'react-redux'; import configureStore from './store/configureStore'; var nowucsandiego = React.createClass({ store: configureStore(), getInitialState() { return { inHome: true, }; }, componentWillMount() { AppState.addEventListener('change', this.handleAppStateChange); }, componentDidMount() { if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) { // Listen to route focus changes // Should be a better way to do this... this.refs.navRef.refs.navRef.navigationContext.addListener('willfocus', (event) => { const route = event.data.route; // Make sure renders/card refreshes are only happening when in home route if (route.id === "Home") { this.setState({inHome: true}); } else { this.setState({inHome: false}); } }); // Listen to back button on Android BackAndroid.addEventListener('hardwareBackPress', () => { //console.log(util.inspect(this.refs.navRef.refs.navRef.getCurrentRoutes())); //var route = this.refs.navRef.refs.navRef.getCurrentRoutes()[0]; if(this.state.inHome) { BackAndroid.exitApp(); return false; } else { this.refs.navRef.refs.navRef.pop(); return true; } }); } else { // Pause/resume timeouts this.refs.navRef.navigationContext.addListener('didfocus', (event) => { const route = event.data.route; // Make sure renders/card refreshes are only happening when in home route if (route.id === undefined) { //undefined is foxusing "Home"... weird I know this.setState({inHome: true}); } else { this.setState({inHome: false}); } }); // Make all back buttons use text "Back" this.refs.navRef.navigationContext.addListener('willfocus', (event) => { const route = event.data.route; route.backButtonTitle = "Back"; }); } }, componentWillUnmount() { AppState.removeEventListener('change', this.handleAppStateChange); }, render: function() { if (general.platformIOS()) { StatusBar.setBarStyle('light-content'); } if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) { return ( <Provider store={this.store}> <View style={{ flex: 1 }}> <GeoLocationContainer /> <NavigationBarWithRouteMapper ref="navRef" route={{ id: 'Home', name: 'Home', title: 'now@ucsandiego' }} renderScene={this.renderScene} /> </View> </Provider> ); } else { return ( <Provider store={this.store}> <View style={{ flex: 1 }}> <GeoLocationContainer /> <NavigatorIOS initialRoute={{ component: Home, title: AppSettings.APP_NAME, passProps: { isSimulator: this.props.isSimulator }, backButtonTitle: 'Back' }} style={{ flex: 1 }} tintColor='#FFFFFF' barTintColor='#006C92' titleTextColor='#FFFFFF' navigationBarHidden={false} translucent={true} ref="navRef" /> </View> </Provider> ); } }, renderScene: function(route, navigator, index, navState) { switch (route.id) { case 'Home': return (<Home route={route} navigator={navigator}/>); case 'ShuttleStop': return (<ShuttleStop route={route} navigator={navigator} />); case 'SurfReport': return (<SurfReport route={route} navigator={navigator} />); case 'DiningListView': return (<DiningListView route={route} navigator={navigator} />); case 'DiningDetail': return (<DiningDetail route={route} navigator={navigator} />); case 'DiningNutrition': return (<DiningNutrition route={route} navigator={navigator} />); case 'NewsDetail': return (<NewsDetail route={route} navigator={navigator} />); case 'EventDetail': return (<EventDetail route={route} navigator={navigator} />); case 'WebWrapper': return (<WebWrapper route={route} navigator={navigator} />); case 'WelcomeWeekView': return (<WelcomeWeekView route={route} navigator={navigator} />); case 'EventListView': return (<EventListView route={route} navigator={navigator} />); case 'NewsListView': return (<NewsListView route={route} navigator={navigator} />); case 'FeedbackView': return (<FeedbackView route={route} navigator={navigator} />); default: return (<Home route={route} navigator={navigator} />); } } }); module.exports = nowucsandiego;
JavaScript
0.000001
@@ -118,25 +118,14 @@ ar,%0A -%09AppState,%0A %09View%0A + %7D fr @@ -1469,103 +1469,8 @@ %7D,%0A%0A -%09componentWillMount() %7B%0A%09%09AppState.addEventListener('change', this.handleAppStateChange);%0A%09%7D,%0A%0A %09com @@ -2991,24 +2991,24 @@ ck%22;%0A%09%09%09%7D);%0A + %09%09%7D%0A%09%7D,%0A%0A%09co @@ -3008,108 +3008,8 @@ %7D,%0A%0A -%09componentWillUnmount() %7B%0A%09%09AppState.removeEventListener('change', this.handleAppStateChange);%0A%09%7D,%0A%0A %09ren
0fa0475ac1425ea3ad6703a65b775dc5dae830d2
Clarify which API key is needed
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var BoomerangGenerator = module.exports = function BoomerangGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(BoomerangGenerator, yeoman.generators.Base); BoomerangGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [{ name: 'chapterName', message: 'What is your GDG Chapter Name?' },{ name: 'chapterID', message: 'What is your GDG Chapter Google+ ID?' },{ name: 'googleAPIKey', message: 'What is your Google API Key?\n(https://code.google.com/apis/console)' },{ name: 'picasaWebID', message: 'What is your Picasa Web Album ID?\n(Must belong to Chapter Google+ ID)' }]; this.prompt(prompts, function (props) { this.chapterName = props.chapterName; this.chapterID = props.chapterID; this.googleAPIKey = props.googleAPIKey; this.picasaWebID = props.picasaWebID; cb(); }.bind(this)); }; BoomerangGenerator.prototype.app = function app() { this.copy('boomerang/_index.html','index.html'); this.mkdir('css'); this.copy('boomerang/_gdg.css', 'css/gdg.css'); this.mkdir('images'); this.copy('boomerang/_gdg_loading.gif', 'images/gdg_loading.gif'); this.mkdir('js'); this.template('boomerang/_boomerang.js', 'js/boomerang.js'); this.mkdir('lib'); this.copy('_angular.ui.min.js', 'lib/angular.ui.min.js'); this.mkdir('view'); this.copy('boomerang/_about.html','views/about.html'); this.copy('boomerang/_events.html','views/events.html'); this.copy('boomerang/_news.html','views/news.html'); this.copy('boomerang/_photos.html','views/photos.html'); this.copy('_bower.json', 'bower.json'); this.copy('_config.json', 'config.json'); this.copy('_package.json', 'package.json'); this.template('Gruntfile.js', 'Gruntfile.js'); }; BoomerangGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); };
JavaScript
0.999931
@@ -909,16 +909,17 @@ r Google ++ API Key
ac2b0ca6aaca1d84e300405e1c97030e1f299e2d
add in toast, lost in conflicts
app/template.js
app/template.js
define(['app', 'angular','text!./toast.html', 'text!./template-header.html', 'text!./template-footer.html','lodash', 'providers/realm'], function(app, ng, toastTemplate, footerHtml,_) { 'use strict'; app.directive('templateHeader', ['$rootScope', '$window', '$browser', '$document', 'authentication', '$q', function($rootScope, $window, $browser, $document, authentication, $q) { return { restrict: 'E', template: headerHtml, link: function(scope, elem) {}, controller: function($scope, $location) { var basePath = (ng.element('base').attr('href')||'').replace(/\/+$/g, ''); $rootScope.$on('$routeChangeSuccess', function(){ $window.ga('set', 'page', basePath+$location.path()); $window.ga('send', 'pageview'); }); var killWatch = $scope.$watch('user', _.debounce(function(user) { if (!user) return; require(["_slaask"], function(_slaask) { if (user.isAuthenticated) { _slaask.identify(user.name, { 'user-id' : user.userID, 'name' : user.name, 'email' : user.email, }); if(_slaask.initialized) { _slaask.slaaskSendUserInfos(); } } if(!_slaask.initialized) { _slaask.init('ae83e21f01860758210a799872e12ac4'); _slaask.initialized = true; killWatch(); } }); }, 1000)); updateSize(); ng.element($window).on('resize', updateSize); function updateSize() { $rootScope.$applyAsync(function(){ $rootScope.deviceSize = $('.device-size:visible').attr('size'); }); } $q.when(authentication.getUser()).then(function(u){ $scope.user = u; }); $scope.$on('signOut', function(){ $window.location.href = '/'; }); $scope.meetingNavCtrl = { fullPath : function(name) { return basePath + $location.path(); }, isSelected : function(name) { if(name && $scope.meetingNavCtrl.currentSelection) return name==$scope.meetingNavCtrl.currentSelection; var selected = false; var path = basePath + $location.path(); if(name) selected = selected || path.indexOf(name)===0; else selected = selected || path.indexOf('/conferences/')===0; return selected; }, hash : function() { return $location.hash(); } }; //============================================================ // // //============================================================ $scope.isTarget = function () { return $location.path().indexOf('/target/') >= 0; }; //============================================================ // // //============================================================ $scope.encodedReturnUrl = function () { return encodeURIComponent($location.absUrl()); }; //============================================================ // // //============================================================ $scope.signIn = function () { $window.location.href = authentication.accountsBaseUrl() + '/signin?returnUrl=' + $scope.encodedReturnUrl(); }; //============================================================ // // //============================================================ $scope.signOut = function () { authentication.signOut(); }; //============================================================ // // //============================================================ $scope.actionSignup = function () { var redirect_uri = $window.encodeURIComponent($location.protocol()+'://'+$location.host()+':'+$location.port()+'/'); $window.location.href = 'https://accounts.cbd.int/signup?redirect_uri='+redirect_uri; }; //============================================================ // // //============================================================ $scope.password = function () { $window.location.href = authentication.accountsBaseUrl() + '/password?returnurl=' + $scope.encodedReturnUrl(); }; //============================================================ // // //============================================================ $scope.profile = function () { $window.location.href = authentication.accountsBaseUrl() + '/profile?returnurl=' + $scope.encodedReturnUrl(); }; } }; }]); app.directive('templateFooter', [function() { return { restrict: 'E', template: footerHtml, link: function(scope, elem) {}, controller: function($scope, $location) {} }; }]); });
JavaScript
0.000014
@@ -162,16 +162,27 @@ emplate, +headerHtml, footerH @@ -315,16 +315,42 @@ ', '$q', +'toastr','$templateCache', %0A @@ -450,16 +450,38 @@ on, $q +,toastr,$templateCache ) %7B%0A @@ -648,24 +648,105 @@ location) %7B%0A + $templateCache.put(%22directives/toast/toast.html%22, toastTemplate); %0A @@ -6122,32 +6122,776 @@ %7D;%0A%0A + //==============================%0A //%0A //==============================%0A $rootScope.$on(%22showInfo%22, function(evt, msg) %7B%0A toastr.info(msg);%0A %7D);%0A%0A //==============================%0A //%0A //==============================%0A $rootScope.$on(%22showWarning%22, function(evt, msg) %7B%0A toastr.warning(msg);%0A %7D);%0A%0A //==============================%0A //%0A //==============================%0A $rootScope.$on(%22showSuccess%22, function(evt, msg) %7B%0A toastr.success(msg);%0A %7D);%0A%0A //==============================%0A //%0A //==============================%0A $rootScope.$on(%22showError%22, function(evt, msg) %7B%0A toastr.error(msg);%0A %7D);%0A%0A %7D%0A
f2935c4ec0cd2d3d80377155e9ad00eac6750c34
Fix Safari JS error after uglify
webpack.config.production.js
webpack.config.production.js
const webpack = require('webpack') const merge = require('webpack-merge') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const config = require('./webpack.config') // TODO Tree shaking module.exports = merge(config, { devtool: false, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), }), new UglifyJsPlugin({ uglifyOptions: { compress: { drop_console: true, }, }, }), new BundleAnalyzerPlugin(), ], })
JavaScript
0.000001
@@ -543,24 +543,235 @@ %0A %7D,%0A + output: %7B%0A // Fix Safari error:%0A // SyntaxError: Invalid regular expression: missing terminating %5D for character class%0A ascii_only: process.env.TARGET === 'safari',%0A %7D,%0A %7D,%0A
f5210cfb8a2f57de3a3ebe8afbbe2d965220f2b3
Make LESS prompt mostly function
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var _ = require('lodash'); _.str = require('underscore.string'); _.mixin(_.str.exports()); var DrupalBootstrapThemeGenerator = module.exports = function DrupalBootstrapThemeGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); // determine theme name from cwd and form a theme name according to Drupal standards this.dirName = path.basename(process.cwd()); this.themeName = _(_.slugify(this.dirName)).underscored(); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(DrupalBootstrapThemeGenerator, yeoman.generators.Base); DrupalBootstrapThemeGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [ { name: 'themeDescription', message: 'Please provide a description for your theme' }, { name: 'themeUsesLESS', message: 'Do you want to use super awesome LESS instead of plain old CSS?', type: 'confirm', default: true }, { name: 'themeUsesCoffee', message: 'Do you want to use super awesome Coffee Script instead of plain old Javascript?', type: 'confirm', default: true } ]; this.prompt(prompts, function (props) { this.themeDescription = props.themeDescription; this.themeDrupalVersion = props.themeDrupalVersion; // the prompts aren't actually going to do anything for now. this.themeUsesLESS = true; this.themeUsesCoffee = true; cb(); }.bind(this)); }; DrupalBootstrapThemeGenerator.prototype.app = function app() { this.mkdir('css'); this.mkdir('less'); this.mkdir('less/base'); this.mkdir('images'); this.mkdir('js'); this.mkdir('coffee'); this.mkdir('templates'); this.template('_gruntfile.js', 'Gruntfile.js'); this.template('bootstrap_subtheme/_bootstrap_subtheme.info', this.themeName + '.info'); this.copy('bootstrap_subtheme/less/bootstrap.less', 'less/base/bootstrap.less'); this.copy('bootstrap_subtheme/less/responsive.less', 'less/base/responsive.less'); this.copy('bootstrap_subtheme/less/variables.less', 'less/variables.less'); this.copy('bootstrap_subtheme/less/overrides.less', 'less/overrides.less'); this.copy('bootstrap_subtheme/less/style.less', 'less/style.less'); this.template('_script.coffee', 'coffee/script.coffee'); this.copy('_package.json', 'package.json'); this.copy('_bower.json', 'bower.json'); }; DrupalBootstrapThemeGenerator.prototype.projectfiles = function projectfiles() { this.copy('editorconfig', '.editorconfig'); this.copy('jshintrc', '.jshintrc'); };
JavaScript
0.000001
@@ -1720,20 +1720,22 @@ hemeUses -LESS +Coffee = true; @@ -1753,29 +1753,42 @@ hemeUses -Coffee = true +LESS = props.themeUsesLESS ;%0A%0A c @@ -1878,80 +1878,10 @@ p() +%0A %7B -%0A%0A this.mkdir('css');%0A this.mkdir('less');%0A this.mkdir('less/base'); %0A t @@ -2111,24 +2111,413 @@ '.info');%0A%0A + this.copy('_package.json', 'package.json');%0A this.copy('_bower.json', 'bower.json');%0A%7D;%0A%0ADrupalBootstrapThemeGenerator.prototype.styleFiles = function styleFiles()%0A%7B%0A this.mkdir('css');%0A this.template('_style.css', 'css/style.css');%0A %0A if(this.themeUsesLESS)%0A %7B%0A //directory structure for LESS%0A this.mkdir('less');%0A this.mkdir('less/base'); %0A%0A // bootstrap LESS files%0A this.copy( @@ -2825,24 +2825,49 @@ es.less');%0A%0A + // primary LESS file%0A this.copy( @@ -2928,159 +2928,112 @@ ');%0A -%0A this.template('_script.coffee', 'coffee/script.coffee');%0A%0A this.copy('_package.json', 'package.json');%0A this.copy('_bower.json', 'bower.json');%0A%7D; + %7D%0A else%0A %7B%0A // need to do something about the bootstrap templates if we're just using CSS%0A%0A %7D%0A%7D%0A %0A%0ADr
7163f7c0ac92241b5280161ff75eac016c104928
Add code pool setting
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var foldername = path.basename(process.cwd()); var CppSuiteGenerator = module.exports = function CppSuiteGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(CppSuiteGenerator, yeoman.generators.Base); CppSuiteGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [{ name: 'packageName', message: 'What is the name of the package?', default: 'OpenMagento' }, { name: 'moduleName', message: 'What is the name of the module:', default: 'MyModule' }, { name: 'author', message: 'Who is the creator?', default: 'Someone' }]; this.prompt(prompts, function (props) { this.packageName = props.packageName; this.moduleName = props.moduleName; this.author = props.author; cb(); }.bind(this)); };
JavaScript
0
@@ -734,26 +734,24 @@ name: ' -packageNam +namespac e',%0A @@ -780,22 +780,28 @@ name - of the packag +space you want to us e?', @@ -932,24 +932,262 @@ odule'%0A %7D, +%0A %7B%0A type: 'select',%0A name: 'codePool',%0A message: 'Which code pool do you want to use?',%0A choices: %5B%0A %7Bname: %22Local%22, value: %22local%22%7D,%0A %7Bname: %22Community%22, value: %22community%22%7D%0A %5D,%0A default: 'community'%0A %7D,%0A %7B%0A name: @@ -1317,38 +1317,34 @@ his. -packageName = props.packageNam +namespace = props.namespac e;%0A @@ -1382,16 +1382,52 @@ leName;%0A + this.codePool = props.codePool;%0A this
27ab905d4fb7b9d8b4acaceb5ef9e7d61b75d518
remove container query polyfill.
website/docusaurus.config.js
website/docusaurus.config.js
/** @type {import('@docusaurus/types').DocusaurusConfig} */ module.exports = { title: 'Unleash', tagline: 'The enterprise ready feature toggle service', url: 'https://docs.getunleash.io', baseUrl: '/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'img/favicon.ico', organizationName: 'Unleash', // Usually your GitHub org/user name. projectName: 'unleash.github.io', // Usually your repo name. trailingSlash: false, clientModules: ['./client-modules/container-query-polyfill.js'], themeConfig: { defaultMode: 'light', disableSwitch: true, respectPrefersColorScheme: false, algolia: { apiKey: '9772249a7262b377ac876853d32bd760', indexName: 'getunleash', }, navbar: { title: 'Unleash', logo: { alt: 'Unleash logo', src: 'img/logo.svg', }, items: [ { to: '/', label: 'Documentation', activeBaseRegex: '(user_guide|sdks|addons|advanced)', }, { href: 'https://www.getunleash.io/plans', label: 'Unleash Enterprise', position: 'right', }, { href: 'https://github.com/Unleash/unleash', position: 'right', className: 'header-github-link', 'aria-label': 'Unleash GitHub repository', }, ], }, prism: { additionalLanguages: [ 'java', 'swift', 'ruby', 'csharp', 'kotlin', 'php', ], }, footer: { style: 'dark', links: [ { title: 'Product', items: [ { label: 'Docs', to: '/', }, { label: 'Unleash on GitHub', href: 'https://github.com/Unleash/unleash', }, { label: 'Roadmap', href: 'https://github.com/orgs/Unleash/projects/5', }, ], }, { title: 'Community', items: [ { label: 'Stack Overflow', href: 'https://stackoverflow.com/questions/tagged/unleash', }, { label: 'Slack', href: 'https://join.slack.com/t/unleash-community/shared_invite/zt-8b6l1uut-LL67kLpIXm9bcN3~6RVaRQ', }, { label: 'Twitter', href: 'https://twitter.com/getunleash', }, ], }, ], copyright: `Copyright © ${new Date().getFullYear()} Unleash. Built with Docusaurus.`, logo: { src: 'img/logo.svg', alt: 'Unleash logo', }, }, gtag: { trackingID: 'UA-134882379-1', }, image: 'img/logo.png', }, presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarPath: require.resolve('./sidebars.js'), // Please change this to your repo. editUrl: 'https://github.com/Unleash/unleash/edit/main/website/', routeBasePath: '/', remarkPlugins: [ [ require('@docusaurus/remark-plugin-npm2yarn'), { sync: true }, ], ], }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }, ], ], plugins: [ [ '@docusaurus/plugin-client-redirects', { fromExtensions: ['html', 'htm'], redirects: [ { to: '/sdks', from: [ '/user_guide/client-sdk', '/client-sdk', '/user_guide/connect_sdk', '/sdks/community', ], }, { to: '/user_guide/api-token', from: '/deploy/user_guide/api-token', }, { to: '/sdks/unleash-proxy', from: '/user_guide/native_apps/', }, { to: '/advanced/toggle_variants', from: '/toggle_variants', }, { to: '/integrations', from: '/integrations/integrations', }, { to: '/user_guide/activation_strategy', from: '/user_guide/control_rollout', }, ], createRedirects: function (toPath) { if ( toPath.indexOf('/docs/') === -1 && toPath.indexOf('index.html') === -1 ) { return `/docs/${toPath}`; } }, }, ], ], };
JavaScript
0
@@ -472,77 +472,8 @@ se,%0A - clientModules: %5B'./client-modules/container-query-polyfill.js'%5D,%0A
685724545426d92f39802dc3e36fca1b08cf9fa8
remove breadcrumbs
website/docusaurus.config.js
website/docusaurus.config.js
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable no-undef */ // eslint-disable-next-line @typescript-eslint/no-var-requires const typedocConfig = require('./docusaurus.typedoc'); const lightCodeTheme = require('prism-react-renderer/themes/github'); const darkCodeTheme = require('prism-react-renderer/themes/vsDark'); /** @type {import('@docusaurus/types').Config} */ const config = { title: 'React DayPicker', tagline: 'Customizable date picker component for React', url: 'https://react-day-picker.js.org', baseUrl: '/', favicon: 'images/favicon.png', organizationName: 'gpbl', projectName: 'react-day-picker', clientModules: [ require.resolve('react-day-picker/dist/style.css'), require.resolve('@codesandbox/sandpack-react/dist/index.css') ], themeConfig: { image: 'images/favicon.png', navbar: require('./docusaurus.navbar.js'), editUrl: 'https://github.com/gpbl/react-day-picker/edit/master/website/', prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme } }, presets: [ [ '@docusaurus/preset-classic', { docs: { sidebarPath: require.resolve('./docusaurus.sidebars.js'), routeBasePath: '/' }, gtag: { trackingID: 'UA-68185118-1' }, theme: { customCss: require.resolve('./src/custom.css') } } ] ], plugins: [['docusaurus-plugin-typedoc', typedocConfig]] }; module.exports = config;
JavaScript
0
@@ -1,24 +1,40 @@ +// @ts-check */%0A /* eslint-disable @types @@ -61,24 +61,24 @@ requires */%0A - /* eslint-di @@ -353,16 +353,335 @@ ark');%0A%0A +/** @type %7Bimport('@docusaurus/preset-classic').Options%7D */%0Aconst presetClassicConfig = %7B%0A docs: %7B%0A sidebarPath: require.resolve('./docusaurus.sidebars.js'),%0A routeBasePath: '/',%0A breadcrumbs: false%0A %7D,%0A gtag: %7B trackingID: 'UA-68185118-1' %7D,%0A theme: %7B customCss: require.resolve('./src/custom.css') %7D%0A%7D;%0A%0A /** @typ @@ -1139,24 +1139,52 @@ meConfig: %7B%0A + hideableSidebar: false,%0A image: ' @@ -1413,21 +1413,9 @@ s: %5B -%0A %5B%0A +%5B '@do @@ -1443,270 +1443,29 @@ ic', -%0A %7B%0A docs: %7B%0A sidebarPath: require.resolve('./docusaurus.sidebars.js'),%0A routeBasePath: '/'%0A %7D,%0A gtag: %7B trackingID: 'UA-68185118-1' %7D,%0A theme: %7B customCss: require.resolve('./src/custom.css') %7D%0A %7D%0A %5D%0A + presetClassicConfig%5D %5D,%0A
6a8b5457c243bf934533c73a6024a0360ce4922d
Remove codepush from setup
app/setup.js
app/setup.js
import React from 'react'; import { View, StatusBar, Alert, AsyncStorage } from 'react-native'; import { setJSExceptionHandler } from 'react-native-exception-handler'; import RNExitApp from 'react-native-exit-app'; // CODE PUSH import codePush from 'react-native-code-push'; // REDUX import { Provider } from 'react-redux'; import configureStore from './store/configureStore'; import Main from './main'; import general from './util/general'; import logger from './util/logger'; const codePushOptions = { checkFrequency: codePush.CheckFrequency.ON_APP_RESUME, installMode: codePush.InstallMode.ON_NEXT_RESTART }; class CampusMobileSetup extends React.Component { constructor(props) { super(props); this.state = { store: configureStore({}, this.finishLoading), isLoading: true, }; } finishLoading = () => { this.setState({ isLoading: false }); const errorHandler = (e, isFatal) => { if (isFatal) { AsyncStorage.clear(); var errorStr = 'Crash: ' + e.name + ': ' + e.message, errorStack; try { errorStack = e.stack.replace(/.*\n/,'').replace(/\n.*/g, '').trim(); errorStr += ' ' + errorStack; } catch (stackErr) { logger.log('Error: ' + stackErr); } logger.trackException(errorStr, isFatal); Alert.alert( 'Unexpected error occurred', 'Please try restarting the app. If the app is still crashing, please keep an eye out for an update or try again later.', [{ text: 'Okay', onPress: () => { RNExitApp.exitApp(); } }] ); } else { console.log(e); // So that we can see it in the ADB logs in case of Android if needed } }; setJSExceptionHandler(errorHandler, true); } render() { if (general.platformIOS()) { StatusBar.setBarStyle('light-content'); } else if (general.platformAndroid()) { StatusBar.setBackgroundColor('#101d32', false); } let mainApp = <View />; if (this.state.isLoading) { return ( <View /> ); } else { return ( <Provider store={this.state.store}> <Main /> </Provider> ); } } } CampusMobileSetup = codePush(codePushOptions)(CampusMobileSetup); module.exports = CampusMobileSetup;
JavaScript
0.000001
@@ -213,69 +213,8 @@ ';%0A%0A -// CODE PUSH%0Aimport codePush from 'react-native-code-push';%0A%0A // R @@ -218,16 +218,16 @@ / REDUX%0A + import %7B @@ -418,143 +418,8 @@ ';%0A%0A -const codePushOptions = %7B checkFrequency: codePush.CheckFrequency.ON_APP_RESUME, installMode: codePush.InstallMode.ON_NEXT_RESTART %7D;%0A%0A clas @@ -758,11 +758,11 @@ %09%09%09%09 -var +let err @@ -806,23 +806,26 @@ .message -, +; %0A%09%09%09%09 -%09 +let errorSta @@ -1892,74 +1892,8 @@ %0A%7D%0A%0A -CampusMobileSetup = codePush(codePushOptions)(CampusMobileSetup);%0A modu
fa41444ed59effd9e43045e750ccc05b2a586fe9
Fix file open via CLI
main/launch.js
main/launch.js
import BrowserWindow from 'browser-window'; import path from 'path'; import { emptyNotebook, emptyCodeCell, appendCell } from 'commutable'; import { fromJS } from 'immutable'; import fs from 'fs'; export function launch(notebook, filename) { let win = new BrowserWindow({ width: 800, height: 1000, // frame: false, darkTheme: true, title: !filename ? 'Untitled' : path.relative('.', filename.replace(/.ipynb$/, '')), }); const index = path.join(__dirname, '..', 'index.html'); win.loadURL(`file://${index}`); // When the page finishes loading, send the notebook data via IPC win.webContents.on('did-finish-load', function() { win.webContents.send('main:load', { notebook: notebook.toJS(), filename }); }); // Emitted when the window is closed. win.on('closed', () => { win = null; }); return win; } export function launchNewNotebook(kernelspec) { // TODO: This needs to create a new notebook using the kernelspec that // was specified return Promise.resolve(launch( appendCell(emptyNotebook, emptyCodeCell) .set('kernelspec', fromJS(kernelspec)))); } export function launchFilename(filename) { if (!filename) { return Promise.resolve(launchNewNotebook()); } return new Promise((resolve, reject) => { fs.readFile(filename, {}, (err, data) => { if (err) { reject(err); } else { launch(fromJS(JSON.parse(data)), filename); } }); }); }
JavaScript
0
@@ -112,16 +112,24 @@ pendCell +, fromJS %7D from @@ -153,18 +153,22 @@ ort -%7B fromJS %7D +* as immutable fro @@ -1103,16 +1103,26 @@ lspec', +immutable. fromJS(k @@ -1407,16 +1407,24 @@ +resolve( launch(f @@ -1457,16 +1457,17 @@ ilename) +) ;%0A
54b2eac8822fe816e348360738102d9cfd8d9ce3
fix 35-symbol-for.js
tests/35-symbol-for.js
tests/35-symbol-for.js
// 35: Symbol.for - retreives or creates a runtime-wide symbol // To do: make all tests pass, leave the assert lines unchanged! var assert = require("assert"); describe('`Symbol.for` for registering Symbols globally', function() { it('creates a new symbol (check via `typeof`)', function() { const symbolType = Symbol.for('symbol name'); assert.equal(symbolType, 'symbol'); }); it('stores the symbol in a runtime-wide registry and retreives it from it', function() { const sym = Symbol.for('new symbol'); const sym1 = Symbol.for('new symbol1'); assert.equal(sym, sym1); }); it('is different to `Symbol()` which creates a symbol every time and does not store it', function() { var globalSymbol = Symbol.for('new symbol'); var globalSymbol = Symbol('new symbol'); assert.notEqual(globalSymbol, localSymbol); }); describe('`.toString()` on a Symbol', function() { const localSymbol = Symbol('new symbol'); const symbolFromRegistry = Symbol.for('new symbol'); it('also contains the key given to `Symbol.for()`', function() { const description = localSymbol.toString; assert.equal(description, 'Symbol(new symbol)'); }); describe('NOTE: the description of two different symbols', function() { it('might be the same', function() { const localDescription = localSymbol.toString(); const fromRegistryDescription = ''+symbolFromRegistry; assert.equal(localDescription, fromRegistryDescription); }); it('but the symbols are not the same!', function() { assert.notEqual(localSymbol, symbolFromRegistry); }); }); }); });
JavaScript
0.001108
@@ -312,16 +312,23 @@ olType = + typeof Symbol. @@ -346,24 +346,27 @@ name');%0A + // assert.equa @@ -390,16 +390,56 @@ mbol');%0A + assert.equal(symbolType, 'object');%0A %7D);%0A%0A @@ -609,17 +609,16 @@ w symbol -1 ');%0A%0A @@ -803,36 +803,35 @@ mbol');%0A var -g lo -b +c alSymbol = Symbo @@ -1176,23 +1176,28 @@ toString +() ;%0A + // assert. @@ -1234,24 +1234,82 @@ symbol)');%0A + assert.notEqual(description, 'Symbol(new symbol)');%0A %7D);%0A%0A @@ -1525,11 +1525,8 @@ n = -''+ symb @@ -1539,16 +1539,27 @@ Registry +.toString() ;%0A%0A @@ -1552,32 +1552,35 @@ ring();%0A%0A + // assert.equal(lo @@ -1621,16 +1621,84 @@ ption);%0A + assert.notEqual(localDescription, fromRegistryDescription);%0A %7D)
5911b3709fb59bd0e58314099b6daeeb590e15f0
Apply prettyfier to webpack.config.js
WebUI/webpack.config.js
WebUI/webpack.config.js
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. const path = require('path'); const process = require('process'); const fs = require('fs'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const QrcGeneratorPlugin = require('./plugins/qrc-generator'); const MinimizeWritesPlugin = require('./plugins/minimize-writes'); if (!process.env.ORBIT_BUILD_FOLDER && !fs.existsSync(path.resolve(__dirname, "qtwebchannel", "qwebchannel.js"))) { console.error(`Could not find qtwebchannel/qwebchannel.js! Webpack needs a version of "qwebchannel.js" which fits the currently used version of Qt. Our build system automatically extracts the correct version into WebUI/qtwebchannel/qwebchannel.js inside of the Orbit build directory. You have two options: - Either set the ORBIT_BUILD_FOLDER environment variable and have it point to your corresponding Orbit-build directory, (i.e. ${path.resolve(__dirname, '..', 'build_default_relwithdebinfo')}) - Or copy qtwebchannel/qwebchannel.js from your Orbit build directory into the WebUI source directory (${__dirname}). `) process.exit(); } const qwebchannel_search_path = (() => { if (process.env.ORBIT_BUILD_FOLDER) { return path.resolve(process.env.ORBIT_BUILD_FOLDER, "WebUI"); } else { return __dirname; } })(); const config = { mode: 'development', entry: { dummy: './src/dummy.js', }, output: { filename: '[name]/bundle.js', path: path.resolve(__dirname, "dist") }, resolve: { modules: [ 'node_modules', qwebchannel_search_path ] }, plugins: [ new HtmlWebpackPlugin({ chunks: ['dummy'], filename: 'dummy/index.html', title: "Dummy" }), new QrcGeneratorPlugin(), new MinimizeWritesPlugin() ], devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 9000 } }; module.exports = (env, args) => { const is_development = () => { return !args.mode || args.mode === 'development'; }; if (!is_development()) { config.mode = 'production'; config.output.path = path.resolve(process.env.ORBIT_BUILD_FOLDER, "WebUI", "dist"); config.output.publicPath = 'qrc:/webUI/'; } return config; };
JavaScript
0
@@ -185,14 +185,14 @@ ire( -' +%22 path -' +%22 );%0Ac @@ -218,17 +218,17 @@ ire( -' +%22 process -' +%22 );%0Ac @@ -249,12 +249,12 @@ ire( -'fs' +%22fs%22 );%0Ac @@ -286,17 +286,17 @@ require( -' +%22 html-web @@ -306,17 +306,17 @@ k-plugin -' +%22 );%0Aconst @@ -337,33 +337,33 @@ lugin = require( -' +%22 ./plugins/qrc-ge @@ -369,17 +369,17 @@ enerator -' +%22 );%0Aconst @@ -410,17 +410,17 @@ require( -' +%22 ./plugin @@ -440,17 +440,17 @@ ites -' +%22 );%0A%0Aif ( !pro @@ -445,16 +445,19 @@ );%0A%0Aif ( +%0A !process @@ -558,16 +558,17 @@ el.js%22)) +%0A ) %7B%0A co @@ -1044,15 +1044,15 @@ me, -'..', ' +%22..%22, %22 buil @@ -1075,17 +1075,17 @@ hdebinfo -' +%22 )%7D)%0A - @@ -1207,16 +1207,17 @@ me%7D).%0A%60) +; %0A proce @@ -1446,17 +1446,17 @@ mode: -' +%22 developm @@ -1458,17 +1458,17 @@ elopment -' +%22 ,%0A entr @@ -1532,17 +1532,17 @@ lename: -' +%22 %5Bname%5D/b @@ -1549,17 +1549,17 @@ undle.js -' +%22 ,%0A pa @@ -1593,16 +1593,17 @@ %22dist%22) +, %0A %7D,%0A @@ -1631,16 +1631,9 @@ s: %5B -%0A ' +%22 node @@ -1640,24 +1640,18 @@ _modules -',%0A +%22, qwebcha @@ -1670,14 +1670,10 @@ path -%0A %5D +, %0A %7D @@ -1865,16 +1865,17 @@ Plugin() +, %0A %5D,%0A @@ -1929,14 +1929,14 @@ me, -' +%22 dist -' +%22 ),%0A @@ -1972,18 +1972,19 @@ 9000 +, %0A %7D +, %0A%7D;%0A%0A -%0A modu @@ -2013,17 +2013,16 @@ s) =%3E %7B%0A -%0A const @@ -2085,17 +2085,17 @@ ode === -' +%22 developm @@ -2097,17 +2097,17 @@ elopment -' +%22 ;%0A %7D;%0A%0A @@ -2151,17 +2151,17 @@ .mode = -' +%22 producti @@ -2162,17 +2162,17 @@ oduction -' +%22 ;%0A co @@ -2195,32 +2195,39 @@ = path.resolve( +%0A process.env.ORBI @@ -2233,32 +2233,38 @@ IT_BUILD_FOLDER, +%0A %22WebUI%22, %22dist%22 @@ -2256,23 +2256,34 @@ %22WebUI%22, +%0A %22dist%22 +%0A );%0A c
89d7a7d852501bcd834a2b02a6dc989710848a58
Convert tabs to spaces. (need to fix vi on my linux machine.)
lib/OpenLayers/Control/PanZoom.js
lib/OpenLayers/Control/PanZoom.js
// @require: core/util.js // @require: core/alphaImage.js // // default zoom/pan controls // OpenLayers.Control.PanZoom = Class.create(); OpenLayers.Control.PanZoom.prototype = Object.extend( new OpenLayers.Control(), { // Array(...) buttons: null, initialize: function() { OpenLayers.Control.prototype.initialize.apply(this, arguments); }, draw: function() { // initialize our internal div OpenLayers.Control.prototype.draw.apply(this); // place the controls this.buttons = new Array(); var sz = new OpenLayers.Size(18,18); var xy = new OpenLayers.Pixel(4,4); var centered = new OpenLayers.Pixel(xy.x+sz.w/2, xy.y); this._addButton("panup", "north-mini.png", centered, sz); xy.y = centered.y+sz.h; this._addButton("panleft", "west-mini.png", xy, sz); this._addButton("panright", "east-mini.png", xy.addX(sz.w), sz); this._addButton("pandown", "south-mini.png", centered.addY(sz.h*2), sz); this._addButton("zoomin", "zoom-plus-mini.png", centered.addY(sz.h*3), sz); centered = centered.addY(sz.h*3); for (var i=this.map.getZoomLevels(); i--; i>=0) { centered = centered.addY(sz.h); this._addButton("zoomLevel"+i, "zoom-world-mini.png", centered, sz); } this._addButton("zoomout", "zoom-minus-mini.png", centered.addY(sz.h), sz); return this.div; }, _addButton:function(id, img, xy, sz) { var imgLocation = OpenLayers.Util.getImagesLocation() + img; // var btn = new ol.AlphaImage("_"+id, imgLocation, xy, sz); var btn = OpenLayers.Util.createImage( imgLocation, sz, xy, "absolute", "OpenLayers_Control_PanZoom_" + id ); //we want to add the outer div this.div.appendChild(btn); btn.onmousedown = this.buttonDown.bindAsEventListener(btn); btn.ondblclick = this.doubleClick.bindAsEventListener(btn); btn.action = id; btn.map = this.map; //we want to remember/reference the outer div this.buttons.push(btn); return btn; }, doubleClick: function (evt) { Event.stop(evt); }, buttonDown: function (evt) { if (this.action.startsWith("zoomLevel")) { this.map.zoomTo(parseInt(this.action.substr(9,this.action.length))); } switch (this.action) { case "zoomLevel0": this.map.zoomExtent(); break; case "panup": var resolution = this.map.getResolution(); var center = this.map.getCenter(); this.map.setCenter( new OpenLayers.LatLon(center.lat + (resolution * 50), center.lon ) ); break; case "pandown": var resolution = this.map.getResolution(); var center = this.map.getCenter(); this.map.setCenter( new OpenLayers.LatLon(center.lat - (resolution * 50), center.lon ) ); break; case "panleft": var resolution = this.map.getResolution(); var center = this.map.getCenter(); this.map.setCenter( new OpenLayers.LatLon(center.lat, center.lon - (resolution * 50) ) ); break; case "panright": var resolution = this.map.getResolution(); var center = this.map.getCenter(); this.map.setCenter( new OpenLayers.LatLon(center.lat, center.lon + (resolution * 50) ) ); break; case "zoomin": this.map.zoomIn(); break; case "zoomout": this.map.zoomOut(); break; case "zoomextents": this.map.zoomExtent(); break; } Event.stop(evt); }, destroy: function() { OpenLayers.Control.prototype.destroy.apply(this, arguments); for(i=0; i<this.buttons.length; i++) { this.buttons[i].map = null; } } });
JavaScript
0.998855
@@ -1204,10 +1204,20 @@ ) %7B%0A -%09%09 + cent @@ -1256,9 +1256,12 @@ -%09 + this
c15ad03e2dbb86a55ea82ac19475f28db4885f99
Update LoginView.js
src/routes/Login/components/LoginView.js
src/routes/Login/components/LoginView.js
import React, { Component, PropTypes } from 'react' import { Input, Icon, Row, Col, Button } from 'antd' import { Link } from 'react-router' import { API } from 'CONSTANT/globals' import handleChange from 'UTIL/handleChange' import 'STYLE/login.scss' export default class LoginView extends Component { constructor(props) { super(props) this.state = { isLogin: 'false', userName: '', pswd: '', vcode: '', } this.handleChange = handleChange.bind(this) this.reloadCode = this.reloadCode.bind(this) } emitEmptyName = () => { this.userNameInput.focus() this.setState({ userName: '' }) } emitEmptyPswd = () => { this.pswdInput.focus() this.setState({ pswd: '' }) } reloadCode() { this.props.setSessionID() } componentWillMount() { this.reloadCode() } handleSubmit() { const showHome = () => { this.props.router.push(API.CONTENTNAME + '/' + window.globalConfig.HOME_PATH) } this.props.validateLogin(this.state, showHome) } render() { const { userName, pswd, vcode } = this.state const suffixName = userName ? <Icon type="close-circle" onClick={this.emitEmptyName} /> : null const suffixPswd = pswd ? <Icon type="close-circle" onClick={this.emitEmptyPswd} /> : null return ( <div className="Login"> <div className="loginBox"> <div className="row"> <Input placeholder="请输入用户名" prefix={<Icon type="user" />} suffix={suffixName} value={userName} name="userName" size="large" onChange={this.handleChange} ref={node => this.userNameInput = node} /> </div> <div className="row" style={{marginTop: '15px'}}> <Input placeholder="请输入密码" type="password" prefix={<Icon type="lock" />} suffix={suffixPswd} value={pswd} name="pswd" size="large" onChange={this.handleChange} ref={node => this.pswdInput = node} /> </div> <div className="row" style={{marginTop: '15px'}}> <Row> <Col span={18}> <Input placeholder="请输入验证码" value={vcode} name="vcode" size="large" onChange={this.handleChange} /> </Col> <Col span={4}> <img style={{height: '32px', width: '90px', marginLeft: '10px'}} src={this.props.vcodeSrc} onClick={this.reloadCode} /> </Col> </Row> </div> <div className="row" style={{marginTop: '15px', textAlign: 'center'}}> <Button type="primary" size="large" onClick={(e) => this.handleSubmit()}>立即登录</Button> </div> </div> <div className='content-cell'> <Row> <Col span={12}> {this.state.userName} ~ {this.state.pswd} ~ {this.state.vcode} <span style={{lineHeight: '28px'}}>Triple结果: {this.props.count}</span> </Col> <Col span={8}> <Button type="primary" onClick={this.props.triple}> 点击增加 </Button> </Col> <Col span={4}> <Button type="primary" style={{marginleft: '20px'}}> <Link to='/inmanage/message'>下一页</Link> </Button> </Col> </Row> </div> </div> ) } }
JavaScript
0.000001
@@ -966,24 +966,270 @@ PATH)%0A %7D%0A + if (this.state.userName.trim() == '') %7B%0A message.error('%E8%AF%B7%E8%BE%93%E5%85%A5%E7%94%A8%E6%88%B7%E5%90%8D%EF%BC%81')%0A %7D else if (this.state.pswd.trim() == '') %7B%0A message.error('%E8%AF%B7%E8%BE%93%E5%85%A5%E5%AF%86%E7%A0%81%EF%BC%81')%0A %7D else if (this.state.vcode.trim() == '') %7B%0A message.error('%E8%AF%B7%E8%BE%93%E5%85%A5%E9%AA%8C%E8%AF%81%E7%A0%81%EF%BC%81')%0A %7D else %7B%0A this.pro @@ -1267,16 +1267,22 @@ owHome)%0A + %7D%0A %7D%0A%0A r @@ -3980,8 +3980,9 @@ )%0A %7D%0A%0A%7D +%0A
a09cdd8aa878263c11d5c36b8bd3e193ef375710
fix async part 1
discordJs/util.js
discordJs/util.js
const FS = require('fs'); module.exports = { // prints id of the user getId: function(message) { return message.channel.send(message.author.id); }, getRandomInt: function(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }, addCoins: function(message) { // 86400 var path = '/tmp/' + message.author.id + ".json"; if (FS.existsSync(path)) { var readFile = FS.readFile(path,'utf8', function(err){ if (err) { return console.log(err); } }); var obj = JSON.parse(readFile); var gain = module.exports.getRandomInt(50, 500); obj.coins = Number(obj.coins) + Number(gain); FS.writeFile(path, JSON.stringify(obj),function(err){ if (err) { return console.log(err); } }); message.channel.send("You received " + gain + " Coins !!!!"); message.channel.send("You now have " + obj.coins + " coins in your account."); } else { var ts = module.exports.getTimestamp(); FS.writeFile(path, '{"coins":"250","timestamp":"' + ts + '"}',function(err){ if (err) { return console.log(err); } }); message.channel.send("Mako created a bank account for you !"); message.channel.send("You received 250 Coins !!!!"); } }, removeCoins: function(ammount) { }, getTimestamp: function() { var ts = Math.floor(Date.now() / 1000); return ts; }, getCredits: function(message) { var path = '/tmp/' + message.author.id + ".json"; var obj; if (FS.existsSync(path)) { var readFile = FS.readFile(path); obj = JSON.parse(readFile); message.channel.send(message.author + ' you have ' + obj.coins); } else { message.channel.send('You need a bank account to use this command!\nPlease type <mako wage> to create one.'); } }, getHours: function(seconds) { console.log('seconds ' + seconds); var minutes = seconds / 60; minutes = Math.floor(minutes); var hours = minutes / 60; hours = Math.floor(hours); console.log('minutes ' + minutes); console.log('hours ' + hours); seconds = seconds % 60; minutes = minutes % 60; hours = hours % 60; console.log('minutes ' + minutes); console.log('hours ' + hours); // hours = 24 - hours; // minutes = 60 -minutes; // seconds = 60 - seconds; var time = '' + hours + ':' + minutes + ':' + seconds + ''; return time; }, writeObjProperty: function(message, propertyName, propertyValue) { var path = '/tmp/' + message.author.id + '.json'; if (FS.existsSync(path) == true) { var readFile = FS.readFile(path); var obj = JSON.parse(readFile); obj[propertyName] = propertyValue; FS.writeFile(path, JSON.stringify(obj),function(err){ if (err) { return console.log(err); } }); } else { FS.writeFile(path,function(err){ if (err) { return console.log(err); } }); } }, readObjProperty: function(message, propertyName) { var path = '/tmp/' + message.author.id + '.json'; if (FS.existsSync(path) == true) { var readFile = FS.readFile(path); var obj = JSON.parse(readFile); if (typeof obj[propertyName] == 'undefined') { console.log('propertyName does not exist'); return null; } else { return obj[propertyName]; } } else { console.log('file does not exist'); return null; } } };
JavaScript
0.000011
@@ -1635,32 +1635,135 @@ FS.readFile(path +,'utf8', function(err)%7B%0A if (err) %7B%0A return console.log(err);%0A %7D%0A %7D );%0A obj = J @@ -2795,32 +2795,135 @@ FS.readFile(path +,'utf8', function(err)%7B%0A if (err) %7B%0A return console.log(err);%0A %7D%0A %7D );%0A var obj
c4644a10eaf115b0ddd88acc03e2ae6a516b92b4
Fix annotator regressions.
nodes/text/text_view.js
nodes/text/text_view.js
var DocumentNode = require('../node'); var Document = require("substance-document"); var Annotator = Document.Annotator; // Substance.Text.View // ----------------- // // Manipulation interface shared by all textish types (paragraphs, headings) // This behavior can overriden by the concrete node types var TextView = function(node) { DocumentNode.View.call(this, node); this.$el.addClass('content-node text'); this.$el.attr('id', this.node.id); }; TextView.Prototype = function() { // Rendering // ============================= // this.render = function() { this.content = $('<div class="content">')[0]; this.$el.append(this.content); this.renderContent(); return this; }; this.dispose = function() { console.log('disposing paragraph view'); this.stopListening(); }; this.renderContent = function() { var el = document.createTextNode(this.node.content+" "); this.content.appendChild(el); }; this.insert = function(pos, str) { var range = this.getDOMPosition(pos); var textNode = range.startContainer; var offset = range.startOffset; var text = textNode.textContent; text = text.substring(0, offset) + str + text.substring(offset); textNode.textContent = text; }; this.delete = function(pos, length) { var range = this.getDOMPosition(pos); var textNode = range.startContainer; var offset = range.startOffset; var text = textNode.textContent; text = text.substring(0, offset) + text.substring(offset+length); textNode.textContent = text; }; this.getCharPosition = function(el, offset) { // lookup the given element and compute a // the corresponding char position in the plain document var range = document.createRange(); range.setStart(this.content.childNodes[0], 0); range.setEnd(el, offset); var str = range.toString(); return Math.min(this.node.content.length, str.length); }; // Returns the corresponding DOM element position for the given character // -------- // // A DOM position is specified by a tuple of element and offset. // In the case of text nodes it is a TEXT element. this.getDOMPosition = function(charPos) { if (this.content === undefined) { throw new Error("Not rendered yet."); } var range = document.createRange(); if (this.node.content.length === 0) { range.setStart(this.content.childNodes[0], 0); return range; } // otherwise look for the containing node in DFS order // TODO: this could be optimized using some indexing or caching? var stack = [this.content]; while(stack.length > 0) { var el = stack.pop(); if (el.nodeType === Node.TEXT_NODE) { var text = el; if (text.length >= charPos) { range.setStart(el, charPos); return range; } else { charPos -= text.length; } } else if (el.childNodes.length > 0) { // push in reverse order to have a left bound DFS for (var i = el.childNodes.length - 1; i >= 0; i--) { stack.push(el.childNodes[i]); } } } throw new Error("should not reach here"); }; var createAnnotationElement = function(entry) { var el = document.createElement("SPAN"); el.classList.add("annotation"); el.classList.add(entry.type); el.setAttribute("id", entry.id); return el; }; this.renderAnnotations = function(annotations) { var text = this.node.content; var fragment = document.createDocumentFragment(); var fragmenter = new Annotator.Fragmenter(fragment, text, annotations); fragmenter.onText = function(context, text) { context.appendChild(document.createTextNode(text)); }; fragmenter.onEnter = function(context, entry) { context.appendChild(createAnnotationElement(entry)); }; // this calls onText and onEnter in turns... fragmenter.start(fragment, text, annotations); // append a trailing white-space to improve the browser's behaviour with softbreaks at the end // of a node. fragment.appendChild(document.createTextNode(" ")); // set the content this.content.innerHTML = ""; this.content.appendChild(fragment); }; }; TextView.Prototype.prototype = DocumentNode.View.prototype; TextView.prototype = new TextView.Prototype(); module.exports = TextView;
JavaScript
0.000001
@@ -3766,83 +3766,131 @@ ion( -context, entry) %7B%0A context.appendChild(createAnnotationElement(entry)) +entry, parentContext) %7B%0A var el = createAnnotationElement(entry);%0A parentContext.appendChild(el);%0A return el ;%0A